Regenerate.
[bpt/emacs.git] / man / calc.texi
CommitLineData
d7b8e6c6
EZ
1\input texinfo @c -*-texinfo-*-
2@comment %**start of header (This is for running Texinfo on a region.)
3@c smallbook
4@setfilename ../info/calc
5@c [title]
6@settitle GNU Emacs Calc 2.02 Manual
7@setchapternewpage odd
8@comment %**end of header (This is for running Texinfo on a region.)
9
10@tex
11% Some special kludges to make TeX formatting prettier.
12% Because makeinfo.c exists, we can't just define new commands.
13% So instead, we take over little-used existing commands.
14%
15% Redefine @cite{text} to act like $text$ in regular TeX.
16% Info will typeset this same as @samp{text}.
17\gdef\goodtex{\tex \let\rm\goodrm \let\t\ttfont \turnoffactive}
18\gdef\goodrm{\fam0\tenrm}
19\gdef\cite{\goodtex$\citexxx}
20\gdef\citexxx#1{#1$\Etex}
21\global\let\oldxrefX=\xrefX
22\gdef\xrefX[#1]{\begingroup\let\cite=\dfn\oldxrefX[#1]\endgroup}
23%
24% Redefine @i{text} to be equivalent to @cite{text}, i.e., to use math mode.
25% This looks the same in TeX but omits the surrounding ` ' in Info.
26\global\let\i=\cite
27%
28% Redefine @c{tex-stuff} \n @whatever{info-stuff}.
29\gdef\c{\futurelet\next\mycxxx}
30\gdef\mycxxx{%
31 \ifx\next\bgroup \goodtex\let\next\mycxxy
32 \else\ifx\next\mindex \let\next\relax
33 \else\ifx\next\kindex \let\next\relax
34 \else\ifx\next\starindex \let\next\relax \else \let\next\comment
35 \fi\fi\fi\fi \next
36}
37\gdef\mycxxy#1#2{#1\Etex\mycxxz}
38\gdef\mycxxz#1{}
39@end tex
40
41@c Fix some things to make math mode work properly.
42@iftex
43@textfont0=@tenrm
44@font@teni=cmmi10 scaled @magstephalf @textfont1=@teni
45@font@seveni=cmmi7 scaled @magstephalf @scriptfont1=@seveni
46@font@fivei=cmmi5 scaled @magstephalf @scriptscriptfont1=@fivei
47@font@tensy=cmsy10 scaled @magstephalf @textfont2=@tensy
48@font@sevensy=cmsy7 scaled @magstephalf @scriptfont2=@sevensy
49@font@fivesy=cmsy5 scaled @magstephalf @scriptscriptfont2=@fivesy
50@font@tenex=cmex10 scaled @magstephalf @textfont3=@tenex
51@scriptfont3=@tenex @scriptscriptfont3=@tenex
52@textfont7=@tentt @scriptfont7=@tentt @scriptscriptfont7=@tentt
53@end iftex
54
55@c Fix some other things specifically for this manual.
56@iftex
57@finalout
58@mathcode`@:=`@: @c Make Calc fractions come out right in math mode
59@tocindent=.5pc @c Indent subsections in table of contents less
60@rightskip=0pt plus 2pt @c Favor short lines rather than overfull hboxes
61@tex
62\gdef\coloneq{\mathrel{\mathord:\mathord=}}
63\ifdim\parskip>17pt
64 \global\parskip=12pt % Standard parskip looks a bit too large
65\fi
66\gdef\internalBitem{\parskip=7pt\kyhpos=\tableindent\kyvpos=0pt
67\smallbreak\parsearg\itemzzy}
68\gdef\itemzzy#1{\itemzzz{#1}\relax\ifvmode\kern-7pt\fi}
69\gdef\trademark{${}^{\rm TM}$}
70\gdef\group{%
71 \par\vskip8pt\begingroup
72 \def\Egroup{\egroup\endgroup}%
73 \let\aboveenvbreak=\relax % so that nothing gets between vtop and first box
74 \def\singlespace{\baselineskip=\singlespaceskip}%
75 \vtop\bgroup
76}
77%
78%\global\abovedisplayskip=0pt
79%\global\abovedisplayshortskip=-10pt
80%\global\belowdisplayskip=7pt
81%\global\belowdisplayshortskip=2pt
82\gdef\beforedisplay{\vskip-10pt}
83\gdef\afterdisplay{\vskip-5pt}
84\gdef\beforedisplayh{\vskip-25pt}
85\gdef\afterdisplayh{\vskip-10pt}
86%
87\gdef\printindex{\parsearg\calcprintindex}
88\gdef\calcprintindex#1{%
89 \doprintindex{#1}%
90 \openin1 \jobname.#1s
91 \ifeof1{\let\s=\indexskip \csname indexsize#1\endcsname}\fi
92 \closein1
93}
94\gdef\indexskip{(This page intentionally left blank)\vfill\eject}
95\gdef\indexsizeky{\s\s\s\s\s\s\s\s}
96\gdef\indexsizepg{\s\s\s\s\s\s}
97\gdef\indexsizetp{\s\s\s\s\s\s}
98\gdef\indexsizecp{\s\s\s\s}
99\gdef\indexsizevr{}
100\gdef\indexsizefn{\s\s}
101\gdef\langle#1\rangle{\it XXX} % Avoid length mismatch with true expansion
102%
103% Ensure no indentation at beginning of sections, and avoid club paragraphs.
104\global\let\calcchapternofonts=\chapternofonts
105\gdef\chapternofonts{\aftergroup\calcfixclub\calcchapternofonts}
106\gdef\calcfixclub{\calcclubpenalty=10000\noindent}
107\global\let\calcdobreak=\dobreak
108\gdef\dobreak{{\penalty-9999\dimen0=\pagetotal\advance\dimen0by1.5in
109\ifdim\dimen0>\pagegoal\vfill\eject\fi}\calcdobreak}
110%
111\gdef\kindex{\def\indexname{ky}\futurelet\next\calcindexer}
112\gdef\tindex{\def\indexname{tp}\futurelet\next\calcindexer}
113\gdef\mindex{\let\indexname\relax\futurelet\next\calcindexer}
114\gdef\calcindexer{\catcode`\ =\active\parsearg\calcindexerxx}
115\gdef\calcindexerxx#1{%
116 \catcode`\ =10%
117 \ifvmode \indent \fi \setbox0=\lastbox \advance\kyhpos\wd0 \fixoddpages \box0
118 \setbox0=\hbox{\ninett #1}%
119 \calcindexersh{\llap{\hbox to 4em{\bumpoddpages\lower\kyvpos\box0\hss}\hskip\kyhpos}}%
120 \global\let\calcindexersh=\calcindexershow
121 \advance\clubpenalty by 5000%
122 \ifx\indexname\relax \else
123 \singlecodeindexer{#1\indexstar}%
124 \global\def\indexstar{}%
125 \fi
126 \futurelet\next\calcindexerxxx
127}
128\gdef\indexstar{}
129\gdef\bumpoddpages{\ifodd\calcpageno\hskip7.3in\fi}
130%\gdef\bumpoddpages{\hskip7.3in} % for marginal notes on right side always
131%\gdef\bumpoddpages{} % for marginal notes on left side always
132\gdef\fixoddpages{%
133\global\calcpageno=\pageno
134{\dimen0=\pagetotal
135\advance\dimen0 by2\baselineskip
136\ifdim\dimen0>\pagegoal
137\global\advance\calcpageno by 1
138\vfill\eject\noindent
139\fi}%
140}
141\gdef\calcindexershow#1{\smash{#1}\advance\kyvpos by 11pt}
142\gdef\calcindexernoshow#1{}
143\global\let\calcindexersh=\calcindexershow
144\gdef\calcindexerxxx{%
145 \ifx\indexname\relax
146 \ifx\next\kindex \global\let\calcindexersh=\calcindexernoshow \fi
147 \ifx\next\tindex \global\let\calcindexersh=\calcindexernoshow \fi
148 \fi
149 \calcindexerxxxx
150}
151\gdef\calcindexerxxxx#1{\next}
152\gdef\indexstarxx{\thinspace{\rm *}}
153\gdef\starindex{\global\let\indexstar=\indexstarxx}
154\gdef\calceverypar{%
155\kyhpos=\leftskip\kyvpos=0pt\clubpenalty=\calcclubpenalty
156\calcclubpenalty=1000\relax
157}
158\gdef\idots{{\indrm...}}
159@end tex
160@newdimen@kyvpos @kyvpos=0pt
161@newdimen@kyhpos @kyhpos=0pt
162@newcount@calcclubpenalty @calcclubpenalty=1000
163@newcount@calcpageno
164@newtoks@calcoldeverypar @calcoldeverypar=@everypar
165@everypar={@calceverypar@the@calcoldeverypar}
166@ifx@turnoffactive@undefinedzzz@def@turnoffactive{}@fi
167@ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi
168@catcode`@\=0 \catcode`\@=11
169\r@ggedbottomtrue
170\catcode`\@=0 @catcode`@\=@active
171@end iftex
172
173@ifinfo
174This file documents Calc, the GNU Emacs calculator.
175
176Copyright (C) 1990, 1991 Free Software Foundation, Inc.
177
178Permission is granted to make and distribute verbatim copies of this
179manual provided the copyright notice and this permission notice are
180preserved on all copies.
181
182@ignore
183Permission is granted to process this file through TeX and print the
184results, provided the printed document carries copying permission notice
185identical to this one except for the removal of this paragraph (this
186paragraph not being relevant to the printed manual).
187
188@end ignore
189Permission is granted to copy and distribute modified versions of this
190manual under the conditions for verbatim copying, provided also that the
191section entitled ``GNU General Public License'' is included exactly as
192in the original, and provided that the entire resulting derived work is
193distributed under the terms of a permission notice identical to this one.
194
195Permission is granted to copy and distribute translations of this manual
196into another language, under the above conditions for modified versions,
197except that the section entitled ``GNU General Public License'' may be
198included in a translation approved by the author instead of in the
199original English.
200@end ifinfo
201
202@titlepage
203@sp 6
204@center @titlefont{Calc Manual}
205@sp 4
206@center GNU Emacs Calc Version 2.02
207@c [volume]
208@sp 1
209@center January 1992
210@sp 5
211@center Dave Gillespie
212@center daveg@@synaptics.com
213@page
214
215@vskip 0pt plus 1filll
216Copyright @copyright{} 1990, 1991 Free Software Foundation, Inc.
217
218Permission is granted to make and distribute verbatim copies of
219this manual provided the copyright notice and this permission notice
220are preserved on all copies.
221
222@ignore
223Permission is granted to process this file through TeX and print the
224results, provided the printed document carries copying permission notice
225identical to this one except for the removal of this paragraph (this
226paragraph not being relevant to the printed manual).
227
228@end ignore
229Permission is granted to copy and distribute modified versions of this
230manual under the conditions for verbatim copying, provided also that the
231section entitled ``GNU General Public License'' is included exactly as
232in the original, and provided that the entire resulting derived work is
233distributed under the terms of a permission notice identical to this one.
234
235Permission is granted to copy and distribute translations of this manual
236into another language, under the above conditions for modified versions,
237except that the section entitled ``GNU General Public License'' may be
238included in a translation approved by the author instead of in the
239original English.
240@end titlepage
241
242@c [begin]
243@ifinfo
244@node Top, Getting Started,, (dir)
245@ichapter The GNU Emacs Calculator
246
247@noindent
248@dfn{Calc 2.02} is an advanced desk calculator and mathematical tool
249that runs as part of the GNU Emacs environment.
250
251This manual is divided into three major parts: "Getting Started," the
252"Calc Tutorial," and the "Calc Reference." The Tutorial introduces all
253the major aspects of Calculator use in an easy, hands-on way. The
254remainder of the manual is a complete reference to the features of the
255Calculator.
256
257For help in the Emacs Info system (which you are using to read this
258file), type @kbd{?}. (You can also type @kbd{h} to run through a
259longer Info tutorial.)
260
261@end ifinfo
262@menu
263* Copying:: How you can copy and share Calc.
264
265* Getting Started:: General description and overview.
266* Tutorial:: A step-by-step introduction for beginners.
267
268* Introduction:: Introduction to the Calc reference manual.
269* Data Types:: Types of objects manipulated by Calc.
270* Stack and Trail:: Manipulating the stack and trail buffers.
271* Mode Settings:: Adjusting display format and other modes.
272* Arithmetic:: Basic arithmetic functions.
273* Scientific Functions:: Transcendentals and other scientific functions.
274* Matrix Functions:: Operations on vectors and matrices.
275* Algebra:: Manipulating expressions algebraically.
276* Units:: Operations on numbers with units.
277* Store and Recall:: Storing and recalling variables.
278* Graphics:: Commands for making graphs of data.
279* Kill and Yank:: Moving data into and out of Calc.
280* Embedded Mode:: Working with formulas embedded in a file.
281* Programming:: Calc as a programmable calculator.
282
283* Installation:: Installing Calc as a part of GNU Emacs.
284* Reporting Bugs:: How to report bugs and make suggestions.
285
286* Summary:: Summary of Calc commands and functions.
287
288* Key Index:: The standard Calc key sequences.
289* Command Index:: The interactive Calc commands.
290* Function Index:: Functions (in algebraic formulas).
291* Concept Index:: General concepts.
292* Variable Index:: Variables used by Calc (both user and internal).
293* Lisp Function Index:: Internal Lisp math functions.
294@end menu
295
296@node Copying, Getting Started, Top, Top
297@unnumbered GNU GENERAL PUBLIC LICENSE
298@center Version 1, February 1989
299
300@display
301Copyright @copyright{} 1989 Free Software Foundation, Inc.
302675 Mass Ave, Cambridge, MA 02139, USA
303
304Everyone is permitted to copy and distribute verbatim copies
305of this license document, but changing it is not allowed.
306@end display
307
308@unnumberedsec Preamble
309
310 The license agreements of most software companies try to keep users
311at the mercy of those companies. By contrast, our General Public
312License is intended to guarantee your freedom to share and change free
313software---to make sure the software is free for all its users. The
314General Public License applies to the Free Software Foundation's
315software and to any other program whose authors commit to using it.
316You can use it for your programs, too.
317
318 When we speak of free software, we are referring to freedom, not
319price. Specifically, the General Public License is designed to make
320sure that you have the freedom to give away or sell copies of free
321software, that you receive source code or can get it if you want it,
322that you can change the software or use pieces of it in new free
323programs; and that you know you can do these things.
324
325 To protect your rights, we need to make restrictions that forbid
326anyone to deny you these rights or to ask you to surrender the rights.
327These restrictions translate to certain responsibilities for you if you
328distribute copies of the software, or if you modify it.
329
330 For example, if you distribute copies of a such a program, whether
331gratis or for a fee, you must give the recipients all the rights that
332you have. You must make sure that they, too, receive or can get the
333source code. And you must tell them their rights.
334
335 We protect your rights with two steps: (1) copyright the software, and
336(2) offer you this license which gives you legal permission to copy,
337distribute and/or modify the software.
338
339 Also, for each author's protection and ours, we want to make certain
340that everyone understands that there is no warranty for this free
341software. If the software is modified by someone else and passed on, we
342want its recipients to know that what they have is not the original, so
343that any problems introduced by others will not reflect on the original
344authors' reputations.
345
346 The precise terms and conditions for copying, distribution and
347modification follow.
348
349@iftex
350@unnumberedsec TERMS AND CONDITIONS
351@end iftex
352@ifinfo
353@center TERMS AND CONDITIONS
354@end ifinfo
355
356@enumerate
357@item
358This License Agreement applies to any program or other work which
359contains a notice placed by the copyright holder saying it may be
360distributed under the terms of this General Public License. The
361``Program'', below, refers to any such program or work, and a ``work based
362on the Program'' means either the Program or any work containing the
363Program or a portion of it, either verbatim or with modifications. Each
364licensee is addressed as ``you''.
365
366@item
367You may copy and distribute verbatim copies of the Program's source
368code as you receive it, in any medium, provided that you conspicuously and
369appropriately publish on each copy an appropriate copyright notice and
370disclaimer of warranty; keep intact all the notices that refer to this
371General Public License and to the absence of any warranty; and give any
372other recipients of the Program a copy of this General Public License
373along with the Program. You may charge a fee for the physical act of
374transferring a copy.
375
376@item
377You may modify your copy or copies of the Program or any portion of
378it, and copy and distribute such modifications under the terms of Paragraph
3791 above, provided that you also do the following:
380
381@itemize @bullet
382@item
383cause the modified files to carry prominent notices stating that
384you changed the files and the date of any change; and
385
386@item
387cause the whole of any work that you distribute or publish, that
388in whole or in part contains the Program or any part thereof, either
389with or without modifications, to be licensed at no charge to all
390third parties under the terms of this General Public License (except
391that you may choose to grant warranty protection to some or all
392third parties, at your option).
393
394@item
395If the modified program normally reads commands interactively when
396run, you must cause it, when started running for such interactive use
397in the simplest and most usual way, to print or display an
398announcement including an appropriate copyright notice and a notice
399that there is no warranty (or else, saying that you provide a
400warranty) and that users may redistribute the program under these
401conditions, and telling the user how to view a copy of this General
402Public License.
403
404@item
405You may charge a fee for the physical act of transferring a
406copy, and you may at your option offer warranty protection in
407exchange for a fee.
408@end itemize
409
410Mere aggregation of another independent work with the Program (or its
411derivative) on a volume of a storage or distribution medium does not bring
412the other work under the scope of these terms.
413
414@item
415You may copy and distribute the Program (or a portion or derivative of
416it, under Paragraph 2) in object code or executable form under the terms of
417Paragraphs 1 and 2 above provided that you also do one of the following:
418
419@itemize @bullet
420@item
421accompany it with the complete corresponding machine-readable
422source code, which must be distributed under the terms of
423Paragraphs 1 and 2 above; or,
424
425@item
426accompany it with a written offer, valid for at least three
427years, to give any third party free (except for a nominal charge
428for the cost of distribution) a complete machine-readable copy of the
429corresponding source code, to be distributed under the terms of
430Paragraphs 1 and 2 above; or,
431
432@item
433accompany it with the information you received as to where the
434corresponding source code may be obtained. (This alternative is
435allowed only for noncommercial distribution and only if you
436received the program in object code or executable form alone.)
437@end itemize
438
439Source code for a work means the preferred form of the work for making
440modifications to it. For an executable file, complete source code means
441all the source code for all modules it contains; but, as a special
442exception, it need not include source code for modules which are standard
443libraries that accompany the operating system on which the executable
444file runs, or for standard header files or definitions files that
445accompany that operating system.
446
447@item
448You may not copy, modify, sublicense, distribute or transfer the
449Program except as expressly provided under this General Public License.
450Any attempt otherwise to copy, modify, sublicense, distribute or transfer
451the Program is void, and will automatically terminate your rights to use
452the Program under this License. However, parties who have received
453copies, or rights to use copies, from you under this General Public
454License will not have their licenses terminated so long as such parties
455remain in full compliance.
456
457@item
458By copying, distributing or modifying the Program (or any work based
459on the Program) you indicate your acceptance of this license to do so,
460and all its terms and conditions.
461
462@item
463Each time you redistribute the Program (or any work based on the
464Program), the recipient automatically receives a license from the original
465licensor to copy, distribute or modify the Program subject to these
466terms and conditions. You may not impose any further restrictions on the
467recipients' exercise of the rights granted herein.
468
469@item
470The Free Software Foundation may publish revised and/or new versions
471of the General Public License from time to time. Such new versions will
472be similar in spirit to the present version, but may differ in detail to
473address new problems or concerns.
474
475Each version is given a distinguishing version number. If the Program
476specifies a version number of the license which applies to it and ``any
477later version'', you have the option of following the terms and conditions
478either of that version or of any later version published by the Free
479Software Foundation. If the Program does not specify a version number of
480the license, you may choose any version ever published by the Free Software
481Foundation.
482
483@item
484If you wish to incorporate parts of the Program into other free
485programs whose distribution conditions are different, write to the author
486to ask for permission. For software which is copyrighted by the Free
487Software Foundation, write to the Free Software Foundation; we sometimes
488make exceptions for this. Our decision will be guided by the two goals
489of preserving the free status of all derivatives of our free software and
490of promoting the sharing and reuse of software generally.
491
492@iftex
493@heading NO WARRANTY
494@end iftex
495@ifinfo
496@center NO WARRANTY
497@end ifinfo
498
499@item
500BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
501FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
502OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
503PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
504OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
505MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
506TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
507PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
508REPAIR OR CORRECTION.
509
510@item
511IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
512ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
513REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
514INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
515ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT
516LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES
517SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
518WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
519ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
520@end enumerate
521
522@node Getting Started, Tutorial, Top, Top
523@chapter Getting Started
524
525@noindent
526This chapter provides a general overview of Calc, the GNU Emacs
527Calculator: What it is, how to start it and how to exit from it,
528and what are the various ways that it can be used.
529
530@menu
531* What is Calc::
532* About This Manual::
533* Notations Used in This Manual::
534* Using Calc::
535* Demonstration of Calc::
536* History and Acknowledgements::
537@end menu
538
539@node What is Calc, About This Manual, Getting Started, Getting Started
540@section What is Calc?
541
542@noindent
543@dfn{Calc} is an advanced calculator and mathematical tool that runs as
544part of the GNU Emacs environment. Very roughly based on the HP-28/48
545series of calculators, its many features include:
546
547@itemize @bullet
548@item
549Choice of algebraic or RPN (stack-based) entry of calculations.
550
551@item
552Arbitrary precision integers and floating-point numbers.
553
554@item
555Arithmetic on rational numbers, complex numbers (rectangular and polar),
556error forms with standard deviations, open and closed intervals, vectors
557and matrices, dates and times, infinities, sets, quantities with units,
558and algebraic formulas.
559
560@item
561Mathematical operations such as logarithms and trigonometric functions.
562
563@item
564Programmer's features (bitwise operations, non-decimal numbers).
565
566@item
567Financial functions such as future value and internal rate of return.
568
569@item
570Number theoretical features such as prime factorization and arithmetic
571modulo @i{M} for any @i{M}.
572
573@item
574Algebraic manipulation features, including symbolic calculus.
575
576@item
577Moving data to and from regular editing buffers.
578
579@item
580``Embedded mode'' for manipulating Calc formulas and data directly
581inside any editing buffer.
582
583@item
584Graphics using GNUPLOT, a versatile (and free) plotting program.
585
586@item
587Easy programming using keyboard macros, algebraic formulas,
588algebraic rewrite rules, or extended Emacs Lisp.
589@end itemize
590
591Calc tries to include a little something for everyone; as a result it is
592large and might be intimidating to the first-time user. If you plan to
593use Calc only as a traditional desk calculator, all you really need to
594read is the ``Getting Started'' chapter of this manual and possibly the
595first few sections of the tutorial. As you become more comfortable with
596the program you can learn its additional features. In terms of efficiency,
597scope and depth, Calc cannot replace a powerful tool like Mathematica.
598@c Removed this per RMS' request:
599@c Mathematica@c{\trademark} @asis{ (tm)}.
600But Calc has the advantages of convenience, portability, and availability
601of the source code. And, of course, it's free!
602
603@node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
604@section About This Manual
605
606@noindent
607This document serves as a complete description of the GNU Emacs
608Calculator. It works both as an introduction for novices, and as
609a reference for experienced users. While it helps to have some
610experience with GNU Emacs in order to get the most out of Calc,
611this manual ought to be readable even if you don't know or use Emacs
612regularly.
613
614@ifinfo
615The manual is divided into three major parts:@: the ``Getting
616Started'' chapter you are reading now, the Calc tutorial (chapter 2),
617and the Calc reference manual (the remaining chapters and appendices).
618@end ifinfo
619@iftex
620The manual is divided into three major parts:@: the ``Getting
621Started'' chapter you are reading now, the Calc tutorial (chapter 2),
622and the Calc reference manual (the remaining chapters and appendices).
623@c [when-split]
624@c This manual has been printed in two volumes, the @dfn{Tutorial} and the
625@c @dfn{Reference}. Both volumes include a copy of the ``Getting Started''
626@c chapter.
627@end iftex
628
629If you are in a hurry to use Calc, there is a brief ``demonstration''
630below which illustrates the major features of Calc in just a couple of
631pages. If you don't have time to go through the full tutorial, this
632will show you everything you need to know to begin.
633@xref{Demonstration of Calc}.
634
635The tutorial chapter walks you through the various parts of Calc
636with lots of hands-on examples and explanations. If you are new
637to Calc and you have some time, try going through at least the
638beginning of the tutorial. The tutorial includes about 70 exercises
639with answers. These exercises give you some guided practice with
640Calc, as well as pointing out some interesting and unusual ways
641to use its features.
642
643The reference section discusses Calc in complete depth. You can read
644the reference from start to finish if you want to learn every aspect
645of Calc. Or, you can look in the table of contents or the Concept
646Index to find the parts of the manual that discuss the things you
647need to know.
648
649@cindex Marginal notes
650Every Calc keyboard command is listed in the Calc Summary, and also
651in the Key Index. Algebraic functions, @kbd{M-x} commands, and
652variables also have their own indices. @c{Each}
653@asis{In the printed manual, each}
654paragraph that is referenced in the Key or Function Index is marked
655in the margin with its index entry.
656
657@c [fix-ref Help Commands]
658You can access this manual on-line at any time within Calc by
659pressing the @kbd{h i} key sequence. Outside of the Calc window,
660you can press @kbd{M-# i} to read the manual on-line. Also, you
661can jump directly to the Tutorial by pressing @kbd{h t} or @kbd{M-# t},
662or to the Summary by pressing @kbd{h s} or @kbd{M-# s}. Within Calc,
663you can also go to the part of the manual describing any Calc key,
664function, or variable using @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v},
665respectively. @xref{Help Commands}.
666
667Printed copies of this manual are also available from the Free Software
668Foundation.
669
670@node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
671@section Notations Used in This Manual
672
673@noindent
674This section describes the various notations that are used
675throughout the Calc manual.
676
677In keystroke sequences, uppercase letters mean you must hold down
678the shift key while typing the letter. Keys pressed with Control
679held down are shown as @kbd{C-x}. Keys pressed with Meta held down
680are shown as @kbd{M-x}. Other notations are @key{RET} for the
681Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
682@key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
683
684(If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
685the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
686If you don't have a Meta key, look for Alt or Extend Char. You can
687also press @key{ESC} or @key{C-[} first to get the same effect, so
688that @kbd{M-x}, @kbd{ESC x}, and @kbd{C-[ x} are all equivalent.)
689
690Sometimes the @key{RET} key is not shown when it is ``obvious''
691that you must press @kbd{RET} to proceed. For example, the @key{RET}
692is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
693
694Commands are generally shown like this: @kbd{p} (@code{calc-precision})
695or @kbd{M-# k} (@code{calc-keypad}). This means that the command is
696normally used by pressing the @kbd{p} key or @kbd{M-# k} key sequence,
697but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
698
699Commands that correspond to functions in algebraic notation
700are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means
701the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
702the corresponding function in an algebraic-style formula would
703be @samp{cos(@var{x})}.
704
705A few commands don't have key equivalents: @code{calc-sincos}
706[@code{sincos}].@refill
707
708@node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
709@section A Demonstration of Calc
710
711@noindent
712@cindex Demonstration of Calc
713This section will show some typical small problems being solved with
714Calc. The focus is more on demonstration than explanation, but
715everything you see here will be covered more thoroughly in the
716Tutorial.
717
718To begin, start Emacs if necessary (usually the command @code{emacs}
719does this), and type @kbd{M-# c} (or @kbd{ESC # c}) to start the
720Calculator. (@xref{Starting Calc}, if this doesn't work for you.)
721
722Be sure to type all the sample input exactly, especially noting the
723difference between lower-case and upper-case letters. Remember,
724@kbd{RET}, @kbd{TAB}, @kbd{DEL}, and @kbd{SPC} are the Return, Tab,
725Delete, and Space keys.
726
727@strong{RPN calculation.} In RPN, you type the input number(s) first,
728then the command to operate on the numbers.
729
730@noindent
731Type @kbd{2 RET 3 + Q} to compute @c{$\sqrt{2+3} = 2.2360679775$}
732@asis{the square root of 2+3, which is 2.2360679775}.
733
734@noindent
735Type @kbd{P 2 ^} to compute @c{$\pi^2 = 9.86960440109$}
736@asis{the value of `pi' squared, 9.86960440109}.
737
738@noindent
739Type @kbd{TAB} to exchange the order of these two results.
740
741@noindent
742Type @kbd{- I H S} to subtract these results and compute the Inverse
743Hyperbolic sine of the difference, 2.72996136574.
744
745@noindent
746Type @kbd{DEL} to erase this result.
747
748@strong{Algebraic calculation.} You can also enter calculations using
749conventional ``algebraic'' notation. To enter an algebraic formula,
750use the apostrophe key.
751
752@noindent
753Type @kbd{' sqrt(2+3) RET} to compute @c{$\sqrt{2+3}$}
754@asis{the square root of 2+3}.
755
756@noindent
757Type @kbd{' pi^2 RET} to enter @c{$\pi^2$}
758@asis{`pi' squared}. To evaluate this symbolic
759formula as a number, type @kbd{=}.
760
761@noindent
762Type @kbd{' arcsinh($ - $$) RET} to subtract the second-most-recent
763result from the most-recent and compute the Inverse Hyperbolic sine.
764
765@strong{Keypad mode.} If you are using the X window system, press
766@w{@kbd{M-# k}} to get Keypad mode. (If you don't use X, skip to
767the next section.)
768
769@noindent
770Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
771``buttons'' using your left mouse button.
772
773@noindent
774Click on @key{PI}, @key{2}, and @t{y^x}.
775
776@noindent
777Click on @key{INV}, then @key{ENTER} to swap the two results.
778
779@noindent
780Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
781
782@noindent
783Click on @key{<-} to erase the result, then click @key{OFF} to turn
784the Keypad Calculator off.
785
786@strong{Grabbing data.} Type @kbd{M-# x} if necessary to exit Calc.
787Now select the following numbers as an Emacs region: ``Mark'' the
788front of the list by typing control-@kbd{SPC} or control-@kbd{@@} there,
789then move to the other end of the list. (Either get this list from
790the on-line copy of this manual, accessed by @w{@kbd{M-# i}}, or just
791type these numbers into a scratch file.) Now type @kbd{M-# g} to
792``grab'' these numbers into Calc.
793
794@group
795@example
7961.23 1.97
7971.6 2
7981.19 1.08
799@end example
800@end group
801
802@noindent
803The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
804Type @w{@kbd{V R +}} to compute the sum of these numbers.
805
806@noindent
807Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
808the product of the numbers.
809
810@noindent
811You can also grab data as a rectangular matrix. Place the cursor on
812the upper-leftmost @samp{1} and set the mark, then move to just after
813the lower-right @samp{8} and press @kbd{M-# r}.
814
815@noindent
816Type @kbd{v t} to transpose this @c{$3\times2$}
817@asis{3x2} matrix into a @c{$2\times3$}
818@asis{2x3} matrix. Type
819@w{@kbd{v u}} to unpack the rows into two separate vectors. Now type
820@w{@kbd{V R + TAB V R +}} to compute the sums of the two original columns.
821(There is also a special grab-and-sum-columns command, @kbd{M-# :}.)
822
823@strong{Units conversion.} Units are entered algebraically.
824Type @w{@kbd{' 43 mi/hr RET}} to enter the quantity 43 miles-per-hour.
825Type @w{@kbd{u c km/hr RET}}. Type @w{@kbd{u c m/s RET}}.
826
827@strong{Date arithmetic.} Type @kbd{t N} to get the current date and
828time. Type @kbd{90 +} to find the date 90 days from now. Type
829@kbd{' <25 dec 87> RET} to enter a date, then @kbd{- 7 /} to see how
830many weeks have passed since then.
831
832@strong{Algebra.} Algebraic entries can also include formulas
833or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] RET}
834to enter a pair of equations involving three variables.
835(Note the leading apostrophe in this example; also, note that the space
836between @samp{x y} is required.) Type @w{@kbd{a S x,y RET}} to solve
837these equations for the variables @cite{x} and @cite{y}.@refill
838
839@noindent
840Type @kbd{d B} to view the solutions in more readable notation.
841Type @w{@kbd{d C}} to view them in C language notation, and @kbd{d T}
842to view them in the notation for the @TeX{} typesetting system.
843Type @kbd{d N} to return to normal notation.
844
845@noindent
846Type @kbd{7.5}, then @kbd{s l a RET} to let @cite{a = 7.5} in these formulas.
847(That's a letter @kbd{l}, not a numeral @kbd{1}.)
848
849@iftex
850@strong{Help functions.} You can read about any command in the on-line
851manual. Type @kbd{M-# c} to return to Calc after each of these
852commands: @kbd{h k t N} to read about the @kbd{t N} command,
853@kbd{h f sqrt RET} to read about the @code{sqrt} function, and
854@kbd{h s} to read the Calc summary.
855@end iftex
856@ifinfo
857@strong{Help functions.} You can read about any command in the on-line
858manual. Remember to type the letter @kbd{l}, then @kbd{M-# c}, to
859return here after each of these commands: @w{@kbd{h k t N}} to read
860about the @w{@kbd{t N}} command, @kbd{h f sqrt RET} to read about the
861@code{sqrt} function, and @kbd{h s} to read the Calc summary.
862@end ifinfo
863
864Press @kbd{DEL} repeatedly to remove any leftover results from the stack.
865To exit from Calc, press @kbd{q} or @kbd{M-# c} again.
866
867@node Using Calc, History and Acknowledgements, Demonstration of Calc, Getting Started
868@section Using Calc
869
870@noindent
871Calc has several user interfaces that are specialized for
872different kinds of tasks. As well as Calc's standard interface,
873there are Quick Mode, Keypad Mode, and Embedded Mode.
874
875@c [fix-ref Installation]
876Calc must be @dfn{installed} before it can be used. @xref{Installation},
877for instructions on setting up and installing Calc. We will assume
878you or someone on your system has already installed Calc as described
879there.
880
881@menu
882* Starting Calc::
883* The Standard Interface::
884* Quick Mode Overview::
885* Keypad Mode Overview::
886* Standalone Operation::
887* Embedded Mode Overview::
888* Other M-# Commands::
889@end menu
890
891@node Starting Calc, The Standard Interface, Using Calc, Using Calc
892@subsection Starting Calc
893
894@noindent
895On most systems, you can type @kbd{M-#} to start the Calculator.
896The notation @kbd{M-#} is short for Meta-@kbd{#}. On most
897keyboards this means holding down the Meta (or Alt) and
898Shift keys while typing @kbd{3}.
899
900@cindex META key
901Once again, if you don't have a Meta key on your keyboard you can type
902@key{ESC} first, then @kbd{#}, to accomplish the same thing. If you
903don't even have an @key{ESC} key, you can fake it by holding down
904Control or @key{CTRL} while typing a left square bracket
905(that's @kbd{C-[} in Emacs notation).@refill
906
907@kbd{M-#} is a @dfn{prefix key}; when you press it, Emacs waits for
908you to press a second key to complete the command. In this case,
909you will follow @kbd{M-#} with a letter (upper- or lower-case, it
910doesn't matter for @kbd{M-#}) that says which Calc interface you
911want to use.
912
913To get Calc's standard interface, type @kbd{M-# c}. To get
914Keypad Mode, type @kbd{M-# k}. Type @kbd{M-# ?} to get a brief
915list of the available options, and type a second @kbd{?} to get
916a complete list.
917
918To ease typing, @kbd{M-# M-#} (or @kbd{M-# #} if that's easier)
919also works to start Calc. It starts the same interface (either
920@kbd{M-# c} or @w{@kbd{M-# k}}) that you last used, selecting the
921@kbd{M-# c} interface by default. (If your installation has
922a special function key set up to act like @kbd{M-#}, hitting that
923function key twice is just like hitting @kbd{M-# M-#}.)
924
925If @kbd{M-#} doesn't work for you, you can always type explicit
926commands like @kbd{M-x calc} (for the standard user interface) or
927@w{@kbd{M-x calc-keypad}} (for Keypad Mode). First type @kbd{M-x}
928(that's Meta with the letter @kbd{x}), then, at the prompt,
929type the full command (like @kbd{calc-keypad}) and press Return.
930
931If you type @kbd{M-x calc} and Emacs still doesn't recognize the
932command (it will say @samp{[No match]} when you try to press
933@key{RET}), then Calc has not been properly installed.
934
935The same commands (like @kbd{M-# c} or @kbd{M-# M-#}) that start
936the Calculator also turn it off if it is already on.
937
938@node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
939@subsection The Standard Calc Interface
940
941@noindent
942@cindex Standard user interface
943Calc's standard interface acts like a traditional RPN calculator,
944operated by the normal Emacs keyboard. When you type @kbd{M-# c}
945to start the Calculator, the Emacs screen splits into two windows
946with the file you were editing on top and Calc on the bottom.
947
948@group
949@iftex
950@advance@hsize20pt
951@end iftex
952@smallexample
953
954...
955--**-Emacs: myfile (Fundamental)----All----------------------
956--- Emacs Calculator Mode --- |Emacs Calc Mode v2.00...
9572: 17.3 | 17.3
9581: -5 | 3
959 . | 2
960 | 4
961 | * 8
962 | ->-5
963 |
964--%%-Calc: 12 Deg (Calculator)----All----- --%%-Emacs: *Calc Trail*
965@end smallexample
966@end group
967
968In this figure, the mode-line for @file{myfile} has moved up and the
969``Calculator'' window has appeared below it. As you can see, Calc
970actually makes two windows side-by-side. The lefthand one is
971called the @dfn{stack window} and the righthand one is called the
972@dfn{trail window.} The stack holds the numbers involved in the
973calculation you are currently performing. The trail holds a complete
974record of all calculations you have done. In a desk calculator with
975a printer, the trail corresponds to the paper tape that records what
976you do.
977
978In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
979were first entered into the Calculator, then the 2 and 4 were
980multiplied to get 8, then the 3 and 8 were subtracted to get @i{-5}.
981(The @samp{>} symbol shows that this was the most recent calculation.)
982The net result is the two numbers 17.3 and @i{-5} sitting on the stack.
983
984Most Calculator commands deal explicitly with the stack only, but
985there is a set of commands that allow you to search back through
986the trail and retrieve any previous result.
987
988Calc commands use the digits, letters, and punctuation keys.
989Shifted (i.e., upper-case) letters are different from lowercase
990letters. Some letters are @dfn{prefix} keys that begin two-letter
991commands. For example, @kbd{e} means ``enter exponent'' and shifted
992@kbd{E} means @cite{e^x}. With the @kbd{d} (``display modes'') prefix
993the letter ``e'' takes on very different meanings: @kbd{d e} means
994``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
995
996There is nothing stopping you from switching out of the Calc
997window and back into your editing window, say by using the Emacs
998@w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is
999inside a regular window, Emacs acts just like normal. When the
1000cursor is in the Calc stack or trail windows, keys are interpreted
1001as Calc commands.
1002
1003When you quit by pressing @kbd{M-# c} a second time, the Calculator
1004windows go away but the actual Stack and Trail are not gone, just
1005hidden. When you press @kbd{M-# c} once again you will get the
1006same stack and trail contents you had when you last used the
1007Calculator.
1008
1009The Calculator does not remember its state between Emacs sessions.
1010Thus if you quit Emacs and start it again, @kbd{M-# c} will give you
1011a fresh stack and trail. There is a command (@kbd{m m}) that lets
1012you save your favorite mode settings between sessions, though.
1013One of the things it saves is which user interface (standard or
1014Keypad) you last used; otherwise, a freshly started Emacs will
1015always treat @kbd{M-# M-#} the same as @kbd{M-# c}.
1016
1017The @kbd{q} key is another equivalent way to turn the Calculator off.
1018
1019If you type @kbd{M-# b} first and then @kbd{M-# c}, you get a
1020full-screen version of Calc (@code{full-calc}) in which the stack and
1021trail windows are still side-by-side but are now as tall as the whole
1022Emacs screen. When you press @kbd{q} or @kbd{M-# c} again to quit,
1023the file you were editing before reappears. The @kbd{M-# b} key
1024switches back and forth between ``big'' full-screen mode and the
1025normal partial-screen mode.
1026
1027Finally, @kbd{M-# o} (@code{calc-other-window}) is like @kbd{M-# c}
1028except that the Calc window is not selected. The buffer you were
1029editing before remains selected instead. @kbd{M-# o} is a handy
1030way to switch out of Calc momentarily to edit your file; type
1031@kbd{M-# c} to switch back into Calc when you are done.
1032
1033@node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
1034@subsection Quick Mode (Overview)
1035
1036@noindent
1037@dfn{Quick Mode} is a quick way to use Calc when you don't need the
1038full complexity of the stack and trail. To use it, type @kbd{M-# q}
1039(@code{quick-calc}) in any regular editing buffer.
1040
1041Quick Mode is very simple: It prompts you to type any formula in
1042standard algebraic notation (like @samp{4 - 2/3}) and then displays
1043the result at the bottom of the Emacs screen (@i{3.33333333333}
1044in this case). You are then back in the same editing buffer you
1045were in before, ready to continue editing or to type @kbd{M-# q}
1046again to do another quick calculation. The result of the calculation
1047will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
1048at this point will yank the result into your editing buffer.
1049
1050Calc mode settings affect Quick Mode, too, though you will have to
1051go into regular Calc (with @kbd{M-# c}) to change the mode settings.
1052
1053@c [fix-ref Quick Calculator mode]
1054@xref{Quick Calculator}, for further information.
1055
1056@node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
1057@subsection Keypad Mode (Overview)
1058
1059@noindent
1060@dfn{Keypad Mode} is a mouse-based interface to the Calculator.
1061It is designed for use with the X window system. If you don't
1062have X, you will have to operate keypad mode with your arrow
1063keys (which is probably more trouble than it's worth). Keypad
1064mode is currently not supported under Emacs 19.
1065
1066Type @kbd{M-# k} to turn Keypad Mode on or off. Once again you
1067get two new windows, this time on the righthand side of the screen
1068instead of at the bottom. The upper window is the familiar Calc
1069Stack; the lower window is a picture of a typical calculator keypad.
1070
1071@tex
1072\dimen0=\pagetotal%
1073\advance \dimen0 by 24\baselineskip%
1074\ifdim \dimen0>\pagegoal \vfill\eject \fi%
1075\medskip
1076@end tex
1077@smallexample
1078 |--- Emacs Calculator Mode ---
1079 |2: 17.3
1080 |1: -5
1081 | .
1082 |--%%-Calc: 12 Deg (Calcul
1083 |----+-----Calc 2.00-----+----1
1084 |FLR |CEIL|RND |TRNC|CLN2|FLT |
1085 |----+----+----+----+----+----|
1086 | LN |EXP | |ABS |IDIV|MOD |
1087 |----+----+----+----+----+----|
1088 |SIN |COS |TAN |SQRT|y^x |1/x |
1089 |----+----+----+----+----+----|
1090 | ENTER |+/- |EEX |UNDO| <- |
1091 |-----+---+-+--+--+-+---++----|
1092 | INV | 7 | 8 | 9 | / |
1093 |-----+-----+-----+-----+-----|
1094 | HYP | 4 | 5 | 6 | * |
1095 |-----+-----+-----+-----+-----|
1096 |EXEC | 1 | 2 | 3 | - |
1097 |-----+-----+-----+-----+-----|
1098 | OFF | 0 | . | PI | + |
1099 |-----+-----+-----+-----+-----+
1100@end smallexample
1101@iftex
1102@begingroup
1103@ifdim@hsize=5in
1104@vskip-3.7in
1105@advance@hsize-2.2in
1106@else
1107@vskip-3.89in
1108@advance@hsize-3.05in
1109@advance@vsize.1in
1110@fi
1111@end iftex
1112
1113Keypad Mode is much easier for beginners to learn, because there
1114is no need to memorize lots of obscure key sequences. But not all
1115commands in regular Calc are available on the Keypad. You can
1116always switch the cursor into the Calc stack window to use
1117standard Calc commands if you need. Serious Calc users, though,
1118often find they prefer the standard interface over Keypad Mode.
1119
1120To operate the Calculator, just click on the ``buttons'' of the
1121keypad using your left mouse button. To enter the two numbers
1122shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
1123add them together you would then click @kbd{+} (to get 12.3 on
1124the stack).
1125
1126If you click the right mouse button, the top three rows of the
1127keypad change to show other sets of commands, such as advanced
1128math functions, vector operations, and operations on binary
1129numbers.
1130
1131@iftex
1132@endgroup
1133@end iftex
1134Because Keypad Mode doesn't use the regular keyboard, Calc leaves
1135the cursor in your original editing buffer. You can type in
1136this buffer in the usual way while also clicking on the Calculator
1137keypad. One advantage of Keypad Mode is that you don't need an
1138explicit command to switch between editing and calculating.
1139
1140If you press @kbd{M-# b} first, you get a full-screen Keypad Mode
1141(@code{full-calc-keypad}) with three windows: The keypad in the lower
1142left, the stack in the lower right, and the trail on top.
1143
1144@c [fix-ref Keypad Mode]
1145@xref{Keypad Mode}, for further information.
1146
1147@node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
1148@subsection Standalone Operation
1149
1150@noindent
1151@cindex Standalone Operation
1152If you are not in Emacs at the moment but you wish to use Calc,
1153you must start Emacs first. If all you want is to run Calc, you
1154can give the commands:
1155
1156@example
1157emacs -f full-calc
1158@end example
1159
1160@noindent
1161or
1162
1163@example
1164emacs -f full-calc-keypad
1165@end example
1166
1167@noindent
1168which run a full-screen Calculator (as if by @kbd{M-# b M-# c}) or
1169a full-screen X-based Calculator (as if by @kbd{M-# b M-# k}).
1170In standalone operation, quitting the Calculator (by pressing
1171@kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
1172itself.
1173
1174@node Embedded Mode Overview, Other M-# Commands, Standalone Operation, Using Calc
1175@subsection Embedded Mode (Overview)
1176
1177@noindent
1178@dfn{Embedded Mode} is a way to use Calc directly from inside an
1179editing buffer. Suppose you have a formula written as part of a
1180document like this:
1181
1182@group
1183@smallexample
1184The derivative of
1185
1186 ln(ln(x))
1187
1188is
1189@end smallexample
1190@end group
1191
1192@noindent
1193and you wish to have Calc compute and format the derivative for
1194you and store this derivative in the buffer automatically. To
1195do this with Embedded Mode, first copy the formula down to where
1196you want the result to be:
1197
1198@group
1199@smallexample
1200The derivative of
1201
1202 ln(ln(x))
1203
1204is
1205
1206 ln(ln(x))
1207@end smallexample
1208@end group
1209
1210Now, move the cursor onto this new formula and press @kbd{M-# e}.
1211Calc will read the formula (using the surrounding blank lines to
1212tell how much text to read), then push this formula (invisibly)
1213onto the Calc stack. The cursor will stay on the formula in the
1214editing buffer, but the buffer's mode line will change to look
1215like the Calc mode line (with mode indicators like @samp{12 Deg}
1216and so on). Even though you are still in your editing buffer,
1217the keyboard now acts like the Calc keyboard, and any new result
1218you get is copied from the stack back into the buffer. To take
1219the derivative, you would type @kbd{a d x @key{RET}}.
1220
1221@group
1222@smallexample
1223The derivative of
1224
1225 ln(ln(x))
1226
1227is
1228
12291 / ln(x) x
1230@end smallexample
1231@end group
1232
1233To make this look nicer, you might want to press @kbd{d =} to center
1234the formula, and even @kbd{d B} to use ``big'' display mode.
1235
1236@group
1237@smallexample
1238The derivative of
1239
1240 ln(ln(x))
1241
1242is
1243% [calc-mode: justify: center]
1244% [calc-mode: language: big]
1245
1246 1
1247 -------
1248 ln(x) x
1249@end smallexample
1250@end group
1251
1252Calc has added annotations to the file to help it remember the modes
1253that were used for this formula. They are formatted like comments
1254in the @TeX{} typesetting language, just in case you are using @TeX{}.
1255(In this example @TeX{} is not being used, so you might want to move
1256these comments up to the top of the file or otherwise put them out
1257of the way.)
1258
1259As an extra flourish, we can add an equation number using a
1260righthand label: Type @kbd{d @} (1) RET}.
1261
1262@group
1263@smallexample
1264% [calc-mode: justify: center]
1265% [calc-mode: language: big]
1266% [calc-mode: right-label: " (1)"]
1267
1268 1
1269 ------- (1)
1270 ln(x) x
1271@end smallexample
1272@end group
1273
1274To leave Embedded Mode, type @kbd{M-# e} again. The mode line
1275and keyboard will revert to the way they were before. (If you have
1276actually been trying this as you read along, you'll want to press
1277@kbd{M-# 0} [with the digit zero] now to reset the modes you changed.)
1278
1279The related command @kbd{M-# w} operates on a single word, which
1280generally means a single number, inside text. It uses any
1281non-numeric characters rather than blank lines to delimit the
1282formula it reads. Here's an example of its use:
1283
1284@smallexample
1285A slope of one-third corresponds to an angle of 1 degrees.
1286@end smallexample
1287
1288Place the cursor on the @samp{1}, then type @kbd{M-# w} to enable
1289Embedded Mode on that number. Now type @kbd{3 /} (to get one-third),
1290and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
1291then @w{@kbd{M-# w}} again to exit Embedded mode.
1292
1293@smallexample
1294A slope of one-third corresponds to an angle of 18.4349488229 degrees.
1295@end smallexample
1296
1297@c [fix-ref Embedded Mode]
1298@xref{Embedded Mode}, for full details.
1299
1300@node Other M-# Commands, , Embedded Mode Overview, Using Calc
1301@subsection Other @kbd{M-#} Commands
1302
1303@noindent
1304Two more Calc-related commands are @kbd{M-# g} and @kbd{M-# r},
1305which ``grab'' data from a selected region of a buffer into the
1306Calculator. The region is defined in the usual Emacs way, by
1307a ``mark'' placed at one end of the region, and the Emacs
1308cursor or ``point'' placed at the other.
1309
1310The @kbd{M-# g} command reads the region in the usual left-to-right,
1311top-to-bottom order. The result is packaged into a Calc vector
1312of numbers and placed on the stack. Calc (in its standard
1313user interface) is then started. Type @kbd{v u} if you want
1314to unpack this vector into separate numbers on the stack. Also,
1315@kbd{C-u M-# g} interprets the region as a single number or
1316formula.
1317
1318The @kbd{M-# r} command reads a rectangle, with the point and
1319mark defining opposite corners of the rectangle. The result
1320is a matrix of numbers on the Calculator stack.
1321
1322Complementary to these is @kbd{M-# y}, which ``yanks'' the
1323value at the top of the Calc stack back into an editing buffer.
1324If you type @w{@kbd{M-# y}} while in such a buffer, the value is
1325yanked at the current position. If you type @kbd{M-# y} while
1326in the Calc buffer, Calc makes an educated guess as to which
1327editing buffer you want to use. The Calc window does not have
1328to be visible in order to use this command, as long as there
1329is something on the Calc stack.
1330
1331Here, for reference, is the complete list of @kbd{M-#} commands.
1332The shift, control, and meta keys are ignored for the keystroke
1333following @kbd{M-#}.
1334
1335@noindent
1336Commands for turning Calc on and off:
1337
1338@table @kbd
1339@item #
1340Turn Calc on or off, employing the same user interface as last time.
1341
1342@item C
1343Turn Calc on or off using its standard bottom-of-the-screen
1344interface. If Calc is already turned on but the cursor is not
1345in the Calc window, move the cursor into the window.
1346
1347@item O
1348Same as @kbd{C}, but don't select the new Calc window. If
1349Calc is already turned on and the cursor is in the Calc window,
1350move it out of that window.
1351
1352@item B
1353Control whether @kbd{M-# c} and @kbd{M-# k} use the full screen.
1354
1355@item Q
1356Use Quick Mode for a single short calculation.
1357
1358@item K
1359Turn Calc Keypad mode on or off.
1360
1361@item E
1362Turn Calc Embedded mode on or off at the current formula.
1363
1364@item J
1365Turn Calc Embedded mode on or off, select the interesting part.
1366
1367@item W
1368Turn Calc Embedded mode on or off at the current word (number).
1369
1370@item Z
1371Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
1372
1373@item X
1374Quit Calc; turn off standard, Keypad, or Embedded mode if on.
1375(This is like @kbd{q} or @key{OFF} inside of Calc.)
1376@end table
1377@iftex
1378@sp 2
1379@end iftex
1380
1381@group
1382@noindent
1383Commands for moving data into and out of the Calculator:
1384
1385@table @kbd
1386@item G
1387Grab the region into the Calculator as a vector.
1388
1389@item R
1390Grab the rectangular region into the Calculator as a matrix.
1391
1392@item :
1393Grab the rectangular region and compute the sums of its columns.
1394
1395@item _
1396Grab the rectangular region and compute the sums of its rows.
1397
1398@item Y
1399Yank a value from the Calculator into the current editing buffer.
1400@end table
1401@iftex
1402@sp 2
1403@end iftex
1404@end group
1405
1406@group
1407@noindent
1408Commands for use with Embedded Mode:
1409
1410@table @kbd
1411@item A
1412``Activate'' the current buffer. Locate all formulas that
1413contain @samp{:=} or @samp{=>} symbols and record their locations
1414so that they can be updated automatically as variables are changed.
1415
1416@item D
1417Duplicate the current formula immediately below and select
1418the duplicate.
1419
1420@item F
1421Insert a new formula at the current point.
1422
1423@item N
1424Move the cursor to the next active formula in the buffer.
1425
1426@item P
1427Move the cursor to the previous active formula in the buffer.
1428
1429@item U
1430Update (i.e., as if by the @kbd{=} key) the formula at the current point.
1431
1432@item `
1433Edit (as if by @code{calc-edit}) the formula at the current point.
1434@end table
1435@iftex
1436@sp 2
1437@end iftex
1438@end group
1439
1440@group
1441@noindent
1442Miscellaneous commands:
1443
1444@table @kbd
1445@item I
1446Run the Emacs Info system to read the Calc manual.
1447(This is the same as @kbd{h i} inside of Calc.)
1448
1449@item T
1450Run the Emacs Info system to read the Calc Tutorial.
1451
1452@item S
1453Run the Emacs Info system to read the Calc Summary.
1454
1455@item L
1456Load Calc entirely into memory. (Normally the various parts
1457are loaded only as they are needed.)
1458
1459@item M
1460Read a region of written keystroke names (like @samp{C-n a b c RET})
1461and record them as the current keyboard macro.
1462
1463@item 0
1464(This is the ``zero'' digit key.) Reset the Calculator to
1465its default state: Empty stack, and default mode settings.
1466With any prefix argument, reset everything but the stack.
1467@end table
1468@end group
1469
1470@node History and Acknowledgements, , Using Calc, Getting Started
1471@section History and Acknowledgements
1472
1473@noindent
1474Calc was originally started as a two-week project to occupy a lull
1475in the author's schedule. Basically, a friend asked if I remembered
1476the value of @c{$2^{32}$}
1477@cite{2^32}. I didn't offhand, but I said, ``that's
1478easy, just call up an @code{xcalc}.'' @code{Xcalc} duly reported
1479that the answer to our question was @samp{4.294967e+09}---with no way to
1480see the full ten digits even though we knew they were there in the
1481program's memory! I was so annoyed, I vowed to write a calculator
1482of my own, once and for all.
1483
1484I chose Emacs Lisp, a) because I had always been curious about it
1485and b) because, being only a text editor extension language after
1486all, Emacs Lisp would surely reach its limits long before the project
1487got too far out of hand.
1488
1489To make a long story short, Emacs Lisp turned out to be a distressingly
1490solid implementation of Lisp, and the humble task of calculating
1491turned out to be more open-ended than one might have expected.
1492
1493Emacs Lisp doesn't have built-in floating point math, so it had to be
1494simulated in software. In fact, Emacs integers will only comfortably
1495fit six decimal digits or so---not enough for a decent calculator. So
1496I had to write my own high-precision integer code as well, and once I had
1497this I figured that arbitrary-size integers were just as easy as large
1498integers. Arbitrary floating-point precision was the logical next step.
1499Also, since the large integer arithmetic was there anyway it seemed only
1500fair to give the user direct access to it, which in turn made it practical
1501to support fractions as well as floats. All these features inspired me
1502to look around for other data types that might be worth having.
1503
1504Around this time, my friend Rick Koshi showed me his nifty new HP-28
1505calculator. It allowed the user to manipulate formulas as well as
1506numerical quantities, and it could also operate on matrices. I decided
1507that these would be good for Calc to have, too. And once things had
1508gone this far, I figured I might as well take a look at serious algebra
1509systems like Mathematica, Macsyma, and Maple for further ideas. Since
1510these systems did far more than I could ever hope to implement, I decided
1511to focus on rewrite rules and other programming features so that users
1512could implement what they needed for themselves.
1513
1514Rick complained that matrices were hard to read, so I put in code to
1515format them in a 2D style. Once these routines were in place, Big mode
1516was obligatory. Gee, what other language modes would be useful?
1517
1518Scott Hemphill and Allen Knutson, two friends with a strong mathematical
1519bent, contributed ideas and algorithms for a number of Calc features
1520including modulo forms, primality testing, and float-to-fraction conversion.
1521
1522Units were added at the eager insistence of Mass Sivilotti. Later,
1523Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
1524expert assistance with the units table. As far as I can remember, the
1525idea of using algebraic formulas and variables to represent units dates
1526back to an ancient article in Byte magazine about muMath, an early
1527algebra system for microcomputers.
1528
1529Many people have contributed to Calc by reporting bugs and suggesting
1530features, large and small. A few deserve special mention: Tim Peters,
1531who helped develop the ideas that led to the selection commands, rewrite
1532rules, and many other algebra features; @c{Fran\c cois}
1533@asis{Francois} Pinard, who contributed
1534an early prototype of the Calc Summary appendix as well as providing
1535valuable suggestions in many other areas of Calc; Carl Witty, whose eagle
1536eyes discovered many typographical and factual errors in the Calc manual;
1537Tim Kay, who drove the development of Embedded mode; Ove Ewerlid, who
1538made many suggestions relating to the algebra commands and contributed
1539some code for polynomial operations; Randal Schwartz, who suggested the
1540@code{calc-eval} function; Robert J. Chassell, who suggested the Calc
1541Tutorial and exercises; and Juha Sarlin, who first worked out how to split
1542Calc into quickly-loading parts. Bob Weiner helped immensely with the
1543Lucid Emacs port.
1544
1545@cindex Bibliography
1546@cindex Knuth, Art of Computer Programming
1547@cindex Numerical Recipes
1548@c Should these be expanded into more complete references?
1549Among the books used in the development of Calc were Knuth's @emph{Art
1550of Computer Programming} (especially volume II, @emph{Seminumerical
1551Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
1552and Vetterling; Bevington's @emph{Data Reduction and Error Analysis for
1553the Physical Sciences}; @emph{Concrete Mathematics} by Graham, Knuth,
1554and Patashnik; Steele's @emph{Common Lisp, the Language}; the @emph{CRC
1555Standard Math Tables} (William H. Beyer, ed.); and Abramowitz and
1556Stegun's venerable @emph{Handbook of Mathematical Functions}. I
1557consulted the user's manuals for the HP-28 and HP-48 calculators, as
1558well as for the programs Mathematica, SMP, Macsyma, Maple, MathCAD,
1559Gnuplot, and others. Also, of course, Calc could not have been written
1560without the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil
1561Lewis and Dan LaLiberte.
1562
1563Final thanks go to Richard Stallman, without whose fine implementations
1564of the Emacs editor, language, and environment, Calc would have been
1565finished in two weeks.
1566
1567@c [tutorial]
1568
1569@ifinfo
1570@c This node is accessed by the `M-# t' command.
1571@node Interactive Tutorial, , , Top
1572@chapter Tutorial
1573
1574@noindent
1575Some brief instructions on using the Emacs Info system for this tutorial:
1576
1577Press the space bar and Delete keys to go forward and backward in a
1578section by screenfuls (or use the regular Emacs scrolling commands
1579for this).
1580
1581Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
1582If the section has a @dfn{menu}, press a digit key like @kbd{1}
1583or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to
1584go back up from a sub-section to the menu it is part of.
1585
1586Exercises in the tutorial all have cross-references to the
1587appropriate page of the ``answers'' section. Press @kbd{f}, then
1588the exercise number, to see the answer to an exercise. After
1589you have followed a cross-reference, you can press the letter
1590@kbd{l} to return to where you were before.
1591
1592You can press @kbd{?} at any time for a brief summary of Info commands.
1593
1594Press @kbd{1} now to enter the first section of the Tutorial.
1595
1596@menu
1597* Tutorial::
1598@end menu
1599@end ifinfo
1600
1601@node Tutorial, Introduction, Getting Started, Top
1602@chapter Tutorial
1603
1604@noindent
1605This chapter explains how to use Calc and its many features, in
1606a step-by-step, tutorial way. You are encouraged to run Calc and
1607work along with the examples as you read (@pxref{Starting Calc}).
1608If you are already familiar with advanced calculators, you may wish
1609@c [not-split]
1610to skip on to the rest of this manual.
1611@c [when-split]
1612@c to skip on to volume II of this manual, the @dfn{Calc Reference}.
1613
1614@c [fix-ref Embedded Mode]
1615This tutorial describes the standard user interface of Calc only.
1616The ``Quick Mode'' and ``Keypad Mode'' interfaces are fairly
1617self-explanatory. @xref{Embedded Mode}, for a description of
1618the ``Embedded Mode'' interface.
1619
1620@ifinfo
1621The easiest way to read this tutorial on-line is to have two windows on
1622your Emacs screen, one with Calc and one with the Info system. (If you
1623have a printed copy of the manual you can use that instead.) Press
1624@kbd{M-# c} to turn Calc on or to switch into the Calc window, and
1625press @kbd{M-# i} to start the Info system or to switch into its window.
1626Or, you may prefer to use the tutorial in printed form.
1627@end ifinfo
1628@iftex
1629The easiest way to read this tutorial on-line is to have two windows on
1630your Emacs screen, one with Calc and one with the Info system. (If you
1631have a printed copy of the manual you can use that instead.) Press
1632@kbd{M-# c} to turn Calc on or to switch into the Calc window, and
1633press @kbd{M-# i} to start the Info system or to switch into its window.
1634@end iftex
1635
1636This tutorial is designed to be done in sequence. But the rest of this
1637manual does not assume you have gone through the tutorial. The tutorial
1638does not cover everything in the Calculator, but it touches on most
1639general areas.
1640
1641@ifinfo
1642You may wish to print out a copy of the Calc Summary and keep notes on
1643it as you learn Calc. @xref{Installation}, to see how to make a printed
1644summary. @xref{Summary}.
1645@end ifinfo
1646@iftex
1647The Calc Summary at the end of the reference manual includes some blank
1648space for your own use. You may wish to keep notes there as you learn
1649Calc.
1650@end iftex
1651
1652@menu
1653* Basic Tutorial::
1654* Arithmetic Tutorial::
1655* Vector/Matrix Tutorial::
1656* Types Tutorial::
1657* Algebra Tutorial::
1658* Programming Tutorial::
1659
1660* Answers to Exercises::
1661@end menu
1662
1663@node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
1664@section Basic Tutorial
1665
1666@noindent
1667In this section, we learn how RPN and algebraic-style calculations
1668work, how to undo and redo an operation done by mistake, and how
1669to control various modes of the Calculator.
1670
1671@menu
1672* RPN Tutorial:: Basic operations with the stack.
1673* Algebraic Tutorial:: Algebraic entry; variables.
1674* Undo Tutorial:: If you make a mistake: Undo and the trail.
1675* Modes Tutorial:: Common mode-setting commands.
1676@end menu
1677
1678@node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
1679@subsection RPN Calculations and the Stack
1680
1681@cindex RPN notation
1682@ifinfo
1683@noindent
1684Calc normally uses RPN notation. You may be familiar with the RPN
1685system from Hewlett-Packard calculators, FORTH, or PostScript.
1686(Reverse Polish Notation, RPN, is named after the Polish mathematician
1687Jan Lukasiewicz.)
1688@end ifinfo
1689@tex
1690\noindent
1691Calc normally uses RPN notation. You may be familiar with the RPN
1692system from Hewlett-Packard calculators, FORTH, or PostScript.
1693(Reverse Polish Notation, RPN, is named after the Polish mathematician
1694Jan \L ukasiewicz.)
1695@end tex
1696
1697The central component of an RPN calculator is the @dfn{stack}. A
1698calculator stack is like a stack of dishes. New dishes (numbers) are
1699added at the top of the stack, and numbers are normally only removed
1700from the top of the stack.
1701
1702@cindex Operators
1703@cindex Operands
1704In an operation like @cite{2+3}, the 2 and 3 are called the @dfn{operands}
1705and the @cite{+} is the @dfn{operator}. In an RPN calculator you always
1706enter the operands first, then the operator. Each time you type a
1707number, Calc adds or @dfn{pushes} it onto the top of the Stack.
1708When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
1709number of operands from the stack and pushes back the result.
1710
1711Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
1712@kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to
1713the @key{ENTER} key on traditional RPN calculators.) Try this now if
1714you wish; type @kbd{M-# c} to switch into the Calc window (you can type
1715@kbd{M-# c} again or @kbd{M-# o} to switch back to the Tutorial window).
1716The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
1717The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
1718and pushes the result (5) back onto the stack. Here's how the stack
1719will look at various points throughout the calculation:@refill
1720
1721@group
1722@smallexample
1723 . 1: 2 2: 2 1: 5 .
1724 . 1: 3 .
1725 .
1726
1727 M-# c 2 RET 3 RET + DEL
1728@end smallexample
1729@end group
1730
1731The @samp{.} symbol is a marker that represents the top of the stack.
1732Note that the ``top'' of the stack is really shown at the bottom of
1733the Stack window. This may seem backwards, but it turns out to be
1734less distracting in regular use.
1735
1736@cindex Stack levels
1737@cindex Levels of stack
1738The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
1739numbers}. Old RPN calculators always had four stack levels called
1740@cite{x}, @cite{y}, @cite{z}, and @cite{t}. Calc's stack can grow
1741as large as you like, so it uses numbers instead of letters. Some
1742stack-manipulation commands accept a numeric argument that says
1743which stack level to work on. Normal commands like @kbd{+} always
1744work on the top few levels of the stack.@refill
1745
1746@c [fix-ref Truncating the Stack]
1747The Stack buffer is just an Emacs buffer, and you can move around in
1748it using the regular Emacs motion commands. But no matter where the
1749cursor is, even if you have scrolled the @samp{.} marker out of
1750view, most Calc commands always move the cursor back down to level 1
1751before doing anything. It is possible to move the @samp{.} marker
1752upwards through the stack, temporarily ``hiding'' some numbers from
1753commands like @kbd{+}. This is called @dfn{stack truncation} and
1754we will not cover it in this tutorial; @pxref{Truncating the Stack},
1755if you are interested.
1756
1757You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
1758@key{RET} +}. That's because if you type any operator name or
1759other non-numeric key when you are entering a number, the Calculator
1760automatically enters that number and then does the requested command.
1761Thus @kbd{2 @key{RET} 3 +} will work just as well.@refill
1762
1763Examples in this tutorial will often omit @key{RET} even when the
1764stack displays shown would only happen if you did press @key{RET}:
1765
1766@group
1767@smallexample
17681: 2 2: 2 1: 5
1769 . 1: 3 .
1770 .
1771
1772 2 RET 3 +
1773@end smallexample
1774@end group
1775
1776@noindent
1777Here, after pressing @kbd{3} the stack would really show @samp{1: 2}
1778with @samp{Calc:@: 3} in the minibuffer. In these situations, you can
1779press the optional @key{RET} to see the stack as the figure shows.
1780
1781(@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises
1782at various points. Try them if you wish. Answers to all the exercises
1783are located at the end of the Tutorial chapter. Each exercise will
1784include a cross-reference to its particular answer. If you are
1785reading with the Emacs Info system, press @kbd{f} and the
1786exercise number to go to the answer, then the letter @kbd{l} to
1787return to where you were.)
1788
1789@noindent
1790Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2
1791@key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for
1792multiplication.) Figure it out by hand, then try it with Calc to see
1793if you're right. @xref{RPN Answer 1, 1}. (@bullet{})
1794
1795(@bullet{}) @strong{Exercise 2.} Compute @c{$(2\times4) + (7\times9.4) + {5\over4}$}
1796@cite{2*4 + 7*9.5 + 5/4} using the
1797stack. @xref{RPN Answer 2, 2}. (@bullet{})
1798
1799The @key{DEL} key is called Backspace on some keyboards. It is
1800whatever key you would use to correct a simple typing error when
1801regularly using Emacs. The @key{DEL} key pops and throws away the
1802top value on the stack. (You can still get that value back from
1803the Trail if you should need it later on.) There are many places
1804in this tutorial where we assume you have used @key{DEL} to erase the
1805results of the previous example at the beginning of a new example.
1806In the few places where it is really important to use @key{DEL} to
1807clear away old results, the text will remind you to do so.
1808
1809(It won't hurt to let things accumulate on the stack, except that
1810whenever you give a display-mode-changing command Calc will have to
1811spend a long time reformatting such a large stack.)
1812
1813Since the @kbd{-} key is also an operator (it subtracts the top two
1814stack elements), how does one enter a negative number? Calc uses
1815the @kbd{_} (underscore) key to act like the minus sign in a number.
1816So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
1817will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
1818
1819You can also press @kbd{n}, which means ``change sign.'' It changes
1820the number at the top of the stack (or the number being entered)
1821from positive to negative or vice-versa: @kbd{5 n @key{RET}}.
1822
1823@cindex Duplicating a stack entry
1824If you press @key{RET} when you're not entering a number, the effect
1825is to duplicate the top number on the stack. Consider this calculation:
1826
1827@group
1828@smallexample
18291: 3 2: 3 1: 9 2: 9 1: 81
1830 . 1: 3 . 1: 9 .
1831 . .
1832
1833 3 RET RET * RET *
1834@end smallexample
1835@end group
1836
1837@noindent
1838(Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
1839to raise 3 to the fourth power.)
1840
1841The space-bar key (denoted @key{SPC} here) performs the same function
1842as @key{RET}; you could replace all three occurrences of @key{RET} in
1843the above example with @key{SPC} and the effect would be the same.
1844
1845@cindex Exchanging stack entries
1846Another stack manipulation key is @key{TAB}. This exchanges the top
1847two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +}
1848to get 5, and then you realize what you really wanted to compute
1849was @cite{20 / (2+3)}.
1850
1851@group
1852@smallexample
18531: 5 2: 5 2: 20 1: 4
1854 . 1: 20 1: 5 .
1855 . .
1856
1857 2 RET 3 + 20 TAB /
1858@end smallexample
1859@end group
1860
1861@noindent
1862Planning ahead, the calculation would have gone like this:
1863
1864@group
1865@smallexample
18661: 20 2: 20 3: 20 2: 20 1: 4
1867 . 1: 2 2: 2 1: 5 .
1868 . 1: 3 .
1869 .
1870
1871 20 RET 2 RET 3 + /
1872@end smallexample
1873@end group
1874
1875A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
1876@key{TAB}). It rotates the top three elements of the stack upward,
1877bringing the object in level 3 to the top.
1878
1879@group
1880@smallexample
18811: 10 2: 10 3: 10 3: 20 3: 30
1882 . 1: 20 2: 20 2: 30 2: 10
1883 . 1: 30 1: 10 1: 20
1884 . . .
1885
1886 10 RET 20 RET 30 RET M-TAB M-TAB
1887@end smallexample
1888@end group
1889
1890(@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
1891on the stack. Figure out how to add one to the number in level 2
1892without affecting the rest of the stack. Also figure out how to add
1893one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{})
1894
1895Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
1896arguments from the stack and push a result. Operations like @kbd{n} and
1897@kbd{Q} (square root) pop a single number and push the result. You can
1898think of them as simply operating on the top element of the stack.
1899
1900@group
1901@smallexample
19021: 3 1: 9 2: 9 1: 25 1: 5
1903 . . 1: 16 . .
1904 .
1905
1906 3 RET RET * 4 RET RET * + Q
1907@end smallexample
1908@end group
1909
1910@noindent
1911(Note that capital @kbd{Q} means to hold down the Shift key while
1912typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.)
1913
1914@cindex Pythagorean Theorem
1915Here we've used the Pythagorean Theorem to determine the hypotenuse of a
1916right triangle. Calc actually has a built-in command for that called
1917@kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
1918We can still enter it by its full name using @kbd{M-x} notation:
1919
1920@group
1921@smallexample
19221: 3 2: 3 1: 5
1923 . 1: 4 .
1924 .
1925
1926 3 RET 4 RET M-x calc-hypot
1927@end smallexample
1928@end group
1929
1930All Calculator commands begin with the word @samp{calc-}. Since it
1931gets tiring to type this, Calc provides an @kbd{x} key which is just
1932like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
1933prefix for you:
1934
1935@group
1936@smallexample
19371: 3 2: 3 1: 5
1938 . 1: 4 .
1939 .
1940
1941 3 RET 4 RET x hypot
1942@end smallexample
1943@end group
1944
1945What happens if you take the square root of a negative number?
1946
1947@group
1948@smallexample
19491: 4 1: -4 1: (0, 2)
1950 . . .
1951
1952 4 RET n Q
1953@end smallexample
1954@end group
1955
1956@noindent
1957The notation @cite{(a, b)} represents a complex number.
1958Complex numbers are more traditionally written @c{$a + b i$}
1959@cite{a + b i};
1960Calc can display in this format, too, but for now we'll stick to the
1961@cite{(a, b)} notation.
1962
1963If you don't know how complex numbers work, you can safely ignore this
1964feature. Complex numbers only arise from operations that would be
1965errors in a calculator that didn't have complex numbers. (For example,
1966taking the square root or logarithm of a negative number produces a
1967complex result.)
1968
1969Complex numbers are entered in the notation shown. The @kbd{(} and
1970@kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
1971
1972@group
1973@smallexample
19741: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3)
1975 . 1: 2 . 3 .
1976 . .
1977
1978 ( 2 , 3 )
1979@end smallexample
1980@end group
1981
1982You can perform calculations while entering parts of incomplete objects.
1983However, an incomplete object cannot actually participate in a calculation:
1984
1985@group
1986@smallexample
19871: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ...
1988 . 1: 2 2: 2 5 5
1989 . 1: 3 . .
1990 .
1991 (error)
1992 ( 2 RET 3 + +
1993@end smallexample
1994@end group
1995
1996@noindent
1997Adding 5 to an incomplete object makes no sense, so the last command
1998produces an error message and leaves the stack the same.
1999
2000Incomplete objects can't participate in arithmetic, but they can be
2001moved around by the regular stack commands.
2002
2003@group
2004@smallexample
20052: 2 3: 2 3: 3 1: ( ... 1: (2, 3)
20061: 3 2: 3 2: ( ... 2 .
2007 . 1: ( ... 1: 2 3
2008 . . .
2009
20102 RET 3 RET ( M-TAB M-TAB )
2011@end smallexample
2012@end group
2013
2014@noindent
2015Note that the @kbd{,} (comma) key did not have to be used here.
2016When you press @kbd{)} all the stack entries between the incomplete
2017entry and the top are collected, so there's never really a reason
2018to use the comma. It's up to you.
2019
2020(@bullet{}) @strong{Exercise 4.} To enter the complex number @cite{(2, 3)},
2021your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened?
2022(Joe thought of a clever way to correct his mistake in only two
2023keystrokes, but it didn't quite work. Try it to find out why.)
2024@xref{RPN Answer 4, 4}. (@bullet{})
2025
2026Vectors are entered the same way as complex numbers, but with square
2027brackets in place of parentheses. We'll meet vectors again later in
2028the tutorial.
2029
2030Any Emacs command can be given a @dfn{numeric prefix argument} by
2031typing a series of @key{META}-digits beforehand. If @key{META} is
2032awkward for you, you can instead type @kbd{C-u} followed by the
2033necessary digits. Numeric prefix arguments can be negative, as in
2034@kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric
2035prefix arguments in a variety of ways. For example, a numeric prefix
2036on the @kbd{+} operator adds any number of stack entries at once:
2037
2038@group
2039@smallexample
20401: 10 2: 10 3: 10 3: 10 1: 60
2041 . 1: 20 2: 20 2: 20 .
2042 . 1: 30 1: 30
2043 . .
2044
2045 10 RET 20 RET 30 RET C-u 3 +
2046@end smallexample
2047@end group
2048
2049For stack manipulation commands like @key{RET}, a positive numeric
2050prefix argument operates on the top @var{n} stack entries at once. A
2051negative argument operates on the entry in level @var{n} only. An
2052argument of zero operates on the entire stack. In this example, we copy
2053the second-to-top element of the stack:
2054
2055@group
2056@smallexample
20571: 10 2: 10 3: 10 3: 10 4: 10
2058 . 1: 20 2: 20 2: 20 3: 20
2059 . 1: 30 1: 30 2: 30
2060 . . 1: 20
2061 .
2062
2063 10 RET 20 RET 30 RET C-u -2 RET
2064@end smallexample
2065@end group
2066
2067@cindex Clearing the stack
2068@cindex Emptying the stack
2069Another common idiom is @kbd{M-0 DEL}, which clears the stack.
2070(The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
2071entire stack.)
2072
2073@node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
2074@subsection Algebraic-Style Calculations
2075
2076@noindent
2077If you are not used to RPN notation, you may prefer to operate the
2078Calculator in ``algebraic mode,'' which is closer to the way
2079non-RPN calculators work. In algebraic mode, you enter formulas
2080in traditional @cite{2+3} notation.
2081
2082You don't really need any special ``mode'' to enter algebraic formulas.
2083You can enter a formula at any time by pressing the apostrophe (@kbd{'})
2084key. Answer the prompt with the desired formula, then press @key{RET}.
2085The formula is evaluated and the result is pushed onto the RPN stack.
2086If you don't want to think in RPN at all, you can enter your whole
2087computation as a formula, read the result from the stack, then press
2088@key{DEL} to delete it from the stack.
2089
2090Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
2091The result should be the number 9.
2092
2093Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
2094@samp{/}, and @samp{^}. You can use parentheses to make the order
2095of evaluation clear. In the absence of parentheses, @samp{^} is
2096evaluated first, then @samp{*}, then @samp{/}, then finally
2097@samp{+} and @samp{-}. For example, the expression
2098
2099@example
21002 + 3*4*5 / 6*7^8 - 9
2101@end example
2102
2103@noindent
2104is equivalent to
2105
2106@example
21072 + ((3*4*5) / (6*(7^8)) - 9
2108@end example
2109
2110@noindent
2111or, in large mathematical notation,
2112
2113@ifinfo
2114@group
2115@example
2116 3 * 4 * 5
21172 + --------- - 9
2118 8
2119 6 * 7
2120@end example
2121@end group
2122@end ifinfo
2123@tex
2124\turnoffactive
2125\beforedisplay
2126$$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
2127\afterdisplay
2128@end tex
2129
2130@noindent
2131The result of this expression will be the number @i{-6.99999826533}.
2132
2133Calc's order of evaluation is the same as for most computer languages,
2134except that @samp{*} binds more strongly than @samp{/}, as the above
2135example shows. As in normal mathematical notation, the @samp{*} symbol
2136can often be omitted: @samp{2 a} is the same as @samp{2*a}.
2137
2138Operators at the same level are evaluated from left to right, except
2139that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is
2140equivalent to @samp{(2-3)-4} or @i{-5}, whereas @samp{2^3^4} is equivalent
2141to @samp{2^(3^4)} (a very large integer; try it!).
2142
2143If you tire of typing the apostrophe all the time, there is an
2144``algebraic mode'' you can select in which Calc automatically senses
2145when you are about to type an algebraic expression. To enter this
2146mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator
2147should appear in the Calc window's mode line.)
2148
2149Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
2150
2151In algebraic mode, when you press any key that would normally begin
2152entering a number (such as a digit, a decimal point, or the @kbd{_}
2153key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
2154an algebraic entry.
2155
2156Functions which do not have operator symbols like @samp{+} and @samp{*}
2157must be entered in formulas using function-call notation. For example,
2158the function name corresponding to the square-root key @kbd{Q} is
2159@code{sqrt}. To compute a square root in a formula, you would use
2160the notation @samp{sqrt(@var{x})}.
2161
2162Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should
2163be @cite{0.16227766017}.
2164
2165Note that if the formula begins with a function name, you need to use
2166the apostrophe even if you are in algebraic mode. If you type @kbd{arcsin}
2167out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
2168command, and the @kbd{csin} will be taken as the name of the rewrite
2169rule to use!
2170
2171Some people prefer to enter complex numbers and vectors in algebraic
2172form because they find RPN entry with incomplete objects to be too
2173distracting, even though they otherwise use Calc as an RPN calculator.
2174
2175Still in algebraic mode, type:
2176
2177@group
2178@smallexample
21791: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1)
2180 . 1: (1, -2) . 1: 1 .
2181 . .
2182
2183 (2,3) RET (1,-2) RET * 1 RET +
2184@end smallexample
2185@end group
2186
2187Algebraic mode allows us to enter complex numbers without pressing
2188an apostrophe first, but it also means we need to press @key{RET}
2189after every entry, even for a simple number like @cite{1}.
2190
2191(You can type @kbd{C-u m a} to enable a special ``incomplete algebraic
2192mode'' in which the @kbd{(} and @kbd{[} keys use algebraic entry even
2193though regular numeric keys still use RPN numeric entry. There is also
2194a ``total algebraic mode,'' started by typing @kbd{m t}, in which all
2195normal keys begin algebraic entry. You must then use the @key{META} key
2196to type Calc commands: @kbd{M-m t} to get back out of total algebraic
2197mode, @kbd{M-q} to quit, etc. Total algebraic mode is not supported
2198under Emacs 19.)
2199
2200If you're still in algebraic mode, press @kbd{m a} again to turn it off.
2201
2202Actual non-RPN calculators use a mixture of algebraic and RPN styles.
2203In general, operators of two numbers (like @kbd{+} and @kbd{*})
2204use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
2205use RPN form. Also, a non-RPN calculator allows you to see the
2206intermediate results of a calculation as you go along. You can
2207accomplish this in Calc by performing your calculation as a series
2208of algebraic entries, using the @kbd{$} sign to tie them together.
2209In an algebraic formula, @kbd{$} represents the number on the top
2210of the stack. Here, we perform the calculation @c{$\sqrt{2\times4+1}$}
2211@cite{sqrt(2*4+1)},
2212which on a traditional calculator would be done by pressing
2213@kbd{2 * 4 + 1 =} and then the square-root key.
2214
2215@group
2216@smallexample
22171: 8 1: 9 1: 3
2218 . . .
2219
2220 ' 2*4 RET $+1 RET Q
2221@end smallexample
2222@end group
2223
2224@noindent
2225Notice that we didn't need to press an apostrophe for the @kbd{$+1},
2226because the dollar sign always begins an algebraic entry.
2227
2228(@bullet{}) @strong{Exercise 1.} How could you get the same effect as
2229pressing @kbd{Q} but using an algebraic entry instead? How about
2230if the @kbd{Q} key on your keyboard were broken?
2231@xref{Algebraic Answer 1, 1}. (@bullet{})
2232
2233The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
2234entries. For example, @kbd{' $$+$ RET} is just like typing @kbd{+}.
2235
2236Algebraic formulas can include @dfn{variables}. To store in a
2237variable, press @kbd{s s}, then type the variable name, then press
2238@key{RET}. (There are actually two flavors of store command:
2239@kbd{s s} stores a number in a variable but also leaves the number
2240on the stack, while @w{@kbd{s t}} removes a number from the stack and
2241stores it in the variable.) A variable name should consist of one
2242or more letters or digits, beginning with a letter.
2243
2244@group
2245@smallexample
22461: 17 . 1: a + a^2 1: 306
2247 . . .
2248
2249 17 s t a RET ' a+a^2 RET =
2250@end smallexample
2251@end group
2252
2253@noindent
2254The @kbd{=} key @dfn{evaluates} a formula by replacing all its
2255variables by the values that were stored in them.
2256
2257For RPN calculations, you can recall a variable's value on the
2258stack either by entering its name as a formula and pressing @kbd{=},
2259or by using the @kbd{s r} command.
2260
2261@group
2262@smallexample
22631: 17 2: 17 3: 17 2: 17 1: 306
2264 . 1: 17 2: 17 1: 289 .
2265 . 1: 2 .
2266 .
2267
2268 s r a RET ' a RET = 2 ^ +
2269@end smallexample
2270@end group
2271
2272If you press a single digit for a variable name (as in @kbd{s t 3}, you
2273get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
2274They are ``quick'' simply because you don't have to type the letter
2275@code{q} or the @key{RET} after their names. In fact, you can type
2276simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
2277@kbd{t 3} and @w{@kbd{r 3}}.
2278
2279Any variables in an algebraic formula for which you have not stored
2280values are left alone, even when you evaluate the formula.
2281
2282@group
2283@smallexample
22841: 2 a + 2 b 1: 34 + 2 b
2285 . .
2286
2287 ' 2a+2b RET =
2288@end smallexample
2289@end group
2290
2291Calls to function names which are undefined in Calc are also left
2292alone, as are calls for which the value is undefined.
2293
2294@group
2295@smallexample
22961: 2 + log10(0) + log10(x) + log10(5, 6) + foo(3)
2297 .
2298
2299 ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) RET
2300@end smallexample
2301@end group
2302
2303@noindent
2304In this example, the first call to @code{log10} works, but the other
2305calls are not evaluated. In the second call, the logarithm is
2306undefined for that value of the argument; in the third, the argument
2307is symbolic, and in the fourth, there are too many arguments. In the
2308fifth case, there is no function called @code{foo}. You will see a
2309``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
2310Press the @kbd{w} (``why'') key to see any other messages that may
2311have arisen from the last calculation. In this case you will get
2312``logarithm of zero,'' then ``number expected: @code{x}''. Calc
2313automatically displays the first message only if the message is
2314sufficiently important; for example, Calc considers ``wrong number
2315of arguments'' and ``logarithm of zero'' to be important enough to
2316report automatically, while a message like ``number expected: @code{x}''
2317will only show up if you explicitly press the @kbd{w} key.
2318
2319(@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y},
2320stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
2321@samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)},
2322expecting @samp{10 (1+y)}, but it didn't work. Why not?
2323@xref{Algebraic Answer 2, 2}. (@bullet{})
2324
2325(@bullet{}) @strong{Exercise 3.} What result would you expect
2326@kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}?
2327@xref{Algebraic Answer 3, 3}. (@bullet{})
2328
2329One interesting way to work with variables is to use the
2330@dfn{evaluates-to} (@samp{=>}) operator. It works like this:
2331Enter a formula algebraically in the usual way, but follow
2332the formula with an @samp{=>} symbol. (There is also an @kbd{s =}
2333command which builds an @samp{=>} formula using the stack.) On
2334the stack, you will see two copies of the formula with an @samp{=>}
2335between them. The lefthand formula is exactly like you typed it;
2336the righthand formula has been evaluated as if by typing @kbd{=}.
2337
2338@group
2339@smallexample
23402: 2 + 3 => 5 2: 2 + 3 => 5
23411: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b
2342 . .
2343
2344' 2+3 => RET ' 2a+2b RET s = 10 s t a RET
2345@end smallexample
2346@end group
2347
2348@noindent
2349Notice that the instant we stored a new value in @code{a}, all
2350@samp{=>} operators already on the stack that referred to @cite{a}
2351were updated to use the new value. With @samp{=>}, you can push a
2352set of formulas on the stack, then change the variables experimentally
2353to see the effects on the formulas' values.
2354
2355You can also ``unstore'' a variable when you are through with it:
2356
2357@group
2358@smallexample
23592: 2 + 5 => 5
23601: 2 a + 2 b => 2 a + 2 b
2361 .
2362
2363 s u a RET
2364@end smallexample
2365@end group
2366
2367We will encounter formulas involving variables and functions again
2368when we discuss the algebra and calculus features of the Calculator.
2369
2370@node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
2371@subsection Undo and Redo
2372
2373@noindent
2374If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
2375the ``undo'' command. First, clear the stack (@kbd{M-0 DEL}) and exit
2376and restart Calc (@kbd{M-# M-# M-# M-#}) to make sure things start off
2377with a clean slate. Now:
2378
2379@group
2380@smallexample
23811: 2 2: 2 1: 8 2: 2 1: 6
2382 . 1: 3 . 1: 3 .
2383 . .
2384
2385 2 RET 3 ^ U *
2386@end smallexample
2387@end group
2388
2389You can undo any number of times. Calc keeps a complete record of
2390all you have done since you last opened the Calc window. After the
2391above example, you could type:
2392
2393@group
2394@smallexample
23951: 6 2: 2 1: 2 . .
2396 . 1: 3 .
2397 .
2398 (error)
2399 U U U U
2400@end smallexample
2401@end group
2402
2403You can also type @kbd{D} to ``redo'' a command that you have undone
2404mistakenly.
2405
2406@group
2407@smallexample
2408 . 1: 2 2: 2 1: 6 1: 6
2409 . 1: 3 . .
2410 .
2411 (error)
2412 D D D D
2413@end smallexample
2414@end group
2415
2416@noindent
2417It was not possible to redo past the @cite{6}, since that was placed there
2418by something other than an undo command.
2419
2420@cindex Time travel
2421You can think of undo and redo as a sort of ``time machine.'' Press
2422@kbd{U} to go backward in time, @kbd{D} to go forward. If you go
2423backward and do something (like @kbd{*}) then, as any science fiction
2424reader knows, you have changed your future and you cannot go forward
2425again. Thus, the inability to redo past the @cite{6} even though there
2426was an earlier undo command.
2427
2428You can always recall an earlier result using the Trail. We've ignored
2429the trail so far, but it has been faithfully recording everything we
2430did since we loaded the Calculator. If the Trail is not displayed,
2431press @kbd{t d} now to turn it on.
2432
2433Let's try grabbing an earlier result. The @cite{8} we computed was
2434undone by a @kbd{U} command, and was lost even to Redo when we pressed
2435@kbd{*}, but it's still there in the trail. There should be a little
2436@samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
2437entry. If there isn't, press @kbd{t ]} to reset the trail pointer.
2438Now, press @w{@kbd{t p}} to move the arrow onto the line containing
2439@cite{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
2440stack.
2441
2442If you press @kbd{t ]} again, you will see that even our Yank command
2443went into the trail.
2444
2445Let's go further back in time. Earlier in the tutorial we computed
2446a huge integer using the formula @samp{2^3^4}. We don't remember
2447what it was, but the first digits were ``241''. Press @kbd{t r}
2448(which stands for trail-search-reverse), then type @kbd{241}.
2449The trail cursor will jump back to the next previous occurrence of
2450the string ``241'' in the trail. This is just a regular Emacs
2451incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
2452continue the search forwards or backwards as you like.
2453
2454To finish the search, press @key{RET}. This halts the incremental
2455search and leaves the trail pointer at the thing we found. Now we
2456can type @kbd{t y} to yank that number onto the stack. If we hadn't
2457remembered the ``241'', we could simply have searched for @kbd{2^3^4},
2458then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
2459
2460You may have noticed that all the trail-related commands begin with
2461the letter @kbd{t}. (The store-and-recall commands, on the other hand,
2462all began with @kbd{s}.) Calc has so many commands that there aren't
2463enough keys for all of them, so various commands are grouped into
2464two-letter sequences where the first letter is called the @dfn{prefix}
2465key. If you type a prefix key by accident, you can press @kbd{C-g}
2466to cancel it. (In fact, you can press @kbd{C-g} to cancel almost
2467anything in Emacs.) To get help on a prefix key, press that key
2468followed by @kbd{?}. Some prefixes have several lines of help,
2469so you need to press @kbd{?} repeatedly to see them all. This may
2470not work under Lucid Emacs, but you can also type @kbd{h h} to
2471see all the help at once.
2472
2473Try pressing @kbd{t ?} now. You will see a line of the form,
2474
2475@smallexample
2476trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-
2477@end smallexample
2478
2479@noindent
2480The word ``trail'' indicates that the @kbd{t} prefix key contains
2481trail-related commands. Each entry on the line shows one command,
2482with a single capital letter showing which letter you press to get
2483that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
2484@kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?}
2485again to see more @kbd{t}-prefix comands. Notice that the commands
2486are roughly divided (by semicolons) into related groups.
2487
2488When you are in the help display for a prefix key, the prefix is
2489still active. If you press another key, like @kbd{y} for example,
2490it will be interpreted as a @kbd{t y} command. If all you wanted
2491was to look at the help messages, press @kbd{C-g} afterwards to cancel
2492the prefix.
2493
2494One more way to correct an error is by editing the stack entries.
2495The actual Stack buffer is marked read-only and must not be edited
2496directly, but you can press @kbd{`} (the backquote or accent grave)
2497to edit a stack entry.
2498
2499Try entering @samp{3.141439} now. If this is supposed to represent
2500@c{$\pi$}
2501@cite{pi}, it's got several errors. Press @kbd{`} to edit this number.
2502Now use the normal Emacs cursor motion and editing keys to change
2503the second 4 to a 5, and to transpose the 3 and the 9. When you
2504press @key{RET}, the number on the stack will be replaced by your
2505new number. This works for formulas, vectors, and all other types
2506of values you can put on the stack. The @kbd{`} key also works
2507during entry of a number or algebraic formula.
2508
2509@node Modes Tutorial, , Undo Tutorial, Basic Tutorial
2510@subsection Mode-Setting Commands
2511
2512@noindent
2513Calc has many types of @dfn{modes} that affect the way it interprets
2514your commands or the way it displays data. We have already seen one
2515mode, namely algebraic mode. There are many others, too; we'll
2516try some of the most common ones here.
2517
2518Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
2519Notice the @samp{12} on the Calc window's mode line:
2520
2521@smallexample
2522--%%-Calc: 12 Deg (Calculator)----All------
2523@end smallexample
2524
2525@noindent
2526Most of the symbols there are Emacs things you don't need to worry
2527about, but the @samp{12} and the @samp{Deg} are mode indicators.
2528The @samp{12} means that calculations should always be carried to
252912 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /},
2530we get @cite{0.142857142857} with exactly 12 digits, not counting
2531leading and trailing zeros.
2532
2533You can set the precision to anything you like by pressing @kbd{p},
2534then entering a suitable number. Try pressing @kbd{p 30 @key{RET}},
2535then doing @kbd{1 @key{RET} 7 /} again:
2536
2537@group
2538@smallexample
25391: 0.142857142857
25402: 0.142857142857142857142857142857
2541 .
2542@end smallexample
2543@end group
2544
2545Although the precision can be set arbitrarily high, Calc always
2546has to have @emph{some} value for the current precision. After
2547all, the true value @cite{1/7} is an infinitely repeating decimal;
2548Calc has to stop somewhere.
2549
2550Of course, calculations are slower the more digits you request.
2551Press @w{@kbd{p 12}} now to set the precision back down to the default.
2552
2553Calculations always use the current precision. For example, even
2554though we have a 30-digit value for @cite{1/7} on the stack, if
2555we use it in a calculation in 12-digit mode it will be rounded
2556down to 12 digits before it is used. Try it; press @key{RET} to
2557duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET}
2558key didn't round the number, because it doesn't do any calculation.
2559But the instant we pressed @kbd{+}, the number was rounded down.
2560
2561@group
2562@smallexample
25631: 0.142857142857
25642: 0.142857142857142857142857142857
25653: 1.14285714286
2566 .
2567@end smallexample
2568@end group
2569
2570@noindent
2571In fact, since we added a digit on the left, we had to lose one
2572digit on the right from even the 12-digit value of @cite{1/7}.
2573
2574How did we get more than 12 digits when we computed @samp{2^3^4}? The
2575answer is that Calc makes a distinction between @dfn{integers} and
2576@dfn{floating-point} numbers, or @dfn{floats}. An integer is a number
2577that does not contain a decimal point. There is no such thing as an
2578``infinitely repeating fraction integer,'' so Calc doesn't have to limit
2579itself. If you asked for @samp{2^10000} (don't try this!), you would
2580have to wait a long time but you would eventually get an exact answer.
2581If you ask for @samp{2.^10000}, you will quickly get an answer which is
2582correct only to 12 places. The decimal point tells Calc that it should
2583use floating-point arithmetic to get the answer, not exact integer
2584arithmetic.
2585
2586You can use the @kbd{F} (@code{calc-floor}) command to convert a
2587floating-point value to an integer, and @kbd{c f} (@code{calc-float})
2588to convert an integer to floating-point form.
2589
2590Let's try entering that last calculation:
2591
2592@group
2593@smallexample
25941: 2. 2: 2. 1: 1.99506311689e3010
2595 . 1: 10000 .
2596 .
2597
2598 2.0 RET 10000 RET ^
2599@end smallexample
2600@end group
2601
2602@noindent
2603@cindex Scientific notation, entry of
2604Notice the letter @samp{e} in there. It represents ``times ten to the
2605power of,'' and is used by Calc automatically whenever writing the
2606number out fully would introduce more extra zeros than you probably
2607want to see. You can enter numbers in this notation, too.
2608
2609@group
2610@smallexample
26111: 2. 2: 2. 1: 1.99506311678e3010
2612 . 1: 10000. .
2613 .
2614
2615 2.0 RET 1e4 RET ^
2616@end smallexample
2617@end group
2618
2619@cindex Round-off errors
2620@noindent
2621Hey, the answer is different! Look closely at the middle columns
2622of the two examples. In the first, the stack contained the
2623exact integer @cite{10000}, but in the second it contained
2624a floating-point value with a decimal point. When you raise a
2625number to an integer power, Calc uses repeated squaring and
2626multiplication to get the answer. When you use a floating-point
2627power, Calc uses logarithms and exponentials. As you can see,
2628a slight error crept in during one of these methods. Which
2629one should we trust? Let's raise the precision a bit and find
2630out:
2631
2632@group
2633@smallexample
2634 . 1: 2. 2: 2. 1: 1.995063116880828e3010
2635 . 1: 10000. .
2636 .
2637
2638 p 16 RET 2. RET 1e4 ^ p 12 RET
2639@end smallexample
2640@end group
2641
2642@noindent
2643@cindex Guard digits
2644Presumably, it doesn't matter whether we do this higher-precision
2645calculation using an integer or floating-point power, since we
2646have added enough ``guard digits'' to trust the first 12 digits
2647no matter what. And the verdict is@dots{} Integer powers were more
2648accurate; in fact, the result was only off by one unit in the
2649last place.
2650
2651@cindex Guard digits
2652Calc does many of its internal calculations to a slightly higher
2653precision, but it doesn't always bump the precision up enough.
2654In each case, Calc added about two digits of precision during
2655its calculation and then rounded back down to 12 digits
2656afterward. In one case, it was enough; in the the other, it
2657wasn't. If you really need @var{x} digits of precision, it
2658never hurts to do the calculation with a few extra guard digits.
2659
2660What if we want guard digits but don't want to look at them?
2661We can set the @dfn{float format}. Calc supports four major
2662formats for floating-point numbers, called @dfn{normal},
2663@dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
2664notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f},
2665@kbd{d s}, and @kbd{d e}, respectively. In each case, you can
2666supply a numeric prefix argument which says how many digits
2667should be displayed. As an example, let's put a few numbers
2668onto the stack and try some different display modes. First,
2669use @kbd{M-0 DEL} to clear the stack, then enter the four
2670numbers shown here:
2671
2672@group
2673@smallexample
26744: 12345 4: 12345 4: 12345 4: 12345 4: 12345
26753: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000
26762: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450
26771: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345
2678 . . . . .
2679
2680 d n M-3 d n d s M-3 d s M-3 d f
2681@end smallexample
2682@end group
2683
2684@noindent
2685Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
2686to three significant digits, but then when we typed @kbd{d s} all
2687five significant figures reappeared. The float format does not
2688affect how numbers are stored, it only affects how they are
2689displayed. Only the current precision governs the actual rounding
2690of numbers in the Calculator's memory.
2691
2692Engineering notation, not shown here, is like scientific notation
2693except the exponent (the power-of-ten part) is always adjusted to be
2694a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result
2695there will be one, two, or three digits before the decimal point.
2696
2697Whenever you change a display-related mode, Calc redraws everything
2698in the stack. This may be slow if there are many things on the stack,
2699so Calc allows you to type shift-@kbd{H} before any mode command to
2700prevent it from updating the stack. Anything Calc displays after the
2701mode-changing command will appear in the new format.
2702
2703@group
2704@smallexample
27054: 12345 4: 12345 4: 12345 4: 12345 4: 12345
27063: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345.
27072: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45
27081: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345
2709 . . . . .
2710
2711 H d s DEL U TAB d SPC d n
2712@end smallexample
2713@end group
2714
2715@noindent
2716Here the @kbd{H d s} command changes to scientific notation but without
2717updating the screen. Deleting the top stack entry and undoing it back
2718causes it to show up in the new format; swapping the top two stack
2719entries reformats both entries. The @kbd{d SPC} command refreshes the
2720whole stack. The @kbd{d n} command changes back to the normal float
2721format; since it doesn't have an @kbd{H} prefix, it also updates all
2722the stack entries to be in @kbd{d n} format.
2723
2724Notice that the integer @cite{12345} was not affected by any
2725of the float formats. Integers are integers, and are always
2726displayed exactly.
2727
2728@cindex Large numbers, readability
2729Large integers have their own problems. Let's look back at
2730the result of @kbd{2^3^4}.
2731
2732@example
27332417851639229258349412352
2734@end example
2735
2736@noindent
2737Quick---how many digits does this have? Try typing @kbd{d g}:
2738
2739@example
27402,417,851,639,229,258,349,412,352
2741@end example
2742
2743@noindent
2744Now how many digits does this have? It's much easier to tell!
2745We can actually group digits into clumps of any size. Some
2746people prefer @kbd{M-5 d g}:
2747
2748@example
274924178,51639,22925,83494,12352
2750@end example
2751
2752Let's see what happens to floating-point numbers when they are grouped.
2753First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
2754to get ourselves into trouble. Now, type @kbd{1e13 /}:
2755
2756@example
275724,17851,63922.9258349412352
2758@end example
2759
2760@noindent
2761The integer part is grouped but the fractional part isn't. Now try
2762@kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
2763
2764@example
276524,17851,63922.92583,49412,352
2766@end example
2767
2768If you find it hard to tell the decimal point from the commas, try
2769changing the grouping character to a space with @kbd{d , @key{SPC}}:
2770
2771@example
277224 17851 63922.92583 49412 352
2773@end example
2774
2775Type @kbd{d , ,} to restore the normal grouping character, then
2776@kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to
2777restore the default precision.
2778
2779Press @kbd{U} enough times to get the original big integer back.
2780(Notice that @kbd{U} does not undo each mode-setting command; if
2781you want to undo a mode-setting command, you have to do it yourself.)
2782Now, type @kbd{d r 16 @key{RET}}:
2783
2784@example
278516#200000000000000000000
2786@end example
2787
2788@noindent
2789The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
2790Suddenly it looks pretty simple; this should be no surprise, since we
2791got this number by computing a power of two, and 16 is a power of 2.
2792In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
2793form:
2794
2795@example
27962#1000000000000000000000000000000000000000000000000000000 @dots{}
2797@end example
2798
2799@noindent
2800We don't have enough space here to show all the zeros! They won't
2801fit on a typical screen, either, so you will have to use horizontal
2802scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the
2803stack window left and right by half its width. Another way to view
2804something large is to press @kbd{`} (back-quote) to edit the top of
2805stack in a separate window. (Press @kbd{M-# M-#} when you are done.)
2806
2807You can enter non-decimal numbers using the @kbd{#} symbol, too.
2808Let's see what the hexadecimal number @samp{5FE} looks like in
2809binary. Type @kbd{16#5FE} (the letters can be typed in upper or
2810lower case; they will always appear in upper case). It will also
2811help to turn grouping on with @kbd{d g}:
2812
2813@example
28142#101,1111,1110
2815@end example
2816
2817Notice that @kbd{d g} groups by fours by default if the display radix
2818is binary or hexadecimal, but by threes if it is decimal, octal, or any
2819other radix.
2820
2821Now let's see that number in decimal; type @kbd{d r 10}:
2822
2823@example
28241,534
2825@end example
2826
2827Numbers are not @emph{stored} with any particular radix attached. They're
2828just numbers; they can be entered in any radix, and are always displayed
2829in whatever radix you've chosen with @kbd{d r}. The current radix applies
2830to integers, fractions, and floats.
2831
2832@cindex Roundoff errors, in non-decimal numbers
2833(@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third
2834as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got
2835@samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied
2836that by three, he got @samp{3#0.222222...} instead of the expected
2837@samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief,
2838saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got
2839@samp{3#0.10000001} (some zeros omitted). What's going on here?
2840@xref{Modes Answer 1, 1}. (@bullet{})
2841
2842@cindex Scientific notation, in non-decimal numbers
2843(@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal
2844modes in the natural way (the exponent is a power of the radix instead of
2845a power of ten, although the exponent itself is always written in decimal).
2846Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number
2847@samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}.
2848What is wrong with this picture? What could we write instead that would
2849work better? @xref{Modes Answer 2, 2}. (@bullet{})
2850
2851The @kbd{m} prefix key has another set of modes, relating to the way
2852Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix
2853modes generally affect the way things look, @kbd{m}-prefix modes affect
2854the way they are actually computed.
2855
2856The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice
2857the @samp{Deg} indicator in the mode line. This means that if you use
2858a command that interprets a number as an angle, it will assume the
2859angle is measured in degrees. For example,
2860
2861@group
2862@smallexample
28631: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5
2864 . . . .
2865
2866 45 S 2 ^ c 1
2867@end smallexample
2868@end group
2869
2870@noindent
2871The shift-@kbd{S} command computes the sine of an angle. The sine
2872of 45 degrees is @c{$\sqrt{2}/2$}
2873@cite{sqrt(2)/2}; squaring this yields @cite{2/4 = 0.5}.
2874However, there has been a slight roundoff error because the
2875representation of @c{$\sqrt{2}/2$}
2876@cite{sqrt(2)/2} wasn't exact. The @kbd{c 1}
2877command is a handy way to clean up numbers in this case; it
2878temporarily reduces the precision by one digit while it
2879re-rounds the number on the top of the stack.
2880
2881@cindex Roundoff errors, examples
2882(@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine
2883of 45 degrees as shown above, then, hoping to avoid an inexact
2884result, he increased the precision to 16 digits before squaring.
2885What happened? @xref{Modes Answer 3, 3}. (@bullet{})
2886
2887To do this calculation in radians, we would type @kbd{m r} first.
2888(The indicator changes to @samp{Rad}.) 45 degrees corresponds to
2889@c{$\pi\over4$}
2890@cite{pi/4} radians. To get @c{$\pi$}
2891@cite{pi}, press the @kbd{P} key. (Once
2892again, this is a shifted capital @kbd{P}. Remember, unshifted
2893@kbd{p} sets the precision.)
2894
2895@group
2896@smallexample
28971: 3.14159265359 1: 0.785398163398 1: 0.707106781187
2898 . . .
2899
2900 P 4 / m r S
2901@end smallexample
2902@end group
2903
2904Likewise, inverse trigonometric functions generate results in
2905either radians or degrees, depending on the current angular mode.
2906
2907@group
2908@smallexample
29091: 0.707106781187 1: 0.785398163398 1: 45.
2910 . . .
2911
2912 .5 Q m r I S m d U I S
2913@end smallexample
2914@end group
2915
2916@noindent
2917Here we compute the Inverse Sine of @c{$\sqrt{0.5}$}
2918@cite{sqrt(0.5)}, first in
2919radians, then in degrees.
2920
2921Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
2922and vice-versa.
2923
2924@group
2925@smallexample
29261: 45 1: 0.785398163397 1: 45.
2927 . . .
2928
2929 45 c r c d
2930@end smallexample
2931@end group
2932
2933Another interesting mode is @dfn{fraction mode}. Normally,
2934dividing two integers produces a floating-point result if the
2935quotient can't be expressed as an exact integer. Fraction mode
2936causes integer division to produce a fraction, i.e., a rational
2937number, instead.
2938
2939@group
2940@smallexample
29412: 12 1: 1.33333333333 1: 4:3
29421: 9 . .
2943 .
2944
2945 12 RET 9 / m f U / m f
2946@end smallexample
2947@end group
2948
2949@noindent
2950In the first case, we get an approximate floating-point result.
2951In the second case, we get an exact fractional result (four-thirds).
2952
2953You can enter a fraction at any time using @kbd{:} notation.
2954(Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
2955because @kbd{/} is already used to divide the top two stack
2956elements.) Calculations involving fractions will always
2957produce exact fractional results; fraction mode only says
2958what to do when dividing two integers.
2959
2960@cindex Fractions vs. floats
2961@cindex Floats vs. fractions
2962(@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact,
2963why would you ever use floating-point numbers instead?
2964@xref{Modes Answer 4, 4}. (@bullet{})
2965
2966Typing @kbd{m f} doesn't change any existing values in the stack.
2967In the above example, we had to Undo the division and do it over
2968again when we changed to fraction mode. But if you use the
2969evaluates-to operator you can get commands like @kbd{m f} to
2970recompute for you.
2971
2972@group
2973@smallexample
29741: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3
2975 . . .
2976
2977 ' 12/9 => RET p 4 RET m f
2978@end smallexample
2979@end group
2980
2981@noindent
2982In this example, the righthand side of the @samp{=>} operator
2983on the stack is recomputed when we change the precision, then
2984again when we change to fraction mode. All @samp{=>} expressions
2985on the stack are recomputed every time you change any mode that
2986might affect their values.
2987
2988@node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
2989@section Arithmetic Tutorial
2990
2991@noindent
2992In this section, we explore the arithmetic and scientific functions
2993available in the Calculator.
2994
2995The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
2996and @kbd{^}. Each normally takes two numbers from the top of the stack
2997and pushes back a result. The @kbd{n} and @kbd{&} keys perform
2998change-sign and reciprocal operations, respectively.
2999
3000@group
3001@smallexample
30021: 5 1: 0.2 1: 5. 1: -5. 1: 5.
3003 . . . . .
3004
3005 5 & & n n
3006@end smallexample
3007@end group
3008
3009@cindex Binary operators
3010You can apply a ``binary operator'' like @kbd{+} across any number of
3011stack entries by giving it a numeric prefix. You can also apply it
3012pairwise to several stack elements along with the top one if you use
3013a negative prefix.
3014
3015@group
3016@smallexample
30173: 2 1: 9 3: 2 4: 2 3: 12
30182: 3 . 2: 3 3: 3 2: 13
30191: 4 1: 4 2: 4 1: 14
3020 . . 1: 10 .
3021 .
3022
30232 RET 3 RET 4 M-3 + U 10 M-- M-3 +
3024@end smallexample
3025@end group
3026
3027@cindex Unary operators
3028You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
3029stack entries with a numeric prefix, too.
3030
3031@group
3032@smallexample
30333: 2 3: 0.5 3: 0.5
30342: 3 2: 0.333333333333 2: 3.
30351: 4 1: 0.25 1: 4.
3036 . . .
3037
30382 RET 3 RET 4 M-3 & M-2 &
3039@end smallexample
3040@end group
3041
3042Notice that the results here are left in floating-point form.
3043We can convert them back to integers by pressing @kbd{F}, the
3044``floor'' function. This function rounds down to the next lower
3045integer. There is also @kbd{R}, which rounds to the nearest
3046integer.
3047
3048@group
3049@smallexample
30507: 2. 7: 2 7: 2
30516: 2.4 6: 2 6: 2
30525: 2.5 5: 2 5: 3
30534: 2.6 4: 2 4: 3
30543: -2. 3: -2 3: -2
30552: -2.4 2: -3 2: -2
30561: -2.6 1: -3 1: -3
3057 . . .
3058
3059 M-7 F U M-7 R
3060@end smallexample
3061@end group
3062
3063Since dividing-and-flooring (i.e., ``integer quotient'') is such a
3064common operation, Calc provides a special command for that purpose, the
3065backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which
3066computes the remainder that would arise from a @kbd{\} operation, i.e.,
3067the ``modulo'' of two numbers. For example,
3068
3069@group
3070@smallexample
30712: 1234 1: 12 2: 1234 1: 34
30721: 100 . 1: 100 .
3073 . .
3074
30751234 RET 100 \ U %
3076@end smallexample
3077@end group
3078
3079These commands actually work for any real numbers, not just integers.
3080
3081@group
3082@smallexample
30832: 3.1415 1: 3 2: 3.1415 1: 0.1415
30841: 1 . 1: 1 .
3085 . .
3086
30873.1415 RET 1 \ U %
3088@end smallexample
3089@end group
3090
3091(@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a
3092frill, since you could always do the same thing with @kbd{/ F}. Think
3093of a situation where this is not true---@kbd{/ F} would be inadequate.
3094Now think of a way you could get around the problem if Calc didn't
3095provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{})
3096
3097We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
3098commands. Other commands along those lines are @kbd{C} (cosine),
3099@kbd{T} (tangent), @kbd{E} (@cite{e^x}) and @kbd{L} (natural
3100logarithm). These can be modified by the @kbd{I} (inverse) and
3101@kbd{H} (hyperbolic) prefix keys.
3102
3103Let's compute the sine and cosine of an angle, and verify the
3104identity @c{$\sin^2x + \cos^2x = 1$}
3105@cite{sin(x)^2 + cos(x)^2 = 1}. We'll
3106arbitrarily pick @i{-64} degrees as a good value for @cite{x}. With
3107the angular mode set to degrees (type @w{@kbd{m d}}), do:
3108
3109@group
3110@smallexample
31112: -64 2: -64 2: -0.89879 2: -0.89879 1: 1.
31121: -64 1: -0.89879 1: -64 1: 0.43837 .
3113 . . . .
3114
3115 64 n RET RET S TAB C f h
3116@end smallexample
3117@end group
3118
3119@noindent
3120(For brevity, we're showing only five digits of the results here.
3121You can of course do these calculations to any precision you like.)
3122
3123Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
3124of squares, command.
3125
3126Another identity is @c{$\displaystyle\tan x = {\sin x \over \cos x}$}
3127@cite{tan(x) = sin(x) / cos(x)}.
3128@group
3129@smallexample
3130
31312: -0.89879 1: -2.0503 1: -64.
31321: 0.43837 . .
3133 .
3134
3135 U / I T
3136@end smallexample
3137@end group
3138
3139A physical interpretation of this calculation is that if you move
3140@cite{0.89879} units downward and @cite{0.43837} units to the right,
3141your direction of motion is @i{-64} degrees from horizontal. Suppose
3142we move in the opposite direction, up and to the left:
3143
3144@group
3145@smallexample
31462: -0.89879 2: 0.89879 1: -2.0503 1: -64.
31471: 0.43837 1: -0.43837 . .
3148 . .
3149
3150 U U M-2 n / I T
3151@end smallexample
3152@end group
3153
3154@noindent
3155How can the angle be the same? The answer is that the @kbd{/} operation
3156loses information about the signs of its inputs. Because the quotient
3157is negative, we know exactly one of the inputs was negative, but we
3158can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which
3159computes the inverse tangent of the quotient of a pair of numbers.
3160Since you feed it the two original numbers, it has enough information
3161to give you a full 360-degree answer.
3162
3163@group
3164@smallexample
31652: 0.89879 1: 116. 3: 116. 2: 116. 1: 180.
31661: -0.43837 . 2: -0.89879 1: -64. .
3167 . 1: 0.43837 .
3168 .
3169
3170 U U f T M-RET M-2 n f T -
3171@end smallexample
3172@end group
3173
3174@noindent
3175The resulting angles differ by 180 degrees; in other words, they
3176point in opposite directions, just as we would expect.
3177
3178The @key{META}-@key{RET} we used in the third step is the
3179``last-arguments'' command. It is sort of like Undo, except that it
3180restores the arguments of the last command to the stack without removing
3181the command's result. It is useful in situations like this one,
3182where we need to do several operations on the same inputs. We could
3183have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
3184the top two stack elements right after the @kbd{U U}, then a pair of
3185@kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
3186
3187A similar identity is supposed to hold for hyperbolic sines and cosines,
3188except that it is the @emph{difference}
3189@c{$\cosh^2x - \sinh^2x$}
3190@cite{cosh(x)^2 - sinh(x)^2} that always equals one.
3191Let's try to verify this identity.@refill
3192
3193@group
3194@smallexample
31952: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54
31961: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54
3197 . . . . .
3198
3199 64 n RET RET H C 2 ^ TAB H S 2 ^
3200@end smallexample
3201@end group
3202
3203@noindent
3204@cindex Roundoff errors, examples
3205Something's obviously wrong, because when we subtract these numbers
3206the answer will clearly be zero! But if you think about it, if these
3207numbers @emph{did} differ by one, it would be in the 55th decimal
3208place. The difference we seek has been lost entirely to roundoff
3209error.
3210
3211We could verify this hypothesis by doing the actual calculation with,
3212say, 60 decimal places of precision. This will be slow, but not
3213enormously so. Try it if you wish; sure enough, the answer is
32140.99999, reasonably close to 1.
3215
3216Of course, a more reasonable way to verify the identity is to use
3217a more reasonable value for @cite{x}!
3218
3219@cindex Common logarithm
3220Some Calculator commands use the Hyperbolic prefix for other purposes.
3221The logarithm and exponential functions, for example, work to the base
3222@cite{e} normally but use base-10 instead if you use the Hyperbolic
3223prefix.
3224
3225@group
3226@smallexample
32271: 1000 1: 6.9077 1: 1000 1: 3
3228 . . . .
3229
3230 1000 L U H L
3231@end smallexample
3232@end group
3233
3234@noindent
3235First, we mistakenly compute a natural logarithm. Then we undo
3236and compute a common logarithm instead.
3237
3238The @kbd{B} key computes a general base-@var{b} logarithm for any
3239value of @var{b}.
3240
3241@group
3242@smallexample
32432: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077
32441: 10 . . 1: 2.71828 .
3245 . .
3246
3247 1000 RET 10 B H E H P B
3248@end smallexample
3249@end group
3250
3251@noindent
3252Here we first use @kbd{B} to compute the base-10 logarithm, then use
3253the ``hyperbolic'' exponential as a cheap hack to recover the number
32541000, then use @kbd{B} again to compute the natural logarithm. Note
3255that @kbd{P} with the hyperbolic prefix pushes the constant @cite{e}
3256onto the stack.
3257
3258You may have noticed that both times we took the base-10 logarithm
3259of 1000, we got an exact integer result. Calc always tries to give
3260an exact rational result for calculations involving rational numbers
3261where possible. But when we used @kbd{H E}, the result was a
3262floating-point number for no apparent reason. In fact, if we had
3263computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
3264exact integer 1000. But the @kbd{H E} command is rigged to generate
3265a floating-point result all of the time so that @kbd{1000 H E} will
3266not waste time computing a thousand-digit integer when all you
3267probably wanted was @samp{1e1000}.
3268
3269(@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to
3270the @kbd{B} command for which Calc could find an exact rational
3271result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{})
3272
3273The Calculator also has a set of functions relating to combinatorics
3274and statistics. You may be familiar with the @dfn{factorial} function,
3275which computes the product of all the integers up to a given number.
3276
3277@group
3278@smallexample
32791: 100 1: 93326215443... 1: 100. 1: 9.3326e157
3280 . . . .
3281
3282 100 ! U c f !
3283@end smallexample
3284@end group
3285
3286@noindent
3287Recall, the @kbd{c f} command converts the integer or fraction at the
3288top of the stack to floating-point format. If you take the factorial
3289of a floating-point number, you get a floating-point result
3290accurate to the current precision. But if you give @kbd{!} an
3291exact integer, you get an exact integer result (158 digits long
3292in this case).
3293
3294If you take the factorial of a non-integer, Calc uses a generalized
3295factorial function defined in terms of Euler's Gamma function
3296@c{$\Gamma(n)$}
3297@cite{gamma(n)}
3298(which is itself available as the @kbd{f g} command).
3299
3300@group
3301@smallexample
33023: 4. 3: 24. 1: 5.5 1: 52.342777847
33032: 4.5 2: 52.3427777847 . .
33041: 5. 1: 120.
3305 . .
3306
3307 M-3 ! M-0 DEL 5.5 f g
3308@end smallexample
3309@end group
3310
3311@noindent
3312Here we verify the identity @c{$n! = \Gamma(n+1)$}
3313@cite{@var{n}!@: = gamma(@var{n}+1)}.
3314
3315The binomial coefficient @var{n}-choose-@var{m}@c{ or $\displaystyle {n \choose m}$}
3316@asis{} is defined by
3317@c{$\displaystyle {n! \over m! \, (n-m)!}$}
3318@cite{n!@: / m!@: (n-m)!} for all reals @cite{n} and
3319@cite{m}. The intermediate results in this formula can become quite
3320large even if the final result is small; the @kbd{k c} command computes
3321a binomial coefficient in a way that avoids large intermediate
3322values.
3323
3324The @kbd{k} prefix key defines several common functions out of
3325combinatorics and number theory. Here we compute the binomial
3326coefficient 30-choose-20, then determine its prime factorization.
3327
3328@group
3329@smallexample
33302: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29]
33311: 20 . .
3332 .
3333
3334 30 RET 20 k c k f
3335@end smallexample
3336@end group
3337
3338@noindent
3339You can verify these prime factors by using @kbd{v u} to ``unpack''
3340this vector into 8 separate stack entries, then @kbd{M-8 *} to
3341multiply them back together. The result is the original number,
334230045015.
3343
3344@cindex Hash tables
3345Suppose a program you are writing needs a hash table with at least
334610000 entries. It's best to use a prime number as the actual size
3347of a hash table. Calc can compute the next prime number after 10000:
3348
3349@group
3350@smallexample
33511: 10000 1: 10007 1: 9973
3352 . . .
3353
3354 10000 k n I k n
3355@end smallexample
3356@end group
3357
3358@noindent
3359Just for kicks we've also computed the next prime @emph{less} than
336010000.
3361
3362@c [fix-ref Financial Functions]
3363@xref{Financial Functions}, for a description of the Calculator
3364commands that deal with business and financial calculations (functions
3365like @code{pv}, @code{rate}, and @code{sln}).
3366
3367@c [fix-ref Binary Number Functions]
3368@xref{Binary Functions}, to read about the commands for operating
3369on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
3370
3371@node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
3372@section Vector/Matrix Tutorial
3373
3374@noindent
3375A @dfn{vector} is a list of numbers or other Calc data objects.
3376Calc provides a large set of commands that operate on vectors. Some
3377are familiar operations from vector analysis. Others simply treat
3378a vector as a list of objects.
3379
3380@menu
3381* Vector Analysis Tutorial::
3382* Matrix Tutorial::
3383* List Tutorial::
3384@end menu
3385
3386@node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
3387@subsection Vector Analysis
3388
3389@noindent
3390If you add two vectors, the result is a vector of the sums of the
3391elements, taken pairwise.
3392
3393@group
3394@smallexample
33951: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3]
3396 . 1: [7, 6, 0] .
3397 .
3398
3399 [1,2,3] s 1 [7 6 0] s 2 +
3400@end smallexample
3401@end group
3402
3403@noindent
3404Note that we can separate the vector elements with either commas or
3405spaces. This is true whether we are using incomplete vectors or
3406algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these
3407vectors so we can easily reuse them later.
3408
3409If you multiply two vectors, the result is the sum of the products
3410of the elements taken pairwise. This is called the @dfn{dot product}
3411of the vectors.
3412
3413@group
3414@smallexample
34152: [1, 2, 3] 1: 19
34161: [7, 6, 0] .
3417 .
3418
3419 r 1 r 2 *
3420@end smallexample
3421@end group
3422
3423@cindex Dot product
3424The dot product of two vectors is equal to the product of their
3425lengths times the cosine of the angle between them. (Here the vector
3426is interpreted as a line from the origin @cite{(0,0,0)} to the
3427specified point in three-dimensional space.) The @kbd{A}
3428(absolute value) command can be used to compute the length of a
3429vector.
3430
3431@group
3432@smallexample
34333: 19 3: 19 1: 0.550782 1: 56.579
34342: [1, 2, 3] 2: 3.741657 . .
34351: [7, 6, 0] 1: 9.219544
3436 . .
3437
3438 M-RET M-2 A * / I C
3439@end smallexample
3440@end group
3441
3442@noindent
3443First we recall the arguments to the dot product command, then
3444we compute the absolute values of the top two stack entries to
3445obtain the lengths of the vectors, then we divide the dot product
3446by the product of the lengths to get the cosine of the angle.
3447The inverse cosine finds that the angle between the vectors
3448is about 56 degrees.
3449
3450@cindex Cross product
3451@cindex Perpendicular vectors
3452The @dfn{cross product} of two vectors is a vector whose length
3453is the product of the lengths of the inputs times the sine of the
3454angle between them, and whose direction is perpendicular to both
3455input vectors. Unlike the dot product, the cross product is
3456defined only for three-dimensional vectors. Let's double-check
3457our computation of the angle using the cross product.
3458
3459@group
3460@smallexample
34612: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579
34621: [7, 6, 0] 2: [1, 2, 3] . .
3463 . 1: [7, 6, 0]
3464 .
3465
3466 r 1 r 2 V C s 3 M-RET M-2 A * / A I S
3467@end smallexample
3468@end group
3469
3470@noindent
3471First we recall the original vectors and compute their cross product,
3472which we also store for later reference. Now we divide the vector
3473by the product of the lengths of the original vectors. The length of
3474this vector should be the sine of the angle; sure enough, it is!
3475
3476@c [fix-ref General Mode Commands]
3477Vector-related commands generally begin with the @kbd{v} prefix key.
3478Some are uppercase letters and some are lowercase. To make it easier
3479to type these commands, the shift-@kbd{V} prefix key acts the same as
3480the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all
3481prefix keys have this property.)
3482
3483If we take the dot product of two perpendicular vectors we expect
3484to get zero, since the cosine of 90 degrees is zero. Let's check
3485that the cross product is indeed perpendicular to both inputs:
3486
3487@group
3488@smallexample
34892: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0
34901: [-18, 21, -8] . 1: [-18, 21, -8] .
3491 . .
3492
3493 r 1 r 3 * DEL r 2 r 3 *
3494@end smallexample
3495@end group
3496
3497@cindex Normalizing a vector
3498@cindex Unit vectors
3499(@bullet{}) @strong{Exercise 1.} Given a vector on the top of the
3500stack, what keystrokes would you use to @dfn{normalize} the
3501vector, i.e., to reduce its length to one without changing its
3502direction? @xref{Vector Answer 1, 1}. (@bullet{})
3503
3504(@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be
3505at any of several positions along a ruler. You have a list of
3506those positions in the form of a vector, and another list of the
3507probabilities for the particle to be at the corresponding positions.
3508Find the average position of the particle.
3509@xref{Vector Answer 2, 2}. (@bullet{})
3510
3511@node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
3512@subsection Matrices
3513
3514@noindent
3515A @dfn{matrix} is just a vector of vectors, all the same length.
3516This means you can enter a matrix using nested brackets. You can
3517also use the semicolon character to enter a matrix. We'll show
3518both methods here:
3519
3520@group
3521@smallexample
35221: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3523 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3524 . .
3525
3526 [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] RET
3527@end smallexample
3528@end group
3529
3530@noindent
3531We'll be using this matrix again, so type @kbd{s 4} to save it now.
3532
3533Note that semicolons work with incomplete vectors, but they work
3534better in algebraic entry. That's why we use the apostrophe in
3535the second example.
3536
3537When two matrices are multiplied, the lefthand matrix must have
3538the same number of columns as the righthand matrix has rows.
3539Row @cite{i}, column @cite{j} of the result is effectively the
3540dot product of row @cite{i} of the left matrix by column @cite{j}
3541of the right matrix.
3542
3543If we try to duplicate this matrix and multiply it by itself,
3544the dimensions are wrong and the multiplication cannot take place:
3545
3546@group
3547@smallexample
35481: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ]
3549 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3550 .
3551
3552 RET *
3553@end smallexample
3554@end group
3555
3556@noindent
3557Though rather hard to read, this is a formula which shows the product
3558of two matrices. The @samp{*} function, having invalid arguments, has
3559been left in symbolic form.
3560
3561We can multiply the matrices if we @dfn{transpose} one of them first.
3562
3563@group
3564@smallexample
35652: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ]
3566 [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ]
35671: [ [ 1, 4 ] . [ 27, 36, 45 ] ]
3568 [ 2, 5 ] .
3569 [ 3, 6 ] ]
3570 .
3571
3572 U v t * U TAB *
3573@end smallexample
3574@end group
3575
3576Matrix multiplication is not commutative; indeed, switching the
3577order of the operands can even change the dimensions of the result
3578matrix, as happened here!
3579
3580If you multiply a plain vector by a matrix, it is treated as a
3581single row or column depending on which side of the matrix it is
3582on. The result is a plain vector which should also be interpreted
3583as a row or column as appropriate.
3584
3585@group
3586@smallexample
35872: [ [ 1, 2, 3 ] 1: [14, 32]
3588 [ 4, 5, 6 ] ] .
35891: [1, 2, 3]
3590 .
3591
3592 r 4 r 1 *
3593@end smallexample
3594@end group
3595
3596Multiplying in the other order wouldn't work because the number of
3597rows in the matrix is different from the number of elements in the
3598vector.
3599
3600(@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows
3601of the above @c{$2\times3$}
3602@asis{2x3} matrix to get @cite{[6, 15]}. Now use @samp{*} to
3603sum along the columns to get @cite{[5, 7, 9]}.
3604@xref{Matrix Answer 1, 1}. (@bullet{})
3605
3606@cindex Identity matrix
3607An @dfn{identity matrix} is a square matrix with ones along the
3608diagonal and zeros elsewhere. It has the property that multiplication
3609by an identity matrix, on the left or on the right, always produces
3610the original matrix.
3611
3612@group
3613@smallexample
36141: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3615 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3616 . 1: [ [ 1, 0, 0 ] .
3617 [ 0, 1, 0 ]
3618 [ 0, 0, 1 ] ]
3619 .
3620
3621 r 4 v i 3 RET *
3622@end smallexample
3623@end group
3624
3625If a matrix is square, it is often possible to find its @dfn{inverse},
3626that is, a matrix which, when multiplied by the original matrix, yields
3627an identity matrix. The @kbd{&} (reciprocal) key also computes the
3628inverse of a matrix.
3629
3630@group
3631@smallexample
36321: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ]
3633 [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ]
3634 [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ]
3635 . .
3636
3637 r 4 r 2 | s 5 &
3638@end smallexample
3639@end group
3640
3641@noindent
3642The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
3643matrices together. Here we have used it to add a new row onto
3644our matrix to make it square.
3645
3646We can multiply these two matrices in either order to get an identity.
3647
3648@group
3649@smallexample
36501: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ]
3651 [ 0., 1., 0. ] [ 0., 1., 0. ]
3652 [ 0., 0., 1. ] ] [ 0., 0., 1. ] ]
3653 . .
3654
3655 M-RET * U TAB *
3656@end smallexample
3657@end group
3658
3659@cindex Systems of linear equations
3660@cindex Linear equations, systems of
3661Matrix inverses are related to systems of linear equations in algebra.
3662Suppose we had the following set of equations:
3663
3664@ifinfo
3665@group
3666@example
3667 a + 2b + 3c = 6
3668 4a + 5b + 6c = 2
3669 7a + 6b = 3
3670@end example
3671@end group
3672@end ifinfo
3673@tex
3674\turnoffactive
3675\beforedisplayh
3676$$ \openup1\jot \tabskip=0pt plus1fil
3677\halign to\displaywidth{\tabskip=0pt
3678 $\hfil#$&$\hfil{}#{}$&
3679 $\hfil#$&$\hfil{}#{}$&
3680 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3681 a&+&2b&+&3c&=6 \cr
3682 4a&+&5b&+&6c&=2 \cr
3683 7a&+&6b& & &=3 \cr}
3684$$
3685\afterdisplayh
3686@end tex
3687
3688@noindent
3689This can be cast into the matrix equation,
3690
3691@ifinfo
3692@group
3693@example
3694 [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ]
3695 [ 4, 5, 6 ] * [ b ] = [ 2 ]
3696 [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]
3697@end example
3698@end group
3699@end ifinfo
3700@tex
3701\turnoffactive
3702\beforedisplay
3703$$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
3704 \times
3705 \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
3706$$
3707\afterdisplay
3708@end tex
3709
3710We can solve this system of equations by multiplying both sides by the
3711inverse of the matrix. Calc can do this all in one step:
3712
3713@group
3714@smallexample
37152: [6, 2, 3] 1: [-12.6, 15.2, -3.93333]
37161: [ [ 1, 2, 3 ] .
3717 [ 4, 5, 6 ]
3718 [ 7, 6, 0 ] ]
3719 .
3720
3721 [6,2,3] r 5 /
3722@end smallexample
3723@end group
3724
3725@noindent
3726The result is the @cite{[a, b, c]} vector that solves the equations.
3727(Dividing by a square matrix is equivalent to multiplying by its
3728inverse.)
3729
3730Let's verify this solution:
3731
3732@group
3733@smallexample
37342: [ [ 1, 2, 3 ] 1: [6., 2., 3.]
3735 [ 4, 5, 6 ] .
3736 [ 7, 6, 0 ] ]
37371: [-12.6, 15.2, -3.93333]
3738 .
3739
3740 r 5 TAB *
3741@end smallexample
3742@end group
3743
3744@noindent
3745Note that we had to be careful about the order in which we multiplied
3746the matrix and vector. If we multiplied in the other order, Calc would
3747assume the vector was a row vector in order to make the dimensions
3748come out right, and the answer would be incorrect. If you
3749don't feel safe letting Calc take either interpretation of your
3750vectors, use explicit @c{$N\times1$}
3751@asis{Nx1} or @c{$1\times N$}
3752@asis{1xN} matrices instead.
3753In this case, you would enter the original column vector as
3754@samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
3755
3756(@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make
3757vectors and matrices that include variables. Solve the following
3758system of equations to get expressions for @cite{x} and @cite{y}
3759in terms of @cite{a} and @cite{b}.
3760
3761@ifinfo
3762@group
3763@example
3764 x + a y = 6
3765 x + b y = 10
3766@end example
3767@end group
3768@end ifinfo
3769@tex
3770\turnoffactive
3771\beforedisplay
3772$$ \eqalign{ x &+ a y = 6 \cr
3773 x &+ b y = 10}
3774$$
3775\afterdisplay
3776@end tex
3777
3778@noindent
3779@xref{Matrix Answer 2, 2}. (@bullet{})
3780
3781@cindex Least-squares for over-determined systems
3782@cindex Over-determined systems of equations
3783(@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined''
3784if it has more equations than variables. It is often the case that
3785there are no values for the variables that will satisfy all the
3786equations at once, but it is still useful to find a set of values
3787which ``nearly'' satisfy all the equations. In terms of matrix equations,
3788you can't solve @cite{A X = B} directly because the matrix @cite{A}
3789is not square for an over-determined system. Matrix inversion works
3790only for square matrices. One common trick is to multiply both sides
3791on the left by the transpose of @cite{A}:
3792@ifinfo
3793@samp{trn(A)*A*X = trn(A)*B}.
3794@end ifinfo
3795@tex
3796\turnoffactive
3797$A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
3798@end tex
3799Now @c{$A^T A$}
3800@cite{trn(A)*A} is a square matrix so a solution is possible. It
3801turns out that the @cite{X} vector you compute in this way will be a
3802``least-squares'' solution, which can be regarded as the ``closest''
3803solution to the set of equations. Use Calc to solve the following
3804over-determined system:@refill
3805
3806@ifinfo
3807@group
3808@example
3809 a + 2b + 3c = 6
3810 4a + 5b + 6c = 2
3811 7a + 6b = 3
3812 2a + 4b + 6c = 11
3813@end example
3814@end group
3815@end ifinfo
3816@tex
3817\turnoffactive
3818\beforedisplayh
3819$$ \openup1\jot \tabskip=0pt plus1fil
3820\halign to\displaywidth{\tabskip=0pt
3821 $\hfil#$&$\hfil{}#{}$&
3822 $\hfil#$&$\hfil{}#{}$&
3823 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3824 a&+&2b&+&3c&=6 \cr
3825 4a&+&5b&+&6c&=2 \cr
3826 7a&+&6b& & &=3 \cr
3827 2a&+&4b&+&6c&=11 \cr}
3828$$
3829\afterdisplayh
3830@end tex
3831
3832@noindent
3833@xref{Matrix Answer 3, 3}. (@bullet{})
3834
3835@node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
3836@subsection Vectors as Lists
3837
3838@noindent
3839@cindex Lists
3840Although Calc has a number of features for manipulating vectors and
3841matrices as mathematical objects, you can also treat vectors as
3842simple lists of values. For example, we saw that the @kbd{k f}
3843command returns a vector which is a list of the prime factors of a
3844number.
3845
3846You can pack and unpack stack entries into vectors:
3847
3848@group
3849@smallexample
38503: 10 1: [10, 20, 30] 3: 10
38512: 20 . 2: 20
38521: 30 1: 30
3853 . .
3854
3855 M-3 v p v u
3856@end smallexample
3857@end group
3858
3859You can also build vectors out of consecutive integers, or out
3860of many copies of a given value:
3861
3862@group
3863@smallexample
38641: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4]
3865 . 1: 17 1: [17, 17, 17, 17]
3866 . .
3867
3868 v x 4 RET 17 v b 4 RET
3869@end smallexample
3870@end group
3871
3872You can apply an operator to every element of a vector using the
3873@dfn{map} command.
3874
3875@group
3876@smallexample
38771: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68]
3878 . . .
3879
3880 V M * 2 V M ^ V M Q
3881@end smallexample
3882@end group
3883
3884@noindent
3885In the first step, we multiply the vector of integers by the vector
3886of 17's elementwise. In the second step, we raise each element to
3887the power two. (The general rule is that both operands must be
3888vectors of the same length, or else one must be a vector and the
3889other a plain number.) In the final step, we take the square root
3890of each element.
3891
3892(@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two
3893from @c{$2^{-4}$}
3894@cite{2^-4} to @cite{2^4}. @xref{List Answer 1, 1}. (@bullet{})
3895
3896You can also @dfn{reduce} a binary operator across a vector.
3897For example, reducing @samp{*} computes the product of all the
3898elements in the vector:
3899
3900@group
3901@smallexample
39021: 123123 1: [3, 7, 11, 13, 41] 1: 123123
3903 . . .
3904
3905 123123 k f V R *
3906@end smallexample
3907@end group
3908
3909@noindent
3910In this example, we decompose 123123 into its prime factors, then
3911multiply those factors together again to yield the original number.
3912
3913We could compute a dot product ``by hand'' using mapping and
3914reduction:
3915
3916@group
3917@smallexample
39182: [1, 2, 3] 1: [7, 12, 0] 1: 19
39191: [7, 6, 0] . .
3920 .
3921
3922 r 1 r 2 V M * V R +
3923@end smallexample
3924@end group
3925
3926@noindent
3927Recalling two vectors from the previous section, we compute the
3928sum of pairwise products of the elements to get the same answer
3929for the dot product as before.
3930
3931A slight variant of vector reduction is the @dfn{accumulate} operation,
3932@kbd{V U}. This produces a vector of the intermediate results from
3933a corresponding reduction. Here we compute a table of factorials:
3934
3935@group
3936@smallexample
39371: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720]
3938 . .
3939
3940 v x 6 RET V U *
3941@end smallexample
3942@end group
3943
3944Calc allows vectors to grow as large as you like, although it gets
3945rather slow if vectors have more than about a hundred elements.
3946Actually, most of the time is spent formatting these large vectors
3947for display, not calculating on them. Try the following experiment
3948(if your computer is very fast you may need to substitute a larger
3949vector size).
3950
3951@group
3952@smallexample
39531: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ...
3954 . .
3955
3956 v x 500 RET 1 V M +
3957@end smallexample
3958@end group
3959
3960Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
3961experiment again. In @kbd{v .} mode, long vectors are displayed
3962``abbreviated'' like this:
3963
3964@group
3965@smallexample
39661: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501]
3967 . .
3968
3969 v x 500 RET 1 V M +
3970@end smallexample
3971@end group
3972
3973@noindent
3974(where now the @samp{...} is actually part of the Calc display).
3975You will find both operations are now much faster. But notice that
3976even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
3977Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
3978experiment one more time. Operations on long vectors are now quite
3979fast! (But of course if you use @kbd{t .} you will lose the ability
3980to get old vectors back using the @kbd{t y} command.)
3981
3982An easy way to view a full vector when @kbd{v .} mode is active is
3983to press @kbd{`} (back-quote) to edit the vector; editing always works
3984with the full, unabbreviated value.
3985
3986@cindex Least-squares for fitting a straight line
3987@cindex Fitting data to a line
3988@cindex Line, fitting data to
3989@cindex Data, extracting from buffers
3990@cindex Columns of data, extracting
3991As a larger example, let's try to fit a straight line to some data,
3992using the method of least squares. (Calc has a built-in command for
3993least-squares curve fitting, but we'll do it by hand here just to
3994practice working with vectors.) Suppose we have the following list
3995of values in a file we have loaded into Emacs:
3996
3997@smallexample
3998 x y
3999 --- ---
4000 1.34 0.234
4001 1.41 0.298
4002 1.49 0.402
4003 1.56 0.412
4004 1.64 0.466
4005 1.73 0.473
4006 1.82 0.601
4007 1.91 0.519
4008 2.01 0.603
4009 2.11 0.637
4010 2.22 0.645
4011 2.33 0.705
4012 2.45 0.917
4013 2.58 1.009
4014 2.71 0.971
4015 2.85 1.062
4016 3.00 1.148
4017 3.15 1.157
4018 3.32 1.354
4019@end smallexample
4020
4021@noindent
4022If you are reading this tutorial in printed form, you will find it
4023easiest to press @kbd{M-# i} to enter the on-line Info version of
4024the manual and find this table there. (Press @kbd{g}, then type
4025@kbd{List Tutorial}, to jump straight to this section.)
4026
4027Position the cursor at the upper-left corner of this table, just
4028to the left of the @cite{1.34}. Press @kbd{C-@@} to set the mark.
4029(On your system this may be @kbd{C-2}, @kbd{C-SPC}, or @kbd{NUL}.)
4030Now position the cursor to the lower-right, just after the @cite{1.354}.
4031You have now defined this region as an Emacs ``rectangle.'' Still
4032in the Info buffer, type @kbd{M-# r}. This command
4033(@code{calc-grab-rectangle}) will pop you back into the Calculator, with
4034the contents of the rectangle you specified in the form of a matrix.@refill
4035
4036@group
4037@smallexample
40381: [ [ 1.34, 0.234 ]
4039 [ 1.41, 0.298 ]
4040 @dots{}
4041@end smallexample
4042@end group
4043
4044@noindent
4045(You may wish to use @kbd{v .} mode to abbreviate the display of this
4046large matrix.)
4047
4048We want to treat this as a pair of lists. The first step is to
4049transpose this matrix into a pair of rows. Remember, a matrix is
4050just a vector of vectors. So we can unpack the matrix into a pair
4051of row vectors on the stack.
4052
4053@group
4054@smallexample
40551: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ]
4056 [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ]
4057 . .
4058
4059 v t v u
4060@end smallexample
4061@end group
4062
4063@noindent
4064Let's store these in quick variables 1 and 2, respectively.
4065
4066@group
4067@smallexample
40681: [1.34, 1.41, 1.49, ... ] .
4069 .
4070
4071 t 2 t 1
4072@end smallexample
4073@end group
4074
4075@noindent
4076(Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
4077stored value from the stack.)
4078
4079In a least squares fit, the slope @cite{m} is given by the formula
4080
4081@ifinfo
4082@example
4083m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
4084@end example
4085@end ifinfo
4086@tex
4087\turnoffactive
4088\beforedisplay
4089$$ m = {N \sum x y - \sum x \sum y \over
4090 N \sum x^2 - \left( \sum x \right)^2} $$
4091\afterdisplay
4092@end tex
4093
4094@noindent
4095where @c{$\sum x$}
4096@cite{sum(x)} represents the sum of all the values of @cite{x}.
4097While there is an actual @code{sum} function in Calc, it's easier to
4098sum a vector using a simple reduction. First, let's compute the four
4099different sums that this formula uses.
4100
4101@group
4102@smallexample
41031: 41.63 1: 98.0003
4104 . .
4105
4106 r 1 V R + t 3 r 1 2 V M ^ V R + t 4
4107
4108@end smallexample
4109@end group
4110@noindent
4111@group
4112@smallexample
41131: 13.613 1: 33.36554
4114 . .
4115
4116 r 2 V R + t 5 r 1 r 2 V M * V R + t 6
4117@end smallexample
4118@end group
4119
4120@ifinfo
4121@noindent
4122These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
4123respectively. (We could have used @kbd{*} to compute @samp{sum(x^2)} and
4124@samp{sum(x y)}.)
4125@end ifinfo
4126@tex
4127\turnoffactive
4128These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
4129respectively. (We could have used \kbd{*} to compute $\sum x^2$ and
4130$\sum x y$.)
4131@end tex
4132
4133Finally, we also need @cite{N}, the number of data points. This is just
4134the length of either of our lists.
4135
4136@group
4137@smallexample
41381: 19
4139 .
4140
4141 r 1 v l t 7
4142@end smallexample
4143@end group
4144
4145@noindent
4146(That's @kbd{v} followed by a lower-case @kbd{l}.)
4147
4148Now we grind through the formula:
4149
4150@group
4151@smallexample
41521: 633.94526 2: 633.94526 1: 67.23607
4153 . 1: 566.70919 .
4154 .
4155
4156 r 7 r 6 * r 3 r 5 * -
4157
4158@end smallexample
4159@end group
4160@noindent
4161@group
4162@smallexample
41632: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679
41641: 1862.0057 2: 1862.0057 1: 128.9488 .
4165 . 1: 1733.0569 .
4166 .
4167
4168 r 7 r 4 * r 3 2 ^ - / t 8
4169@end smallexample
4170@end group
4171
4172That gives us the slope @cite{m}. The y-intercept @cite{b} can now
4173be found with the simple formula,
4174
4175@ifinfo
4176@example
4177b = (sum(y) - m sum(x)) / N
4178@end example
4179@end ifinfo
4180@tex
4181\turnoffactive
4182\beforedisplay
4183$$ b = {\sum y - m \sum x \over N} $$
4184\afterdisplay
4185\vskip10pt
4186@end tex
4187
4188@group
4189@smallexample
41901: 13.613 2: 13.613 1: -8.09358 1: -0.425978
4191 . 1: 21.70658 . .
4192 .
4193
4194 r 5 r 8 r 3 * - r 7 / t 9
4195@end smallexample
4196@end group
4197
4198Let's ``plot'' this straight line approximation, @c{$y \approx m x + b$}
4199@cite{m x + b}, and compare it with the original data.@refill
4200
4201@group
4202@smallexample
42031: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ]
4204 . .
4205
4206 r 1 r 8 * r 9 + s 0
4207@end smallexample
4208@end group
4209
4210@noindent
4211Notice that multiplying a vector by a constant, and adding a constant
4212to a vector, can be done without mapping commands since these are
4213common operations from vector algebra. As far as Calc is concerned,
4214we've just been doing geometry in 19-dimensional space!
4215
4216We can subtract this vector from our original @cite{y} vector to get
4217a feel for the error of our fit. Let's find the maximum error:
4218
4219@group
4220@smallexample
42211: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897
4222 . . .
4223
4224 r 2 - V M A V R X
4225@end smallexample
4226@end group
4227
4228@noindent
4229First we compute a vector of differences, then we take the absolute
4230values of these differences, then we reduce the @code{max} function
4231across the vector. (The @code{max} function is on the two-key sequence
4232@kbd{f x}; because it is so common to use @code{max} in a vector
4233operation, the letters @kbd{X} and @kbd{N} are also accepted for
4234@code{max} and @code{min} in this context. In general, you answer
4235the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
4236invokes the function you want. You could have typed @kbd{V R f x} or
4237even @kbd{V R x max @key{RET}} if you had preferred.)
4238
4239If your system has the GNUPLOT program, you can see graphs of your
4240data and your straight line to see how well they match. (If you have
4241GNUPLOT 3.0, the following instructions will work regardless of the
4242kind of display you have. Some GNUPLOT 2.0, non-X-windows systems
4243may require additional steps to view the graphs.)
4244
4245Let's start by plotting the original data. Recall the ``@i{x}'' and ``@i{y}''
4246vectors onto the stack and press @kbd{g f}. This ``fast'' graphing
4247command does everything you need to do for simple, straightforward
4248plotting of data.
4249
4250@group
4251@smallexample
42522: [1.34, 1.41, 1.49, ... ]
42531: [0.234, 0.298, 0.402, ... ]
4254 .
4255
4256 r 1 r 2 g f
4257@end smallexample
4258@end group
4259
4260If all goes well, you will shortly get a new window containing a graph
4261of the data. (If not, contact your GNUPLOT or Calc installer to find
4262out what went wrong.) In the X window system, this will be a separate
4263graphics window. For other kinds of displays, the default is to
4264display the graph in Emacs itself using rough character graphics.
4265Press @kbd{q} when you are done viewing the character graphics.
4266
4267Next, let's add the line we got from our least-squares fit:
4268
4269@group
4270@smallexample
42712: [1.34, 1.41, 1.49, ... ]
42721: [0.273, 0.309, 0.351, ... ]
4273 .
4274
4275 DEL r 0 g a g p
4276@end smallexample
4277@end group
4278
4279It's not very useful to get symbols to mark the data points on this
4280second curve; you can type @kbd{g S g p} to remove them. Type @kbd{g q}
4281when you are done to remove the X graphics window and terminate GNUPLOT.
4282
4283(@bullet{}) @strong{Exercise 2.} An earlier exercise showed how to do
4284least squares fitting to a general system of equations. Our 19 data
4285points are really 19 equations of the form @cite{y_i = m x_i + b} for
4286different pairs of @cite{(x_i,y_i)}. Use the matrix-transpose method
4287to solve for @cite{m} and @cite{b}, duplicating the above result.
4288@xref{List Answer 2, 2}. (@bullet{})
4289
4290@cindex Geometric mean
4291(@bullet{}) @strong{Exercise 3.} If the input data do not form a
4292rectangle, you can use @w{@kbd{M-# g}} (@code{calc-grab-region})
4293to grab the data the way Emacs normally works with regions---it reads
4294left-to-right, top-to-bottom, treating line breaks the same as spaces.
4295Use this command to find the geometric mean of the following numbers.
4296(The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
4297
4298@example
42992.3 6 22 15.1 7
4300 15 14 7.5
4301 2.5
4302@end example
4303
4304@noindent
4305The @kbd{M-# g} command accepts numbers separated by spaces or commas,
4306with or without surrounding vector brackets.
4307@xref{List Answer 3, 3}. (@bullet{})
4308
4309@ifinfo
4310As another example, a theorem about binomial coefficients tells
4311us that the alternating sum of binomial coefficients
4312@var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
4313on up to @var{n}-choose-@var{n},
4314always comes out to zero. Let's verify this
4315for @cite{n=6}.@refill
4316@end ifinfo
4317@tex
4318As another example, a theorem about binomial coefficients tells
4319us that the alternating sum of binomial coefficients
4320${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
4321always comes out to zero. Let's verify this
4322for \cite{n=6}.
4323@end tex
4324
4325@group
4326@smallexample
43271: [1, 2, 3, 4, 5, 6, 7] 1: [0, 1, 2, 3, 4, 5, 6]
4328 . .
4329
4330 v x 7 RET 1 -
4331
4332@end smallexample
4333@end group
4334@noindent
4335@group
4336@smallexample
43371: [1, -6, 15, -20, 15, -6, 1] 1: 0
4338 . .
4339
4340 V M ' (-1)^$ choose(6,$) RET V R +
4341@end smallexample
4342@end group
4343
4344The @kbd{V M '} command prompts you to enter any algebraic expression
4345to define the function to map over the vector. The symbol @samp{$}
4346inside this expression represents the argument to the function.
4347The Calculator applies this formula to each element of the vector,
4348substituting each element's value for the @samp{$} sign(s) in turn.
4349
4350To define a two-argument function, use @samp{$$} for the first
4351argument and @samp{$} for the second: @kbd{V M ' $$-$ RET} is
4352equivalent to @kbd{V M -}. This is analogous to regular algebraic
4353entry, where @samp{$$} would refer to the next-to-top stack entry
4354and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ RET}
4355would act exactly like @kbd{-}.
4356
4357Notice that the @kbd{V M '} command has recorded two things in the
4358trail: The result, as usual, and also a funny-looking thing marked
4359@samp{oper} that represents the operator function you typed in.
4360The function is enclosed in @samp{< >} brackets, and the argument is
4361denoted by a @samp{#} sign. If there were several arguments, they
4362would be shown as @samp{#1}, @samp{#2}, and so on. (For example,
4363@kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
4364trail.) This object is a ``nameless function''; you can use nameless
4365@w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
4366Nameless function notation has the interesting, occasionally useful
4367property that a nameless function is not actually evaluated until
4368it is used. For example, @kbd{V M ' $+random(2.0)} evaluates
4369@samp{random(2.0)} once and adds that random number to all elements
4370of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
4371@samp{random(2.0)} separately for each vector element.
4372
4373Another group of operators that are often useful with @kbd{V M} are
4374the relational operators: @kbd{a =}, for example, compares two numbers
4375and gives the result 1 if they are equal, or 0 if not. Similarly,
4376@w{@kbd{a <}} checks for one number being less than another.
4377
4378Other useful vector operations include @kbd{v v}, to reverse a
4379vector end-for-end; @kbd{V S}, to sort the elements of a vector
4380into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
4381one row or column of a matrix, or (in both cases) to extract one
4382element of a plain vector. With a negative argument, @kbd{v r}
4383and @kbd{v c} instead delete one row, column, or vector element.
4384
4385@cindex Divisor functions
4386(@bullet{}) @strong{Exercise 4.} The @cite{k}th @dfn{divisor function}
4387@tex
4388$\sigma_k(n)$
4389@end tex
4390is the sum of the @cite{k}th powers of all the divisors of an
4391integer @cite{n}. Figure out a method for computing the divisor
4392function for reasonably small values of @cite{n}. As a test,
4393the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
4394@xref{List Answer 4, 4}. (@bullet{})
4395
4396@cindex Square-free numbers
4397@cindex Duplicate values in a list
4398(@bullet{}) @strong{Exercise 5.} The @kbd{k f} command produces a
4399list of prime factors for a number. Sometimes it is important to
4400know that a number is @dfn{square-free}, i.e., that no prime occurs
4401more than once in its list of prime factors. Find a sequence of
4402keystrokes to tell if a number is square-free; your method should
4403leave 1 on the stack if it is, or 0 if it isn't.
4404@xref{List Answer 5, 5}. (@bullet{})
4405
4406@cindex Triangular lists
4407(@bullet{}) @strong{Exercise 6.} Build a list of lists that looks
4408like the following diagram. (You may wish to use the @kbd{v /}
4409command to enable multi-line display of vectors.)
4410
4411@group
4412@smallexample
44131: [ [1],
4414 [1, 2],
4415 [1, 2, 3],
4416 [1, 2, 3, 4],
4417 [1, 2, 3, 4, 5],
4418 [1, 2, 3, 4, 5, 6] ]
4419@end smallexample
4420@end group
4421
4422@noindent
4423@xref{List Answer 6, 6}. (@bullet{})
4424
4425(@bullet{}) @strong{Exercise 7.} Build the following list of lists.
4426
4427@group
4428@smallexample
44291: [ [0],
4430 [1, 2],
4431 [3, 4, 5],
4432 [6, 7, 8, 9],
4433 [10, 11, 12, 13, 14],
4434 [15, 16, 17, 18, 19, 20] ]
4435@end smallexample
4436@end group
4437
4438@noindent
4439@xref{List Answer 7, 7}. (@bullet{})
4440
4441@cindex Maximizing a function over a list of values
4442@c [fix-ref Numerical Solutions]
4443(@bullet{}) @strong{Exercise 8.} Compute a list of values of Bessel's
4444@c{$J_1(x)$}
4445@cite{J1} function @samp{besJ(1,x)} for @cite{x} from 0 to 5
4446in steps of 0.25.
4447Find the value of @cite{x} (from among the above set of values) for
4448which @samp{besJ(1,x)} is a maximum. Use an ``automatic'' method,
4449i.e., just reading along the list by hand to find the largest value
4450is not allowed! (There is an @kbd{a X} command which does this kind
4451of thing automatically; @pxref{Numerical Solutions}.)
4452@xref{List Answer 8, 8}. (@bullet{})@refill
4453
4454@cindex Digits, vectors of
4455(@bullet{}) @strong{Exercise 9.} You are given an integer in the range
4456@c{$0 \le N < 10^m$}
4457@cite{0 <= N < 10^m} for @cite{m=12} (i.e., an integer of less than
4458twelve digits). Convert this integer into a vector of @cite{m}
4459digits, each in the range from 0 to 9. In vector-of-digits notation,
4460add one to this integer to produce a vector of @cite{m+1} digits
4461(since there could be a carry out of the most significant digit).
4462Convert this vector back into a regular integer. A good integer
4463to try is 25129925999. @xref{List Answer 9, 9}. (@bullet{})
4464
4465(@bullet{}) @strong{Exercise 10.} Your friend Joe tried to use
4466@kbd{V R a =} to test if all numbers in a list were equal. What
4467happened? How would you do this test? @xref{List Answer 10, 10}. (@bullet{})
4468
4469(@bullet{}) @strong{Exercise 11.} The area of a circle of radius one
4470is @c{$\pi$}
4471@cite{pi}. The area of the @c{$2\times2$}
4472@asis{2x2} square that encloses that
4473circle is 4. So if we throw @i{N} darts at random points in the square,
4474about @c{$\pi/4$}
4475@cite{pi/4} of them will land inside the circle. This gives us
4476an entertaining way to estimate the value of @c{$\pi$}
4477@cite{pi}. The @w{@kbd{k r}}
4478command picks a random number between zero and the value on the stack.
4479We could get a random floating-point number between @i{-1} and 1 by typing
4480@w{@kbd{2.0 k r 1 -}}. Build a vector of 100 random @cite{(x,y)} points in
4481this square, then use vector mapping and reduction to count how many
4482points lie inside the unit circle. Hint: Use the @kbd{v b} command.
4483@xref{List Answer 11, 11}. (@bullet{})
4484
4485@cindex Matchstick problem
4486(@bullet{}) @strong{Exercise 12.} The @dfn{matchstick problem} provides
4487another way to calculate @c{$\pi$}
4488@cite{pi}. Say you have an infinite field
4489of vertical lines with a spacing of one inch. Toss a one-inch matchstick
4490onto the field. The probability that the matchstick will land crossing
4491a line turns out to be @c{$2/\pi$}
4492@cite{2/pi}. Toss 100 matchsticks to estimate
4493@c{$\pi$}
4494@cite{pi}. (If you want still more fun, the probability that the GCD
4495(@w{@kbd{k g}}) of two large integers is one turns out to be @c{$6/\pi^2$}
4496@cite{6/pi^2}.
4497That provides yet another way to estimate @c{$\pi$}
4498@cite{pi}.)
4499@xref{List Answer 12, 12}. (@bullet{})
4500
4501(@bullet{}) @strong{Exercise 13.} An algebraic entry of a string in
4502double-quote marks, @samp{"hello"}, creates a vector of the numerical
4503(ASCII) codes of the characters (here, @cite{[104, 101, 108, 108, 111]}).
4504Sometimes it is convenient to compute a @dfn{hash code} of a string,
4505which is just an integer that represents the value of that string.
4506Two equal strings have the same hash code; two different strings
4507@dfn{probably} have different hash codes. (For example, Calc has
4508over 400 function names, but Emacs can quickly find the definition for
4509any given name because it has sorted the functions into ``buckets'' by
4510their hash codes. Sometimes a few names will hash into the same bucket,
4511but it is easier to search among a few names than among all the names.)
4512One popular hash function is computed as follows: First set @cite{h = 0}.
4513Then, for each character from the string in turn, set @cite{h = 3h + c_i}
4514where @cite{c_i} is the character's ASCII code. If we have 511 buckets,
4515we then take the hash code modulo 511 to get the bucket number. Develop a
4516simple command or commands for converting string vectors into hash codes.
4517The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
4518511 is 121. @xref{List Answer 13, 13}. (@bullet{})
4519
4520(@bullet{}) @strong{Exercise 14.} The @kbd{H V R} and @kbd{H V U}
4521commands do nested function evaluations. @kbd{H V U} takes a starting
4522value and a number of steps @var{n} from the stack; it then applies the
4523function you give to the starting value 0, 1, 2, up to @var{n} times
4524and returns a vector of the results. Use this command to create a
4525``random walk'' of 50 steps. Start with the two-dimensional point
4526@cite{(0,0)}; then take one step a random distance between @i{-1} and 1
4527in both @cite{x} and @cite{y}; then take another step, and so on. Use the
4528@kbd{g f} command to display this random walk. Now modify your random
4529walk to walk a unit distance, but in a random direction, at each step.
4530(Hint: The @code{sincos} function returns a vector of the cosine and
4531sine of an angle.) @xref{List Answer 14, 14}. (@bullet{})
4532
4533@node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
4534@section Types Tutorial
4535
4536@noindent
4537Calc understands a variety of data types as well as simple numbers.
4538In this section, we'll experiment with each of these types in turn.
4539
4540The numbers we've been using so far have mainly been either @dfn{integers}
4541or @dfn{floats}. We saw that floats are usually a good approximation to
4542the mathematical concept of real numbers, but they are only approximations
4543and are susceptible to roundoff error. Calc also supports @dfn{fractions},
4544which can exactly represent any rational number.
4545
4546@group
4547@smallexample
45481: 3628800 2: 3628800 1: 518400:7 1: 518414:7 1: 7:518414
4549 . 1: 49 . . .
4550 .
4551
4552 10 ! 49 RET : 2 + &
4553@end smallexample
4554@end group
4555
4556@noindent
4557The @kbd{:} command divides two integers to get a fraction; @kbd{/}
4558would normally divide integers to get a floating-point result.
4559Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
4560since the @kbd{:} would otherwise be interpreted as part of a
4561fraction beginning with 49.
4562
4563You can convert between floating-point and fractional format using
4564@kbd{c f} and @kbd{c F}:
4565
4566@group
4567@smallexample
45681: 1.35027217629e-5 1: 7:518414
4569 . .
4570
4571 c f c F
4572@end smallexample
4573@end group
4574
4575The @kbd{c F} command replaces a floating-point number with the
4576``simplest'' fraction whose floating-point representation is the
4577same, to within the current precision.
4578
4579@group
4580@smallexample
45811: 3.14159265359 1: 1146408:364913 1: 3.1416 1: 355:113
4582 . . . .
4583
4584 P c F DEL p 5 RET P c F
4585@end smallexample
4586@end group
4587
4588(@bullet{}) @strong{Exercise 1.} A calculation has produced the
4589result 1.26508260337. You suspect it is the square root of the
4590product of @c{$\pi$}
4591@cite{pi} and some rational number. Is it? (Be sure
4592to allow for roundoff error!) @xref{Types Answer 1, 1}. (@bullet{})
4593
4594@dfn{Complex numbers} can be stored in both rectangular and polar form.
4595
4596@group
4597@smallexample
45981: -9 1: (0, 3) 1: (3; 90.) 1: (6; 90.) 1: (2.4495; 45.)
4599 . . . . .
4600
4601 9 n Q c p 2 * Q
4602@end smallexample
4603@end group
4604
4605@noindent
4606The square root of @i{-9} is by default rendered in rectangular form
4607(@w{@cite{0 + 3i}}), but we can convert it to polar form (3 with a
4608phase angle of 90 degrees). All the usual arithmetic and scientific
4609operations are defined on both types of complex numbers.
4610
4611Another generalized kind of number is @dfn{infinity}. Infinity
4612isn't really a number, but it can sometimes be treated like one.
4613Calc uses the symbol @code{inf} to represent positive infinity,
4614i.e., a value greater than any real number. Naturally, you can
4615also write @samp{-inf} for minus infinity, a value less than any
4616real number. The word @code{inf} can only be input using
4617algebraic entry.
4618
4619@group
4620@smallexample
46212: inf 2: -inf 2: -inf 2: -inf 1: nan
46221: -17 1: -inf 1: -inf 1: inf .
4623 . . . .
4624
4625' inf RET 17 n * RET 72 + A +
4626@end smallexample
4627@end group
4628
4629@noindent
4630Since infinity is infinitely large, multiplying it by any finite
4631number (like @i{-17}) has no effect, except that since @i{-17}
4632is negative, it changes a plus infinity to a minus infinity.
4633(``A huge positive number, multiplied by @i{-17}, yields a huge
4634negative number.'') Adding any finite number to infinity also
4635leaves it unchanged. Taking an absolute value gives us plus
4636infinity again. Finally, we add this plus infinity to the minus
4637infinity we had earlier. If you work it out, you might expect
4638the answer to be @i{-72} for this. But the 72 has been completely
4639lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
4640the finite difference between them, if any, is indetectable.
4641So we say the result is @dfn{indeterminate}, which Calc writes
4642with the symbol @code{nan} (for Not A Number).
4643
4644Dividing by zero is normally treated as an error, but you can get
4645Calc to write an answer in terms of infinity by pressing @kbd{m i}
4646to turn on ``infinite mode.''
4647
4648@group
4649@smallexample
46503: nan 2: nan 2: nan 2: nan 1: nan
46512: 1 1: 1 / 0 1: uinf 1: uinf .
46521: 0 . . .
4653 .
4654
4655 1 RET 0 / m i U / 17 n * +
4656@end smallexample
4657@end group
4658
4659@noindent
4660Dividing by zero normally is left unevaluated, but after @kbd{m i}
4661it instead gives an infinite result. The answer is actually
4662@code{uinf}, ``undirected infinity.'' If you look at a graph of
4663@cite{1 / x} around @w{@cite{x = 0}}, you'll see that it goes toward
4664plus infinity as you approach zero from above, but toward minus
4665infinity as you approach from below. Since we said only @cite{1 / 0},
4666Calc knows that the answer is infinite but not in which direction.
4667That's what @code{uinf} means. Notice that multiplying @code{uinf}
4668by a negative number still leaves plain @code{uinf}; there's no
4669point in saying @samp{-uinf} because the sign of @code{uinf} is
4670unknown anyway. Finally, we add @code{uinf} to our @code{nan},
4671yielding @code{nan} again. It's easy to see that, because
4672@code{nan} means ``totally unknown'' while @code{uinf} means
4673``unknown sign but known to be infinite,'' the more mysterious
4674@code{nan} wins out when it is combined with @code{uinf}, or, for
4675that matter, with anything else.
4676
4677(@bullet{}) @strong{Exercise 2.} Predict what Calc will answer
4678for each of these formulas: @samp{inf / inf}, @samp{exp(inf)},
4679@samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
4680@samp{abs(uinf)}, @samp{ln(0)}.
4681@xref{Types Answer 2, 2}. (@bullet{})
4682
4683(@bullet{}) @strong{Exercise 3.} We saw that @samp{inf - inf = nan},
4684which stands for an unknown value. Can @code{nan} stand for
4685a complex number? Can it stand for infinity?
4686@xref{Types Answer 3, 3}. (@bullet{})
4687
4688@dfn{HMS forms} represent a value in terms of hours, minutes, and
4689seconds.
4690
4691@group
4692@smallexample
46931: 2@@ 30' 0" 1: 3@@ 30' 0" 2: 3@@ 30' 0" 1: 2.
4694 . . 1: 1@@ 45' 0." .
4695 .
4696
4697 2@@ 30' RET 1 + RET 2 / /
4698@end smallexample
4699@end group
4700
4701HMS forms can also be used to hold angles in degrees, minutes, and
4702seconds.
4703
4704@group
4705@smallexample
47061: 0.5 1: 26.56505 1: 26@@ 33' 54.18" 1: 0.44721
4707 . . . .
4708
4709 0.5 I T c h S
4710@end smallexample
4711@end group
4712
4713@noindent
4714First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
4715form, then we take the sine of that angle. Note that the trigonometric
4716functions will accept HMS forms directly as input.
4717
4718@cindex Beatles
4719(@bullet{}) @strong{Exercise 4.} The Beatles' @emph{Abbey Road} is
472047 minutes and 26 seconds long, and contains 17 songs. What is the
4721average length of a song on @emph{Abbey Road}? If the Extended Disco
4722Version of @emph{Abbey Road} added 20 seconds to the length of each
4723song, how long would the album be? @xref{Types Answer 4, 4}. (@bullet{})
4724
4725A @dfn{date form} represents a date, or a date and time. Dates must
4726be entered using algebraic entry. Date forms are surrounded by
4727@samp{< >} symbols; most standard formats for dates are recognized.
4728
4729@group
4730@smallexample
47312: <Sun Jan 13, 1991> 1: 2.25
47321: <6:00pm Thu Jan 10, 1991> .
4733 .
4734
4735' <13 Jan 1991>, <1/10/91, 6pm> RET -
4736@end smallexample
4737@end group
4738
4739@noindent
4740In this example, we enter two dates, then subtract to find the
4741number of days between them. It is also possible to add an
4742HMS form or a number (of days) to a date form to get another
4743date form.
4744
4745@group
4746@smallexample
47471: <4:45:59pm Mon Jan 14, 1991> 1: <2:50:59am Thu Jan 17, 1991>
4748 . .
4749
4750 t N 2 + 10@@ 5' +
4751@end smallexample
4752@end group
4753
4754@c [fix-ref Date Arithmetic]
4755@noindent
4756The @kbd{t N} (``now'') command pushes the current date and time on the
4757stack; then we add two days, ten hours and five minutes to the date and
4758time. Other date-and-time related commands include @kbd{t J}, which
4759does Julian day conversions, @kbd{t W}, which finds the beginning of
4760the week in which a date form lies, and @kbd{t I}, which increments a
4761date by one or several months. @xref{Date Arithmetic}, for more.
4762
4763(@bullet{}) @strong{Exercise 5.} How many days until the next
4764Friday the 13th? @xref{Types Answer 5, 5}. (@bullet{})
4765
4766(@bullet{}) @strong{Exercise 6.} How many leap years will there be
4767between now and the year 10001 A.D.? @xref{Types Answer 6, 6}. (@bullet{})
4768
4769@cindex Slope and angle of a line
4770@cindex Angle and slope of a line
4771An @dfn{error form} represents a mean value with an attached standard
4772deviation, or error estimate. Suppose our measurements indicate that
4773a certain telephone pole is about 30 meters away, with an estimated
4774error of 1 meter, and 8 meters tall, with an estimated error of 0.2
4775meters. What is the slope of a line from here to the top of the
4776pole, and what is the equivalent angle in degrees?
4777
4778@group
4779@smallexample
47801: 8 +/- 0.2 2: 8 +/- 0.2 1: 0.266 +/- 0.011 1: 14.93 +/- 0.594
4781 . 1: 30 +/- 1 . .
4782 .
4783
4784 8 p .2 RET 30 p 1 / I T
4785@end smallexample
4786@end group
4787
4788@noindent
4789This means that the angle is about 15 degrees, and, assuming our
4790original error estimates were valid standard deviations, there is about
4791a 60% chance that the result is correct within 0.59 degrees.
4792
4793@cindex Torus, volume of
4794(@bullet{}) @strong{Exercise 7.} The volume of a torus (a donut shape) is
4795@c{$2 \pi^2 R r^2$}
4796@w{@cite{2 pi^2 R r^2}} where @cite{R} is the radius of the circle that
4797defines the center of the tube and @cite{r} is the radius of the tube
4798itself. Suppose @cite{R} is 20 cm and @cite{r} is 4 cm, each known to
4799within 5 percent. What is the volume and the relative uncertainty of
4800the volume? @xref{Types Answer 7, 7}. (@bullet{})
4801
4802An @dfn{interval form} represents a range of values. While an
4803error form is best for making statistical estimates, intervals give
4804you exact bounds on an answer. Suppose we additionally know that
4805our telephone pole is definitely between 28 and 31 meters away,
4806and that it is between 7.7 and 8.1 meters tall.
4807
4808@group
4809@smallexample
48101: [7.7 .. 8.1] 2: [7.7 .. 8.1] 1: [0.24 .. 0.28] 1: [13.9 .. 16.1]
4811 . 1: [28 .. 31] . .
4812 .
4813
4814 [ 7.7 .. 8.1 ] [ 28 .. 31 ] / I T
4815@end smallexample
4816@end group
4817
4818@noindent
4819If our bounds were correct, then the angle to the top of the pole
4820is sure to lie in the range shown.
4821
4822The square brackets around these intervals indicate that the endpoints
4823themselves are allowable values. In other words, the distance to the
4824telephone pole is between 28 and 31, @emph{inclusive}. You can also
4825make an interval that is exclusive of its endpoints by writing
4826parentheses instead of square brackets. You can even make an interval
4827which is inclusive (``closed'') on one end and exclusive (``open'') on
4828the other.
4829
4830@group
4831@smallexample
48321: [1 .. 10) 1: (0.1 .. 1] 2: (0.1 .. 1] 1: (0.2 .. 3)
4833 . . 1: [2 .. 3) .
4834 .
4835
4836 [ 1 .. 10 ) & [ 2 .. 3 ) *
4837@end smallexample
4838@end group
4839
4840@noindent
4841The Calculator automatically keeps track of which end values should
4842be open and which should be closed. You can also make infinite or
4843semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
4844or both endpoints.
4845
4846(@bullet{}) @strong{Exercise 8.} What answer would you expect from
4847@samp{@w{1 /} @w{(0 .. 10)}}? What about @samp{@w{1 /} @w{(-10 .. 0)}}? What
4848about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
4849zero)? What about @samp{@w{1 /} @w{(-10 .. 10)}}?
4850@xref{Types Answer 8, 8}. (@bullet{})
4851
4852(@bullet{}) @strong{Exercise 9.} Two easy ways of squaring a number
4853are @kbd{RET *} and @w{@kbd{2 ^}}. Normally these produce the same
4854answer. Would you expect this still to hold true for interval forms?
4855If not, which of these will result in a larger interval?
4856@xref{Types Answer 9, 9}. (@bullet{})
4857
4858A @dfn{modulo form} is used for performing arithmetic modulo @i{M}.
4859For example, arithmetic involving time is generally done modulo 12
4860or 24 hours.
4861
4862@group
4863@smallexample
48641: 17 mod 24 1: 3 mod 24 1: 21 mod 24 1: 9 mod 24
4865 . . . .
4866
4867 17 M 24 RET 10 + n 5 /
4868@end smallexample
4869@end group
4870
4871@noindent
4872In this last step, Calc has found a new number which, when multiplied
4873by 5 modulo 24, produces the original number, 21. If @i{M} is prime
4874it is always possible to find such a number. For non-prime @i{M}
4875like 24, it is only sometimes possible.
4876
4877@group
4878@smallexample
48791: 10 mod 24 1: 16 mod 24 1: 1000000... 1: 16
4880 . . . .
4881
4882 10 M 24 RET 100 ^ 10 RET 100 ^ 24 %
4883@end smallexample
4884@end group
4885
4886@noindent
4887These two calculations get the same answer, but the first one is
4888much more efficient because it avoids the huge intermediate value
4889that arises in the second one.
4890
4891@cindex Fermat, primality test of
4892(@bullet{}) @strong{Exercise 10.} A theorem of Pierre de Fermat
4893says that @c{\w{$x^{n-1} \bmod n = 1$}}
4894@cite{x^(n-1) mod n = 1} if @cite{n} is a prime number
4895and @cite{x} is an integer less than @cite{n}. If @cite{n} is
4896@emph{not} a prime number, this will @emph{not} be true for most
4897values of @cite{x}. Thus we can test informally if a number is
4898prime by trying this formula for several values of @cite{x}.
4899Use this test to tell whether the following numbers are prime:
4900811749613, 15485863. @xref{Types Answer 10, 10}. (@bullet{})
4901
4902It is possible to use HMS forms as parts of error forms, intervals,
4903modulo forms, or as the phase part of a polar complex number.
4904For example, the @code{calc-time} command pushes the current time
4905of day on the stack as an HMS/modulo form.
4906
4907@group
4908@smallexample
49091: 17@@ 34' 45" mod 24@@ 0' 0" 1: 6@@ 22' 15" mod 24@@ 0' 0"
4910 . .
4911
4912 x time RET n
4913@end smallexample
4914@end group
4915
4916@noindent
4917This calculation tells me it is six hours and 22 minutes until midnight.
4918
4919(@bullet{}) @strong{Exercise 11.} A rule of thumb is that one year
4920is about @c{$\pi \times 10^7$}
4921@w{@cite{pi * 10^7}} seconds. What time will it be that
4922many seconds from right now? @xref{Types Answer 11, 11}. (@bullet{})
4923
4924(@bullet{}) @strong{Exercise 12.} You are preparing to order packaging
4925for the CD release of the Extended Disco Version of @emph{Abbey Road}.
4926You are told that the songs will actually be anywhere from 20 to 60
4927seconds longer than the originals. One CD can hold about 75 minutes
4928of music. Should you order single or double packages?
4929@xref{Types Answer 12, 12}. (@bullet{})
4930
4931Another kind of data the Calculator can manipulate is numbers with
4932@dfn{units}. This isn't strictly a new data type; it's simply an
4933application of algebraic expressions, where we use variables with
4934suggestive names like @samp{cm} and @samp{in} to represent units
4935like centimeters and inches.
4936
4937@group
4938@smallexample
49391: 2 in 1: 5.08 cm 1: 0.027778 fath 1: 0.0508 m
4940 . . . .
4941
4942 ' 2in RET u c cm RET u c fath RET u b
4943@end smallexample
4944@end group
4945
4946@noindent
4947We enter the quantity ``2 inches'' (actually an algebraic expression
4948which means two times the variable @samp{in}), then we convert it
4949first to centimeters, then to fathoms, then finally to ``base'' units,
4950which in this case means meters.
4951
4952@group
4953@smallexample
49541: 9 acre 1: 3 sqrt(acre) 1: 190.84 m 1: 190.84 m + 30 cm
4955 . . . .
4956
4957 ' 9 acre RET Q u s ' $+30 cm RET
4958
4959@end smallexample
4960@end group
4961@noindent
4962@group
4963@smallexample
49641: 191.14 m 1: 36536.3046 m^2 1: 365363046 cm^2
4965 . . .
4966
4967 u s 2 ^ u c cgs
4968@end smallexample
4969@end group
4970
4971@noindent
4972Since units expressions are really just formulas, taking the square
4973root of @samp{acre} is undefined. After all, @code{acre} might be an
4974algebraic variable that you will someday assign a value. We use the
4975``units-simplify'' command to simplify the expression with variables
4976being interpreted as unit names.
4977
4978In the final step, we have converted not to a particular unit, but to a
4979units system. The ``cgs'' system uses centimeters instead of meters
4980as its standard unit of length.
4981
4982There is a wide variety of units defined in the Calculator.
4983
4984@group
4985@smallexample
49861: 55 mph 1: 88.5139 kph 1: 88.5139 km / hr 1: 8.201407e-8 c
4987 . . . .
4988
4989 ' 55 mph RET u c kph RET u c km/hr RET u c c RET
4990@end smallexample
4991@end group
4992
4993@noindent
4994We express a speed first in miles per hour, then in kilometers per
4995hour, then again using a slightly more explicit notation, then
4996finally in terms of fractions of the speed of light.
4997
4998Temperature conversions are a bit more tricky. There are two ways to
4999interpret ``20 degrees Fahrenheit''---it could mean an actual
5000temperature, or it could mean a change in temperature. For normal
5001units there is no difference, but temperature units have an offset
5002as well as a scale factor and so there must be two explicit commands
5003for them.
5004
5005@group
5006@smallexample
50071: 20 degF 1: 11.1111 degC 1: -20:3 degC 1: -6.666 degC
5008 . . . .
5009
5010 ' 20 degF RET u c degC RET U u t degC RET c f
5011@end smallexample
5012@end group
5013
5014@noindent
5015First we convert a change of 20 degrees Fahrenheit into an equivalent
5016change in degrees Celsius (or Centigrade). Then, we convert the
5017absolute temperature 20 degrees Fahrenheit into Celsius. Since
5018this comes out as an exact fraction, we then convert to floating-point
5019for easier comparison with the other result.
5020
5021For simple unit conversions, you can put a plain number on the stack.
5022Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
5023When you use this method, you're responsible for remembering which
5024numbers are in which units:
5025
5026@group
5027@smallexample
50281: 55 1: 88.5139 1: 8.201407e-8
5029 . . .
5030
5031 55 u c mph RET kph RET u c km/hr RET c RET
5032@end smallexample
5033@end group
5034
5035To see a complete list of built-in units, type @kbd{u v}. Press
5036@w{@kbd{M-# c}} again to re-enter the Calculator when you're done looking
5037at the units table.
5038
5039(@bullet{}) @strong{Exercise 13.} How many seconds are there really
5040in a year? @xref{Types Answer 13, 13}. (@bullet{})
5041
5042@cindex Speed of light
5043(@bullet{}) @strong{Exercise 14.} Supercomputer designs are limited by
5044the speed of light (and of electricity, which is nearly as fast).
5045Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
5046cabinet is one meter across. Is speed of light going to be a
5047significant factor in its design? @xref{Types Answer 14, 14}. (@bullet{})
5048
5049(@bullet{}) @strong{Exercise 15.} Sam the Slug normally travels about
5050five yards in an hour. He has obtained a supply of Power Pills; each
5051Power Pill he eats doubles his speed. How many Power Pills can he
5052swallow and still travel legally on most US highways?
5053@xref{Types Answer 15, 15}. (@bullet{})
5054
5055@node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
5056@section Algebra and Calculus Tutorial
5057
5058@noindent
5059This section shows how to use Calc's algebra facilities to solve
5060equations, do simple calculus problems, and manipulate algebraic
5061formulas.
5062
5063@menu
5064* Basic Algebra Tutorial::
5065* Rewrites Tutorial::
5066@end menu
5067
5068@node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
5069@subsection Basic Algebra
5070
5071@noindent
5072If you enter a formula in algebraic mode that refers to variables,
5073the formula itself is pushed onto the stack. You can manipulate
5074formulas as regular data objects.
5075
5076@group
5077@smallexample
50781: 2 x^2 - 6 1: 6 - 2 x^2 1: (6 - 2 x^2) (3 x^2 + y)
5079 . . .
5080
5081 ' 2x^2-6 RET n ' 3x^2+y RET *
5082@end smallexample
5083@end group
5084
5085(@bullet{}) @strong{Exercise 1.} Do @kbd{' x RET Q 2 ^} and
5086@kbd{' x RET 2 ^ Q} both wind up with the same result (@samp{x})?
5087Why or why not? @xref{Algebra Answer 1, 1}. (@bullet{})
5088
5089There are also commands for doing common algebraic operations on
5090formulas. Continuing with the formula from the last example,
5091
5092@group
5093@smallexample
50941: 18 x^2 + 6 y - 6 x^4 - 2 x^2 y 1: (18 - 2 y) x^2 - 6 x^4 + 6 y
5095 . .
5096
5097 a x a c x RET
5098@end smallexample
5099@end group
5100
5101@noindent
5102First we ``expand'' using the distributive law, then we ``collect''
5103terms involving like powers of @cite{x}.
5104
5105Let's find the value of this expression when @cite{x} is 2 and @cite{y}
5106is one-half.
5107
5108@group
5109@smallexample
51101: 17 x^2 - 6 x^4 + 3 1: -25
5111 . .
5112
5113 1:2 s l y RET 2 s l x RET
5114@end smallexample
5115@end group
5116
5117@noindent
5118The @kbd{s l} command means ``let''; it takes a number from the top of
5119the stack and temporarily assigns it as the value of the variable
5120you specify. It then evaluates (as if by the @kbd{=} key) the
5121next expression on the stack. After this command, the variable goes
5122back to its original value, if any.
5123
5124(An earlier exercise in this tutorial involved storing a value in the
5125variable @code{x}; if this value is still there, you will have to
5126unstore it with @kbd{s u x RET} before the above example will work
5127properly.)
5128
5129@cindex Maximum of a function using Calculus
5130Let's find the maximum value of our original expression when @cite{y}
5131is one-half and @cite{x} ranges over all possible values. We can
5132do this by taking the derivative with respect to @cite{x} and examining
5133values of @cite{x} for which the derivative is zero. If the second
5134derivative of the function at that value of @cite{x} is negative,
5135the function has a local maximum there.
5136
5137@group
5138@smallexample
51391: 17 x^2 - 6 x^4 + 3 1: 34 x - 24 x^3
5140 . .
5141
5142 U DEL s 1 a d x RET s 2
5143@end smallexample
5144@end group
5145
5146@noindent
5147Well, the derivative is clearly zero when @cite{x} is zero. To find
5148the other root(s), let's divide through by @cite{x} and then solve:
5149
5150@group
5151@smallexample
51521: (34 x - 24 x^3) / x 1: 34 x / x - 24 x^3 / x 1: 34 - 24 x^2
5153 . . .
5154
5155 ' x RET / a x a s
5156
5157@end smallexample
5158@end group
5159@noindent
5160@group
5161@smallexample
51621: 34 - 24 x^2 = 0 1: x = 1.19023
5163 . .
5164
5165 0 a = s 3 a S x RET
5166@end smallexample
5167@end group
5168
5169@noindent
5170Notice the use of @kbd{a s} to ``simplify'' the formula. When the
5171default algebraic simplifications don't do enough, you can use
5172@kbd{a s} to tell Calc to spend more time on the job.
5173
5174Now we compute the second derivative and plug in our values of @cite{x}:
5175
5176@group
5177@smallexample
51781: 1.19023 2: 1.19023 2: 1.19023
5179 . 1: 34 x - 24 x^3 1: 34 - 72 x^2
5180 . .
5181
5182 a . r 2 a d x RET s 4
5183@end smallexample
5184@end group
5185
5186@noindent
5187(The @kbd{a .} command extracts just the righthand side of an equation.
5188Another method would have been to use @kbd{v u} to unpack the equation
5189@w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 DEL}
5190to delete the @samp{x}.)
5191
5192@group
5193@smallexample
51942: 34 - 72 x^2 1: -68. 2: 34 - 72 x^2 1: 34
51951: 1.19023 . 1: 0 .
5196 . .
5197
5198 TAB s l x RET U DEL 0 s l x RET
5199@end smallexample
5200@end group
5201
5202@noindent
5203The first of these second derivatives is negative, so we know the function
5204has a maximum value at @cite{x = 1.19023}. (The function also has a
5205local @emph{minimum} at @cite{x = 0}.)
5206
5207When we solved for @cite{x}, we got only one value even though
5208@cite{34 - 24 x^2 = 0} is a quadratic equation that ought to have
5209two solutions. The reason is that @w{@kbd{a S}} normally returns a
5210single ``principal'' solution. If it needs to come up with an
5211arbitrary sign (as occurs in the quadratic formula) it picks @cite{+}.
5212If it needs an arbitrary integer, it picks zero. We can get a full
5213solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
5214
5215@group
5216@smallexample
52171: 34 - 24 x^2 = 0 1: x = 1.19023 s1 1: x = -1.19023
5218 . . .
5219
5220 r 3 H a S x RET s 5 1 n s l s1 RET
5221@end smallexample
5222@end group
5223
5224@noindent
5225Calc has invented the variable @samp{s1} to represent an unknown sign;
5226it is supposed to be either @i{+1} or @i{-1}. Here we have used
5227the ``let'' command to evaluate the expression when the sign is negative.
5228If we plugged this into our second derivative we would get the same,
5229negative, answer, so @cite{x = -1.19023} is also a maximum.
5230
5231To find the actual maximum value, we must plug our two values of @cite{x}
5232into the original formula.
5233
5234@group
5235@smallexample
52362: 17 x^2 - 6 x^4 + 3 1: 24.08333 s1^2 - 12.04166 s1^4 + 3
52371: x = 1.19023 s1 .
5238 .
5239
5240 r 1 r 5 s l RET
5241@end smallexample
5242@end group
5243
5244@noindent
5245(Here we see another way to use @kbd{s l}; if its input is an equation
5246with a variable on the lefthand side, then @kbd{s l} treats the equation
5247like an assignment to that variable if you don't give a variable name.)
5248
5249It's clear that this will have the same value for either sign of
5250@code{s1}, but let's work it out anyway, just for the exercise:
5251
5252@group
5253@smallexample
52542: [-1, 1] 1: [15.04166, 15.04166]
52551: 24.08333 s1^2 ... .
5256 .
5257
5258 [ 1 n , 1 ] TAB V M $ RET
5259@end smallexample
5260@end group
5261
5262@noindent
5263Here we have used a vector mapping operation to evaluate the function
5264at several values of @samp{s1} at once. @kbd{V M $} is like @kbd{V M '}
5265except that it takes the formula from the top of the stack. The
5266formula is interpreted as a function to apply across the vector at the
5267next-to-top stack level. Since a formula on the stack can't contain
5268@samp{$} signs, Calc assumes the variables in the formula stand for
5269different arguments. It prompts you for an @dfn{argument list}, giving
5270the list of all variables in the formula in alphabetical order as the
5271default list. In this case the default is @samp{(s1)}, which is just
5272what we want so we simply press @key{RET} at the prompt.
5273
5274If there had been several different values, we could have used
5275@w{@kbd{V R X}} to find the global maximum.
5276
5277Calc has a built-in @kbd{a P} command that solves an equation using
5278@w{@kbd{H a S}} and returns a vector of all the solutions. It simply
5279automates the job we just did by hand. Applied to our original
5280cubic polynomial, it would produce the vector of solutions
5281@cite{[1.19023, -1.19023, 0]}. (There is also an @kbd{a X} command
5282which finds a local maximum of a function. It uses a numerical search
5283method rather than examining the derivatives, and thus requires you
5284to provide some kind of initial guess to show it where to look.)
5285
5286(@bullet{}) @strong{Exercise 2.} Given a vector of the roots of a
5287polynomial (such as the output of an @kbd{a P} command), what
5288sequence of commands would you use to reconstruct the original
5289polynomial? (The answer will be unique to within a constant
5290multiple; choose the solution where the leading coefficient is one.)
5291@xref{Algebra Answer 2, 2}. (@bullet{})
5292
5293The @kbd{m s} command enables ``symbolic mode,'' in which formulas
5294like @samp{sqrt(5)} that can't be evaluated exactly are left in
5295symbolic form rather than giving a floating-point approximate answer.
5296Fraction mode (@kbd{m f}) is also useful when doing algebra.
5297
5298@group
5299@smallexample
53002: 34 x - 24 x^3 2: 34 x - 24 x^3
53011: 34 x - 24 x^3 1: [sqrt(51) / 6, sqrt(51) / -6, 0]
5302 . .
5303
5304 r 2 RET m s m f a P x RET
5305@end smallexample
5306@end group
5307
5308One more mode that makes reading formulas easier is ``Big mode.''
5309
5310@group
5311@smallexample
5312 3
53132: 34 x - 24 x
5314
5315 ____ ____
5316 V 51 V 51
53171: [-----, -----, 0]
5318 6 -6
5319
5320 .
5321
5322 d B
5323@end smallexample
5324@end group
5325
5326Here things like powers, square roots, and quotients and fractions
5327are displayed in a two-dimensional pictorial form. Calc has other
5328language modes as well, such as C mode, FORTRAN mode, and @TeX{} mode.
5329
5330@group
5331@smallexample
53322: 34*x - 24*pow(x, 3) 2: 34*x - 24*x**3
53331: @{sqrt(51) / 6, sqrt(51) / -6, 0@} 1: /sqrt(51) / 6, sqrt(51) / -6, 0/
5334 . .
5335
5336 d C d F
5337
5338@end smallexample
5339@end group
5340@noindent
5341@group
5342@smallexample
53433: 34 x - 24 x^3
53442: [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
53451: @{2 \over 3@} \sqrt@{5@}
5346 .
5347
5348 d T ' 2 \sqrt@{5@} \over 3 RET
5349@end smallexample
5350@end group
5351
5352@noindent
5353As you can see, language modes affect both entry and display of
5354formulas. They affect such things as the names used for built-in
5355functions, the set of arithmetic operators and their precedences,
5356and notations for vectors and matrices.
5357
5358Notice that @samp{sqrt(51)} may cause problems with older
5359implementations of C and FORTRAN, which would require something more
5360like @samp{sqrt(51.0)}. It is always wise to check over the formulas
5361produced by the various language modes to make sure they are fully
5362correct.
5363
5364Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes. (You
5365may prefer to remain in Big mode, but all the examples in the tutorial
5366are shown in normal mode.)
5367
5368@cindex Area under a curve
5369What is the area under the portion of this curve from @cite{x = 1} to @cite{2}?
5370This is simply the integral of the function:
5371
5372@group
5373@smallexample
53741: 17 x^2 - 6 x^4 + 3 1: 5.6666 x^3 - 1.2 x^5 + 3 x
5375 . .
5376
5377 r 1 a i x
5378@end smallexample
5379@end group
5380
5381@noindent
5382We want to evaluate this at our two values for @cite{x} and subtract.
5383One way to do it is again with vector mapping and reduction:
5384
5385@group
5386@smallexample
53872: [2, 1] 1: [12.93333, 7.46666] 1: 5.46666
53881: 5.6666 x^3 ... . .
5389
5390 [ 2 , 1 ] TAB V M $ RET V R -
5391@end smallexample
5392@end group
5393
5394(@bullet{}) @strong{Exercise 3.} Find the integral from 1 to @cite{y}
5395of @c{$x \sin \pi x$}
5396@w{@cite{x sin(pi x)}} (where the sine is calculated in radians).
5397Find the values of the integral for integers @cite{y} from 1 to 5.
5398@xref{Algebra Answer 3, 3}. (@bullet{})
5399
5400Calc's integrator can do many simple integrals symbolically, but many
5401others are beyond its capabilities. Suppose we wish to find the area
5402under the curve @c{$\sin x \ln x$}
5403@cite{sin(x) ln(x)} over the same range of @cite{x}. If
5404you entered this formula and typed @kbd{a i x RET} (don't bother to try
5405this), Calc would work for a long time but would be unable to find a
5406solution. In fact, there is no closed-form solution to this integral.
5407Now what do we do?
5408
5409@cindex Integration, numerical
5410@cindex Numerical integration
5411One approach would be to do the integral numerically. It is not hard
5412to do this by hand using vector mapping and reduction. It is rather
5413slow, though, since the sine and logarithm functions take a long time.
5414We can save some time by reducing the working precision.
5415
5416@group
5417@smallexample
54183: 10 1: [1, 1.1, 1.2, ... , 1.8, 1.9]
54192: 1 .
54201: 0.1
5421 .
5422
5423 10 RET 1 RET .1 RET C-u v x
5424@end smallexample
5425@end group
5426
5427@noindent
5428(Note that we have used the extended version of @kbd{v x}; we could
5429also have used plain @kbd{v x} as follows: @kbd{v x 10 RET 9 + .1 *}.)
5430
5431@group
5432@smallexample
54332: [1, 1.1, ... ] 1: [0., 0.084941, 0.16993, ... ]
54341: sin(x) ln(x) .
5435 .
5436
5437 ' sin(x) ln(x) RET s 1 m r p 5 RET V M $ RET
5438
5439@end smallexample
5440@end group
5441@noindent
5442@group
5443@smallexample
54441: 3.4195 0.34195
5445 . .
5446
5447 V R + 0.1 *
5448@end smallexample
5449@end group
5450
5451@noindent
5452(If you got wildly different results, did you remember to switch
5453to radians mode?)
5454
5455Here we have divided the curve into ten segments of equal width;
5456approximating these segments as rectangular boxes (i.e., assuming
5457the curve is nearly flat at that resolution), we compute the areas
5458of the boxes (height times width), then sum the areas. (It is
5459faster to sum first, then multiply by the width, since the width
5460is the same for every box.)
5461
5462The true value of this integral turns out to be about 0.374, so
5463we're not doing too well. Let's try another approach.
5464
5465@group
5466@smallexample
54671: sin(x) ln(x) 1: 0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
5468 . .
5469
5470 r 1 a t x=1 RET 4 RET
5471@end smallexample
5472@end group
5473
5474@noindent
5475Here we have computed the Taylor series expansion of the function
5476about the point @cite{x=1}. We can now integrate this polynomial
5477approximation, since polynomials are easy to integrate.
5478
5479@group
5480@smallexample
54811: 0.42074 x^2 + ... 1: [-0.0446, -0.42073] 1: 0.3761
5482 . . .
5483
5484 a i x RET [ 2 , 1 ] TAB V M $ RET V R -
5485@end smallexample
5486@end group
5487
5488@noindent
5489Better! By increasing the precision and/or asking for more terms
5490in the Taylor series, we can get a result as accurate as we like.
5491(Taylor series converge better away from singularities in the
5492function such as the one at @code{ln(0)}, so it would also help to
5493expand the series about the points @cite{x=2} or @cite{x=1.5} instead
5494of @cite{x=1}.)
5495
5496@cindex Simpson's rule
5497@cindex Integration by Simpson's rule
5498(@bullet{}) @strong{Exercise 4.} Our first method approximated the
5499curve by stairsteps of width 0.1; the total area was then the sum
5500of the areas of the rectangles under these stairsteps. Our second
5501method approximated the function by a polynomial, which turned out
5502to be a better approximation than stairsteps. A third method is
5503@dfn{Simpson's rule}, which is like the stairstep method except
5504that the steps are not required to be flat. Simpson's rule boils
5505down to the formula,
5506
5507@ifinfo
5508@example
5509(h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
5510 + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
5511@end example
5512@end ifinfo
5513@tex
5514\turnoffactive
5515\beforedisplay
5516$$ \displaylines{
5517 \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
5518 \hfill \cr \hfill {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
5519} $$
5520\afterdisplay
5521@end tex
5522
5523@noindent
5524where @cite{n} (which must be even) is the number of slices and @cite{h}
5525is the width of each slice. These are 10 and 0.1 in our example.
5526For reference, here is the corresponding formula for the stairstep
5527method:
5528
5529@ifinfo
5530@example
5531h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
5532 + f(a+(n-2)*h) + f(a+(n-1)*h))
5533@end example
5534@end ifinfo
5535@tex
5536\turnoffactive
5537\beforedisplay
5538$$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
5539 + f(a+(n-2)h) + f(a+(n-1)h)) $$
5540\afterdisplay
5541@end tex
5542
5543Compute the integral from 1 to 2 of @c{$\sin x \ln x$}
5544@cite{sin(x) ln(x)} using
5545Simpson's rule with 10 slices. @xref{Algebra Answer 4, 4}. (@bullet{})
5546
5547Calc has a built-in @kbd{a I} command for doing numerical integration.
5548It uses @dfn{Romberg's method}, which is a more sophisticated cousin
5549of Simpson's rule. In particular, it knows how to keep refining the
5550result until the current precision is satisfied.
5551
5552@c [fix-ref Selecting Sub-Formulas]
5553Aside from the commands we've seen so far, Calc also provides a
5554large set of commands for operating on parts of formulas. You
5555indicate the desired sub-formula by placing the cursor on any part
5556of the formula before giving a @dfn{selection} command. Selections won't
5557be covered in the tutorial; @pxref{Selecting Subformulas}, for
5558details and examples.
5559
5560@c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
5561@c to 2^((n-1)*(r-1)).
5562
5563@node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
5564@subsection Rewrite Rules
5565
5566@noindent
5567No matter how many built-in commands Calc provided for doing algebra,
5568there would always be something you wanted to do that Calc didn't have
5569in its repertoire. So Calc also provides a @dfn{rewrite rule} system
5570that you can use to define your own algebraic manipulations.
5571
5572Suppose we want to simplify this trigonometric formula:
5573
5574@group
5575@smallexample
55761: 1 / cos(x) - sin(x) tan(x)
5577 .
5578
5579 ' 1/cos(x) - sin(x) tan(x) RET s 1
5580@end smallexample
5581@end group
5582
5583@noindent
5584If we were simplifying this by hand, we'd probably replace the
5585@samp{tan} with a @samp{sin/cos} first, then combine over a common
5586denominator. There is no Calc command to do the former; the @kbd{a n}
5587algebra command will do the latter but we'll do both with rewrite
5588rules just for practice.
5589
5590Rewrite rules are written with the @samp{:=} symbol.
5591
5592@group
5593@smallexample
55941: 1 / cos(x) - sin(x)^2 / cos(x)
5595 .
5596
5597 a r tan(a) := sin(a)/cos(a) RET
5598@end smallexample
5599@end group
5600
5601@noindent
5602(The ``assignment operator'' @samp{:=} has several uses in Calc. All
5603by itself the formula @samp{tan(a) := sin(a)/cos(a)} doesn't do anything,
5604but when it is given to the @kbd{a r} command, that command interprets
5605it as a rewrite rule.)
5606
5607The lefthand side, @samp{tan(a)}, is called the @dfn{pattern} of the
5608rewrite rule. Calc searches the formula on the stack for parts that
5609match the pattern. Variables in a rewrite pattern are called
5610@dfn{meta-variables}, and when matching the pattern each meta-variable
5611can match any sub-formula. Here, the meta-variable @samp{a} matched
5612the actual variable @samp{x}.
5613
5614When the pattern part of a rewrite rule matches a part of the formula,
5615that part is replaced by the righthand side with all the meta-variables
5616substituted with the things they matched. So the result is
5617@samp{sin(x) / cos(x)}. Calc's normal algebraic simplifications then
5618mix this in with the rest of the original formula.
5619
5620To merge over a common denominator, we can use another simple rule:
5621
5622@group
5623@smallexample
56241: (1 - sin(x)^2) / cos(x)
5625 .
5626
5627 a r a/x + b/x := (a+b)/x RET
5628@end smallexample
5629@end group
5630
5631This rule points out several interesting features of rewrite patterns.
5632First, if a meta-variable appears several times in a pattern, it must
5633match the same thing everywhere. This rule detects common denominators
5634because the same meta-variable @samp{x} is used in both of the
5635denominators.
5636
5637Second, meta-variable names are independent from variables in the
5638target formula. Notice that the meta-variable @samp{x} here matches
5639the subformula @samp{cos(x)}; Calc never confuses the two meanings of
5640@samp{x}.
5641
5642And third, rewrite patterns know a little bit about the algebraic
5643properties of formulas. The pattern called for a sum of two quotients;
5644Calc was able to match a difference of two quotients by matching
5645@samp{a = 1}, @samp{b = -sin(x)^2}, and @samp{x = cos(x)}.
5646
5647@c [fix-ref Algebraic Properties of Rewrite Rules]
5648We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
5649the rule. It would have worked just the same in all cases. (If we
5650really wanted the rule to apply only to @samp{+} or only to @samp{-},
5651we could have used the @code{plain} symbol. @xref{Algebraic Properties
5652of Rewrite Rules}, for some examples of this.)
5653
5654One more rewrite will complete the job. We want to use the identity
5655@samp{sin(x)^2 + cos(x)^2 = 1}, but of course we must first rearrange
5656the identity in a way that matches our formula. The obvious rule
5657would be @samp{@w{1 - sin(x)^2} := cos(x)^2}, but a little thought shows
5658that the rule @samp{sin(x)^2 := 1 - cos(x)^2} will also work. The
5659latter rule has a more general pattern so it will work in many other
5660situations, too.
5661
5662@group
5663@smallexample
56641: (1 + cos(x)^2 - 1) / cos(x) 1: cos(x)
5665 . .
5666
5667 a r sin(x)^2 := 1 - cos(x)^2 RET a s
5668@end smallexample
5669@end group
5670
5671You may ask, what's the point of using the most general rule if you
5672have to type it in every time anyway? The answer is that Calc allows
5673you to store a rewrite rule in a variable, then give the variable
5674name in the @kbd{a r} command. In fact, this is the preferred way to
5675use rewrites. For one, if you need a rule once you'll most likely
5676need it again later. Also, if the rule doesn't work quite right you
5677can simply Undo, edit the variable, and run the rule again without
5678having to retype it.
5679
5680@group
5681@smallexample
5682' tan(x) := sin(x)/cos(x) RET s t tsc RET
5683' a/x + b/x := (a+b)/x RET s t merge RET
5684' sin(x)^2 := 1 - cos(x)^2 RET s t sinsqr RET
5685
56861: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
5687 . .
5688
5689 r 1 a r tsc RET a r merge RET a r sinsqr RET a s
5690@end smallexample
5691@end group
5692
5693To edit a variable, type @kbd{s e} and the variable name, use regular
5694Emacs editing commands as necessary, then type @kbd{M-# M-#} or
5695@kbd{C-c C-c} to store the edited value back into the variable.
5696You can also use @w{@kbd{s e}} to create a new variable if you wish.
5697
5698Notice that the first time you use each rule, Calc puts up a ``compiling''
5699message briefly. The pattern matcher converts rules into a special
5700optimized pattern-matching language rather than using them directly.
5701This allows @kbd{a r} to apply even rather complicated rules very
5702efficiently. If the rule is stored in a variable, Calc compiles it
5703only once and stores the compiled form along with the variable. That's
5704another good reason to store your rules in variables rather than
5705entering them on the fly.
5706
5707(@bullet{}) @strong{Exercise 1.} Type @kbd{m s} to get symbolic
5708mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
5709Using a rewrite rule, simplify this formula by multiplying both
5710sides by the conjugate @w{@samp{1 - sqrt(2)}}. The result will have
5711to be expanded by the distributive law; do this with another
5712rewrite. @xref{Rewrites Answer 1, 1}. (@bullet{})
5713
5714The @kbd{a r} command can also accept a vector of rewrite rules, or
5715a variable containing a vector of rules.
5716
5717@group
5718@smallexample
57191: [tsc, merge, sinsqr] 1: [tan(x) := sin(x) / cos(x), ... ]
5720 . .
5721
5722 ' [tsc,merge,sinsqr] RET =
5723
5724@end smallexample
5725@end group
5726@noindent
5727@group
5728@smallexample
57291: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
5730 . .
5731
5732 s t trig RET r 1 a r trig RET a s
5733@end smallexample
5734@end group
5735
5736@c [fix-ref Nested Formulas with Rewrite Rules]
5737Calc tries all the rules you give against all parts of the formula,
5738repeating until no further change is possible. (The exact order in
5739which things are tried is rather complex, but for simple rules like
5740the ones we've used here the order doesn't really matter.
5741@xref{Nested Formulas with Rewrite Rules}.)
5742
5743Calc actually repeats only up to 100 times, just in case your rule set
5744has gotten into an infinite loop. You can give a numeric prefix argument
5745to @kbd{a r} to specify any limit. In particular, @kbd{M-1 a r} does
5746only one rewrite at a time.
5747
5748@group
5749@smallexample
57501: 1 / cos(x) - sin(x)^2 / cos(x) 1: (1 - sin(x)^2) / cos(x)
5751 . .
5752
5753 r 1 M-1 a r trig RET M-1 a r trig RET
5754@end smallexample
5755@end group
5756
5757You can type @kbd{M-0 a r} if you want no limit at all on the number
5758of rewrites that occur.
5759
5760Rewrite rules can also be @dfn{conditional}. Simply follow the rule
5761with a @samp{::} symbol and the desired condition. For example,
5762
5763@group
5764@smallexample
57651: exp(2 pi i) + exp(3 pi i) + exp(4 pi i)
5766 .
5767
5768 ' exp(2 pi i) + exp(3 pi i) + exp(4 pi i) RET
5769
5770@end smallexample
5771@end group
5772@noindent
5773@group
5774@smallexample
57751: 1 + exp(3 pi i) + 1
5776 .
5777
5778 a r exp(k pi i) := 1 :: k % 2 = 0 RET
5779@end smallexample
5780@end group
5781
5782@noindent
5783(Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
5784which will be zero only when @samp{k} is an even integer.)
5785
5786An interesting point is that the variables @samp{pi} and @samp{i}
5787were matched literally rather than acting as meta-variables.
5788This is because they are special-constant variables. The special
5789constants @samp{e}, @samp{phi}, and so on also match literally.
5790A common error with rewrite
5791rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
5792to match any @samp{f} with five arguments but in fact matching
5793only when the fifth argument is literally @samp{e}!@refill
5794
5795@cindex Fibonacci numbers
5796@c @starindex
5797@tindex fib
5798Rewrite rules provide an interesting way to define your own functions.
5799Suppose we want to define @samp{fib(n)} to produce the @var{n}th
5800Fibonacci number. The first two Fibonacci numbers are each 1;
5801later numbers are formed by summing the two preceding numbers in
5802the sequence. This is easy to express in a set of three rules:
5803
5804@group
5805@smallexample
5806' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] RET s t fib
5807
58081: fib(7) 1: 13
5809 . .
5810
5811 ' fib(7) RET a r fib RET
5812@end smallexample
5813@end group
5814
5815One thing that is guaranteed about the order that rewrites are tried
5816is that, for any given subformula, earlier rules in the rule set will
5817be tried for that subformula before later ones. So even though the
5818first and third rules both match @samp{fib(1)}, we know the first will
5819be used preferentially.
5820
5821This rule set has one dangerous bug: Suppose we apply it to the
5822formula @samp{fib(x)}? (Don't actually try this.) The third rule
5823will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
5824Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
5825fib(x-4)}, and so on, expanding forever. What we really want is to apply
5826the third rule only when @samp{n} is an integer greater than two. Type
5827@w{@kbd{s e fib RET}}, then edit the third rule to:
5828
5829@smallexample
5830fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
5831@end smallexample
5832
5833@noindent
5834Now:
5835
5836@group
5837@smallexample
58381: fib(6) + fib(x) + fib(0) 1: 8 + fib(x) + fib(0)
5839 . .
5840
5841 ' fib(6)+fib(x)+fib(0) RET a r fib RET
5842@end smallexample
5843@end group
5844
5845@noindent
5846We've created a new function, @code{fib}, and a new command,
5847@w{@kbd{a r fib RET}}, which means ``evaluate all @code{fib} calls in
5848this formula.'' To make things easier still, we can tell Calc to
5849apply these rules automatically by storing them in the special
5850variable @code{EvalRules}.
5851
5852@group
5853@smallexample
58541: [fib(1) := ...] . 1: [8, 13]
5855 . .
5856
5857 s r fib RET s t EvalRules RET ' [fib(6), fib(7)] RET
5858@end smallexample
5859@end group
5860
5861It turns out that this rule set has the problem that it does far
5862more work than it needs to when @samp{n} is large. Consider the
5863first few steps of the computation of @samp{fib(6)}:
5864
5865@group
5866@smallexample
5867fib(6) =
5868fib(5) + fib(4) =
5869fib(4) + fib(3) + fib(3) + fib(2) =
5870fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
5871@end smallexample
5872@end group
5873
5874@noindent
5875Note that @samp{fib(3)} appears three times here. Unless Calc's
5876algebraic simplifier notices the multiple @samp{fib(3)}s and combines
5877them (and, as it happens, it doesn't), this rule set does lots of
5878needless recomputation. To cure the problem, type @code{s e EvalRules}
5879to edit the rules (or just @kbd{s E}, a shorthand command for editing
5880@code{EvalRules}) and add another condition:
5881
5882@smallexample
5883fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
5884@end smallexample
5885
5886@noindent
5887If a @samp{:: remember} condition appears anywhere in a rule, then if
5888that rule succeeds Calc will add another rule that describes that match
5889to the front of the rule set. (Remembering works in any rule set, but
5890for technical reasons it is most effective in @code{EvalRules}.) For
5891example, if the rule rewrites @samp{fib(7)} to something that evaluates
5892to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
5893
5894Type @kbd{' fib(8) RET} to compute the eighth Fibonacci number, then
5895type @kbd{s E} again to see what has happened to the rule set.
5896
5897With the @code{remember} feature, our rule set can now compute
5898@samp{fib(@var{n})} in just @var{n} steps. In the process it builds
5899up a table of all Fibonacci numbers up to @var{n}. After we have
5900computed the result for a particular @var{n}, we can get it back
5901(and the results for all smaller @var{n}) later in just one step.
5902
5903All Calc operations will run somewhat slower whenever @code{EvalRules}
5904contains any rules. You should type @kbd{s u EvalRules RET} now to
5905un-store the variable.
5906
5907(@bullet{}) @strong{Exercise 2.} Sometimes it is possible to reformulate
5908a problem to reduce the amount of recursion necessary to solve it.
5909Create a rule that, in about @var{n} simple steps and without recourse
5910to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
5911@samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
5912@var{n}th and @var{n+1}st Fibonacci numbers, respectively. This rule is
5913rather clunky to use, so add a couple more rules to make the ``user
5914interface'' the same as for our first version: enter @samp{fib(@var{n})},
5915get back a plain number. @xref{Rewrites Answer 2, 2}. (@bullet{})
5916
5917There are many more things that rewrites can do. For example, there
5918are @samp{&&&} and @samp{|||} pattern operators that create ``and''
5919and ``or'' combinations of rules. As one really simple example, we
5920could combine our first two Fibonacci rules thusly:
5921
5922@example
5923[fib(1 ||| 2) := 1, fib(n) := ... ]
5924@end example
5925
5926@noindent
5927That means ``@code{fib} of something matching either 1 or 2 rewrites
5928to 1.''
5929
5930You can also make meta-variables optional by enclosing them in @code{opt}.
5931For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
5932@samp{2 + x} or @samp{3 x} or @samp{x}. The pattern @samp{opt(a) + opt(b) x}
5933matches all of these forms, filling in a default of zero for @samp{a}
5934and one for @samp{b}.
5935
5936(@bullet{}) @strong{Exercise 3.} Your friend Joe had @samp{2 + 3 x}
5937on the stack and tried to use the rule
5938@samp{opt(a) + opt(b) x := f(a, b, x)}. What happened?
5939@xref{Rewrites Answer 3, 3}. (@bullet{})
5940
5941(@bullet{}) @strong{Exercise 4.} Starting with a positive integer @cite{a},
5942divide @cite{a} by two if it is even, otherwise compute @cite{3 a + 1}.
5943Now repeat this step over and over. A famous unproved conjecture
5944is that for any starting @cite{a}, the sequence always eventually
5945reaches 1. Given the formula @samp{seq(@var{a}, 0)}, write a set of
5946rules that convert this into @samp{seq(1, @var{n})} where @var{n}
5947is the number of steps it took the sequence to reach the value 1.
5948Now enhance the rules to accept @samp{seq(@var{a})} as a starting
5949configuration, and to stop with just the number @var{n} by itself.
5950Now make the result be a vector of values in the sequence, from @var{a}
5951to 1. (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
5952and @var{y}.) For example, rewriting @samp{seq(6)} should yield the
5953vector @cite{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
5954@xref{Rewrites Answer 4, 4}. (@bullet{})
5955
5956(@bullet{}) @strong{Exercise 5.} Define, using rewrite rules, a function
5957@samp{nterms(@var{x})} that returns the number of terms in the sum
5958@var{x}, or 1 if @var{x} is not a sum. (A @dfn{sum} for our purposes
5959is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
5960so that @cite{2 - 3 (x + y) + x y} is a sum of three terms.)
5961@xref{Rewrites Answer 5, 5}. (@bullet{})
5962
5963(@bullet{}) @strong{Exercise 6.} Calc considers the form @cite{0^0}
5964to be ``indeterminate,'' and leaves it unevaluated (assuming infinite
5965mode is not enabled). Some people prefer to define @cite{0^0 = 1},
5966so that the identity @cite{x^0 = 1} can safely be used for all @cite{x}.
5967Find a way to make Calc follow this convention. What happens if you
5968now type @kbd{m i} to turn on infinite mode?
5969@xref{Rewrites Answer 6, 6}. (@bullet{})
5970
5971(@bullet{}) @strong{Exercise 7.} A Taylor series for a function is an
5972infinite series that exactly equals the value of that function at
5973values of @cite{x} near zero.
5974
5975@ifinfo
5976@example
5977cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
5978@end example
5979@end ifinfo
5980@tex
5981\turnoffactive \let\rm\goodrm
5982\beforedisplay
5983$$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
5984\afterdisplay
5985@end tex
5986
5987The @kbd{a t} command produces a @dfn{truncated Taylor series} which
5988is obtained by dropping all the terms higher than, say, @cite{x^2}.
5989Calc represents the truncated Taylor series as a polynomial in @cite{x}.
5990Mathematicians often write a truncated series using a ``big-O'' notation
5991that records what was the lowest term that was truncated.
5992
5993@ifinfo
5994@example
5995cos(x) = 1 - x^2 / 2! + O(x^3)
5996@end example
5997@end ifinfo
5998@tex
5999\turnoffactive \let\rm\goodrm
6000\beforedisplay
6001$$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
6002\afterdisplay
6003@end tex
6004
6005@noindent
6006The meaning of @cite{O(x^3)} is ``a quantity which is negligibly small
6007if @cite{x^3} is considered negligibly small as @cite{x} goes to zero.''
6008
6009The exercise is to create rewrite rules that simplify sums and products of
6010power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
6011For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
6012on the stack, we want to be able to type @kbd{*} and get the result
6013@samp{x - 2:3 x^3 + O(x^4)}. Don't worry if the terms of the sum are
6014rearranged or if @kbd{a s} needs to be typed after rewriting. (This one
6015is rather tricky; the solution at the end of this chapter uses 6 rewrite
6016rules. Hint: The @samp{constant(x)} condition tests whether @samp{x} is
6017a number.) @xref{Rewrites Answer 7, 7}. (@bullet{})
6018
6019@c [fix-ref Rewrite Rules]
6020@xref{Rewrite Rules}, for the whole story on rewrite rules.
6021
6022@node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
6023@section Programming Tutorial
6024
6025@noindent
6026The Calculator is written entirely in Emacs Lisp, a highly extensible
6027language. If you know Lisp, you can program the Calculator to do
6028anything you like. Rewrite rules also work as a powerful programming
6029system. But Lisp and rewrite rules take a while to master, and often
6030all you want to do is define a new function or repeat a command a few
6031times. Calc has features that allow you to do these things easily.
6032
6033(Note that the programming commands relating to user-defined keys
6034are not yet supported under Lucid Emacs 19.)
6035
6036One very limited form of programming is defining your own functions.
6037Calc's @kbd{Z F} command allows you to define a function name and
6038key sequence to correspond to any formula. Programming commands use
6039the shift-@kbd{Z} prefix; the user commands they create use the lower
6040case @kbd{z} prefix.
6041
6042@group
6043@smallexample
60441: 1 + x + x^2 / 2 + x^3 / 6 1: 1 + x + x^2 / 2 + x^3 / 6
6045 . .
6046
6047 ' 1 + x + x^2/2! + x^3/3! RET Z F e myexp RET RET RET y
6048@end smallexample
6049@end group
6050
6051This polynomial is a Taylor series approximation to @samp{exp(x)}.
6052The @kbd{Z F} command asks a number of questions. The above answers
6053say that the key sequence for our function should be @kbd{z e}; the
6054@kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
6055function in algebraic formulas should also be @code{myexp}; the
6056default argument list @samp{(x)} is acceptable; and finally @kbd{y}
6057answers the question ``leave it in symbolic form for non-constant
6058arguments?''
6059
6060@group
6061@smallexample
60621: 1.3495 2: 1.3495 3: 1.3495
6063 . 1: 1.34986 2: 1.34986
6064 . 1: myexp(a + 1)
6065 .
6066
6067 .3 z e .3 E ' a+1 RET z e
6068@end smallexample
6069@end group
6070
6071@noindent
6072First we call our new @code{exp} approximation with 0.3 as an
6073argument, and compare it with the true @code{exp} function. Then
6074we note that, as requested, if we try to give @kbd{z e} an
6075argument that isn't a plain number, it leaves the @code{myexp}
6076function call in symbolic form. If we had answered @kbd{n} to the
6077final question, @samp{myexp(a + 1)} would have evaluated by plugging
6078in @samp{a + 1} for @samp{x} in the defining formula.
6079
6080@cindex Sine integral Si(x)
6081@c @starindex
6082@tindex Si
6083(@bullet{}) @strong{Exercise 1.} The ``sine integral'' function
6084@c{${\rm Si}(x)$}
6085@cite{Si(x)} is defined as the integral of @samp{sin(t)/t} for
6086@cite{t = 0} to @cite{x} in radians. (It was invented because this
6087integral has no solution in terms of basic functions; if you give it
6088to Calc's @kbd{a i} command, it will ponder it for a long time and then
6089give up.) We can use the numerical integration command, however,
6090which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
6091with any integrand @samp{f(t)}. Define a @kbd{z s} command and
6092@code{Si} function that implement this. You will need to edit the
6093default argument list a bit. As a test, @samp{Si(1)} should return
60940.946083. (Hint: @code{ninteg} will run a lot faster if you reduce
6095the precision to, say, six digits beforehand.)
6096@xref{Programming Answer 1, 1}. (@bullet{})
6097
6098The simplest way to do real ``programming'' of Emacs is to define a
6099@dfn{keyboard macro}. A keyboard macro is simply a sequence of
6100keystrokes which Emacs has stored away and can play back on demand.
6101For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
6102you may wish to program a keyboard macro to type this for you.
6103
6104@group
6105@smallexample
61061: y = sqrt(x) 1: x = y^2
6107 . .
6108
6109 ' y=sqrt(x) RET C-x ( H a S x RET C-x )
6110
61111: y = cos(x) 1: x = s1 arccos(y) + 2 pi n1
6112 . .
6113
6114 ' y=cos(x) RET X
6115@end smallexample
6116@end group
6117
6118@noindent
6119When you type @kbd{C-x (}, Emacs begins recording. But it is also
6120still ready to execute your keystrokes, so you're really ``training''
6121Emacs by walking it through the procedure once. When you type
6122@w{@kbd{C-x )}}, the macro is recorded. You can now type @kbd{X} to
6123re-execute the same keystrokes.
6124
6125You can give a name to your macro by typing @kbd{Z K}.
6126
6127@group
6128@smallexample
61291: . 1: y = x^4 1: x = s2 sqrt(s1 sqrt(y))
6130 . .
6131
6132 Z K x RET ' y=x^4 RET z x
6133@end smallexample
6134@end group
6135
6136@noindent
6137Notice that we use shift-@kbd{Z} to define the command, and lower-case
6138@kbd{z} to call it up.
6139
6140Keyboard macros can call other macros.
6141
6142@group
6143@smallexample
61441: abs(x) 1: x = s1 y 1: 2 / x 1: x = 2 / y
6145 . . . .
6146
6147 ' abs(x) RET C-x ( ' y RET a = z x C-x ) ' 2/x RET X
6148@end smallexample
6149@end group
6150
6151(@bullet{}) @strong{Exercise 2.} Define a keyboard macro to negate
6152the item in level 3 of the stack, without disturbing the rest of
6153the stack. @xref{Programming Answer 2, 2}. (@bullet{})
6154
6155(@bullet{}) @strong{Exercise 3.} Define keyboard macros to compute
6156the following functions:
6157
6158@enumerate
6159@item
6160Compute @c{$\displaystyle{\sin x \over x}$}
6161@cite{sin(x) / x}, where @cite{x} is the number on the
6162top of the stack.
6163
6164@item
6165Compute the base-@cite{b} logarithm, just like the @kbd{B} key except
6166the arguments are taken in the opposite order.
6167
6168@item
6169Produce a vector of integers from 1 to the integer on the top of
6170the stack.
6171@end enumerate
6172@noindent
6173@xref{Programming Answer 3, 3}. (@bullet{})
6174
6175(@bullet{}) @strong{Exercise 4.} Define a keyboard macro to compute
6176the average (mean) value of a list of numbers.
6177@xref{Programming Answer 4, 4}. (@bullet{})
6178
6179In many programs, some of the steps must execute several times.
6180Calc has @dfn{looping} commands that allow this. Loops are useful
6181inside keyboard macros, but actually work at any time.
6182
6183@group
6184@smallexample
61851: x^6 2: x^6 1: 360 x^2
6186 . 1: 4 .
6187 .
6188
6189 ' x^6 RET 4 Z < a d x RET Z >
6190@end smallexample
6191@end group
6192
6193@noindent
6194Here we have computed the fourth derivative of @cite{x^6} by
6195enclosing a derivative command in a ``repeat loop'' structure.
6196This structure pops a repeat count from the stack, then
6197executes the body of the loop that many times.
6198
6199If you make a mistake while entering the body of the loop,
6200type @w{@kbd{Z C-g}} to cancel the loop command.
6201
6202@cindex Fibonacci numbers
6203Here's another example:
6204
6205@group
6206@smallexample
62073: 1 2: 10946
62082: 1 1: 17711
62091: 20 .
6210 .
6211
62121 RET RET 20 Z < TAB C-j + Z >
6213@end smallexample
6214@end group
6215
6216@noindent
6217The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
6218numbers, respectively. (To see what's going on, try a few repetitions
6219of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
6220key if you have one, makes a copy of the number in level 2.)
6221
6222@cindex Golden ratio
6223@cindex Phi, golden ratio
6224A fascinating property of the Fibonacci numbers is that the @cite{n}th
6225Fibonacci number can be found directly by computing @c{$\phi^n / \sqrt{5}$}
6226@cite{phi^n / sqrt(5)}
6227and then rounding to the nearest integer, where @c{$\phi$ (``phi'')}
6228@cite{phi}, the
6229``golden ratio,'' is @c{$(1 + \sqrt{5}) / 2$}
6230@cite{(1 + sqrt(5)) / 2}. (For convenience, this constant is available
6231from the @code{phi} variable, or the @kbd{I H P} command.)
6232
6233@group
6234@smallexample
62351: 1.61803 1: 24476.0000409 1: 10945.9999817 1: 10946
6236 . . . .
6237
6238 I H P 21 ^ 5 Q / R
6239@end smallexample
6240@end group
6241
6242@cindex Continued fractions
6243(@bullet{}) @strong{Exercise 5.} The @dfn{continued fraction}
6244representation of @c{$\phi$}
6245@cite{phi} is @c{$1 + 1/(1 + 1/(1 + 1/( \ldots )))$}
6246@cite{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
6247We can compute an approximate value by carrying this however far
6248and then replacing the innermost @c{$1/( \ldots )$}
6249@cite{1/( ...@: )} by 1. Approximate
6250@c{$\phi$}
6251@cite{phi} using a twenty-term continued fraction.
6252@xref{Programming Answer 5, 5}. (@bullet{})
6253
6254(@bullet{}) @strong{Exercise 6.} Linear recurrences like the one for
6255Fibonacci numbers can be expressed in terms of matrices. Given a
6256vector @w{@cite{[a, b]}} determine a matrix which, when multiplied by this
6257vector, produces the vector @cite{[b, c]}, where @cite{a}, @cite{b} and
6258@cite{c} are three successive Fibonacci numbers. Now write a program
6259that, given an integer @cite{n}, computes the @cite{n}th Fibonacci number
6260using matrix arithmetic. @xref{Programming Answer 6, 6}. (@bullet{})
6261
6262@cindex Harmonic numbers
6263A more sophisticated kind of loop is the @dfn{for} loop. Suppose
6264we wish to compute the 20th ``harmonic'' number, which is equal to
6265the sum of the reciprocals of the integers from 1 to 20.
6266
6267@group
6268@smallexample
62693: 0 1: 3.597739
62702: 1 .
62711: 20
6272 .
6273
62740 RET 1 RET 20 Z ( & + 1 Z )
6275@end smallexample
6276@end group
6277
6278@noindent
6279The ``for'' loop pops two numbers, the lower and upper limits, then
6280repeats the body of the loop as an internal counter increases from
6281the lower limit to the upper one. Just before executing the loop
6282body, it pushes the current loop counter. When the loop body
6283finishes, it pops the ``step,'' i.e., the amount by which to
6284increment the loop counter. As you can see, our loop always
6285uses a step of one.
6286
6287This harmonic number function uses the stack to hold the running
6288total as well as for the various loop housekeeping functions. If
6289you find this disorienting, you can sum in a variable instead:
6290
6291@group
6292@smallexample
62931: 0 2: 1 . 1: 3.597739
6294 . 1: 20 .
6295 .
6296
6297 0 t 7 1 RET 20 Z ( & s + 7 1 Z ) r 7
6298@end smallexample
6299@end group
6300
6301@noindent
6302The @kbd{s +} command adds the top-of-stack into the value in a
6303variable (and removes that value from the stack).
6304
6305It's worth noting that many jobs that call for a ``for'' loop can
6306also be done more easily by Calc's high-level operations. Two
6307other ways to compute harmonic numbers are to use vector mapping
6308and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
6309or to use the summation command @kbd{a +}. Both of these are
6310probably easier than using loops. However, there are some
6311situations where loops really are the way to go:
6312
6313(@bullet{}) @strong{Exercise 7.} Use a ``for'' loop to find the first
6314harmonic number which is greater than 4.0.
6315@xref{Programming Answer 7, 7}. (@bullet{})
6316
6317Of course, if we're going to be using variables in our programs,
6318we have to worry about the programs clobbering values that the
6319caller was keeping in those same variables. This is easy to
6320fix, though:
6321
6322@group
6323@smallexample
6324 . 1: 0.6667 1: 0.6667 3: 0.6667
6325 . . 2: 3.597739
6326 1: 0.6667
6327 .
6328
6329 Z ` p 4 RET 2 RET 3 / s 7 s s a RET Z ' r 7 s r a RET
6330@end smallexample
6331@end group
6332
6333@noindent
6334When we type @kbd{Z `} (that's a back-quote character), Calc saves
6335its mode settings and the contents of the ten ``quick variables''
6336for later reference. When we type @kbd{Z '} (that's an apostrophe
6337now), Calc restores those saved values. Thus the @kbd{p 4} and
6338@kbd{s 7} commands have no effect outside this sequence. Wrapping
6339this around the body of a keyboard macro ensures that it doesn't
6340interfere with what the user of the macro was doing. Notice that
6341the contents of the stack, and the values of named variables,
6342survive past the @kbd{Z '} command.
6343
6344@cindex Bernoulli numbers, approximate
6345The @dfn{Bernoulli numbers} are a sequence with the interesting
6346property that all of the odd Bernoulli numbers are zero, and the
6347even ones, while difficult to compute, can be roughly approximated
6348by the formula @c{$\displaystyle{2 n! \over (2 \pi)^n}$}
6349@cite{2 n!@: / (2 pi)^n}. Let's write a keyboard
6350macro to compute (approximate) Bernoulli numbers. (Calc has a
6351command, @kbd{k b}, to compute exact Bernoulli numbers, but
6352this command is very slow for large @cite{n} since the higher
6353Bernoulli numbers are very large fractions.)
6354
6355@group
6356@smallexample
63571: 10 1: 0.0756823
6358 . .
6359
6360 10 C-x ( RET 2 % Z [ DEL 0 Z : ' 2 $! / (2 pi)^$ RET = Z ] C-x )
6361@end smallexample
6362@end group
6363
6364@noindent
6365You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
6366@kbd{Z ]} as ``end-if.'' There is no need for an explicit ``if''
6367command. For the purposes of @w{@kbd{Z [}}, the condition is ``true''
6368if the value it pops from the stack is a nonzero number, or ``false''
6369if it pops zero or something that is not a number (like a formula).
6370Here we take our integer argument modulo 2; this will be nonzero
6371if we're asking for an odd Bernoulli number.
6372
6373The actual tenth Bernoulli number is @cite{5/66}.
6374
6375@group
6376@smallexample
63773: 0.0756823 1: 0 1: 0.25305 1: 0 1: 1.16659
63782: 5:66 . . . .
63791: 0.0757575
6380 .
6381
638210 k b RET c f M-0 DEL 11 X DEL 12 X DEL 13 X DEL 14 X
6383@end smallexample
6384@end group
6385
6386Just to exercise loops a bit more, let's compute a table of even
6387Bernoulli numbers.
6388
6389@group
6390@smallexample
63913: [] 1: [0.10132, 0.03079, 0.02340, 0.033197, ...]
63922: 2 .
63931: 30
6394 .
6395
6396 [ ] 2 RET 30 Z ( X | 2 Z )
6397@end smallexample
6398@end group
6399
6400@noindent
6401The vertical-bar @kbd{|} is the vector-concatenation command. When
6402we execute it, the list we are building will be in stack level 2
6403(initially this is an empty list), and the next Bernoulli number
6404will be in level 1. The effect is to append the Bernoulli number
6405onto the end of the list. (To create a table of exact fractional
6406Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
6407sequence of keystrokes.)
6408
6409With loops and conditionals, you can program essentially anything
6410in Calc. One other command that makes looping easier is @kbd{Z /},
6411which takes a condition from the stack and breaks out of the enclosing
6412loop if the condition is true (non-zero). You can use this to make
6413``while'' and ``until'' style loops.
6414
6415If you make a mistake when entering a keyboard macro, you can edit
6416it using @kbd{Z E}. First, you must attach it to a key with @kbd{Z K}.
6417One technique is to enter a throwaway dummy definition for the macro,
6418then enter the real one in the edit command.
6419
6420@group
6421@smallexample
64221: 3 1: 3 Keyboard Macro Editor.
6423 . . Original keys: 1 RET 2 +
6424
6425 type "1\r"
6426 type "2"
6427 calc-plus
6428
6429C-x ( 1 RET 2 + C-x ) Z K h RET Z E h
6430@end smallexample
6431@end group
6432
6433@noindent
6434This shows the screen display assuming you have the @file{macedit}
6435keyboard macro editing package installed, which is usually the case
6436since a copy of @file{macedit} comes bundled with Calc.
6437
6438A keyboard macro is stored as a pure keystroke sequence. The
6439@file{macedit} package (invoked by @kbd{Z E}) scans along the
6440macro and tries to decode it back into human-readable steps.
6441If a key or keys are simply shorthand for some command with a
6442@kbd{M-x} name, that name is shown. Anything that doesn't correspond
6443to a @kbd{M-x} command is written as a @samp{type} command.
6444
6445Let's edit in a new definition, for computing harmonic numbers.
6446First, erase the three lines of the old definition. Then, type
6447in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
6448to copy it from this page of the Info file; you can skip typing
6449the comments that begin with @samp{#}).
6450
6451@smallexample
6452calc-kbd-push # Save local values (Z `)
6453type "0" # Push a zero
6454calc-store-into # Store it in variable 1
6455type "1"
6456type "1" # Initial value for loop
6457calc-roll-down # This is the TAB key; swap initial & final
6458calc-kbd-for # Begin "for" loop...
6459calc-inv # Take reciprocal
6460calc-store-plus # Add to accumulator
6461type "1"
6462type "1" # Loop step is 1
6463calc-kbd-end-for # End "for" loop
6464calc-recall # Now recall final accumulated value
6465type "1"
6466calc-kbd-pop # Restore values (Z ')
6467@end smallexample
6468
6469@noindent
6470Press @kbd{M-# M-#} to finish editing and return to the Calculator.
6471
6472@group
6473@smallexample
64741: 20 1: 3.597739
6475 . .
6476
6477 20 z h
6478@end smallexample
6479@end group
6480
6481If you don't know how to write a particular command in @file{macedit}
6482format, you can always write it as keystrokes in a @code{type} command.
6483There is also a @code{keys} command which interprets the rest of the
6484line as standard Emacs keystroke names. In fact, @file{macedit} defines
6485a handy @code{read-kbd-macro} command which reads the current region
6486of the current buffer as a sequence of keystroke names, and defines that
6487sequence on the @kbd{X} (and @kbd{C-x e}) key. Because this is so
6488useful, Calc puts this command on the @kbd{M-# m} key. Try reading in
6489this macro in the following form: Press @kbd{C-@@} (or @kbd{C-SPC}) at
6490one end of the text below, then type @kbd{M-# m} at the other.
6491
6492@group
6493@example
6494Z ` 0 t 1
6495 1 TAB
6496 Z ( & s + 1 1 Z )
6497 r 1
6498Z '
6499@end example
6500@end group
6501
6502(@bullet{}) @strong{Exercise 8.} A general algorithm for solving
6503equations numerically is @dfn{Newton's Method}. Given the equation
6504@cite{f(x) = 0} for any function @cite{f}, and an initial guess
6505@cite{x_0} which is reasonably close to the desired solution, apply
6506this formula over and over:
6507
6508@ifinfo
6509@example
6510new_x = x - f(x)/f'(x)
6511@end example
6512@end ifinfo
6513@tex
6514\beforedisplay
6515$$ x_{\goodrm new} = x - {f(x) \over f'(x)} $$
6516\afterdisplay
6517@end tex
6518
6519@noindent
6520where @cite{f'(x)} is the derivative of @cite{f}. The @cite{x}
6521values will quickly converge to a solution, i.e., eventually
6522@c{$x_{\rm new}$}
6523@cite{new_x} and @cite{x} will be equal to within the limits
6524of the current precision. Write a program which takes a formula
6525involving the variable @cite{x}, and an initial guess @cite{x_0},
6526on the stack, and produces a value of @cite{x} for which the formula
6527is zero. Use it to find a solution of @c{$\sin(\cos x) = 0.5$}
6528@cite{sin(cos(x)) = 0.5}
6529near @cite{x = 4.5}. (Use angles measured in radians.) Note that
6530the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
6531method when it is able. @xref{Programming Answer 8, 8}. (@bullet{})
6532
6533@cindex Digamma function
6534@cindex Gamma constant, Euler's
6535@cindex Euler's gamma constant
6536(@bullet{}) @strong{Exercise 9.} The @dfn{digamma} function @c{$\psi(z)$ (``psi'')}
6537@cite{psi(z)}
6538is defined as the derivative of @c{$\ln \Gamma(z)$}
6539@cite{ln(gamma(z))}. For large
6540values of @cite{z}, it can be approximated by the infinite sum
6541
6542@ifinfo
6543@example
6544psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
6545@end example
6546@end ifinfo
6547@tex
6548\let\rm\goodrm
6549\beforedisplay
6550$$ \psi(z) \approx \ln z - {1\over2z} -
6551 \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
6552$$
6553\afterdisplay
6554@end tex
6555
6556@noindent
6557where @c{$\sum$}
6558@cite{sum} represents the sum over @cite{n} from 1 to infinity
6559(or to some limit high enough to give the desired accuracy), and
6560the @code{bern} function produces (exact) Bernoulli numbers.
6561While this sum is not guaranteed to converge, in practice it is safe.
6562An interesting mathematical constant is Euler's gamma, which is equal
6563to about 0.5772. One way to compute it is by the formula,
6564@c{$\gamma = -\psi(1)$}
6565@cite{gamma = -psi(1)}. Unfortunately, 1 isn't a large enough argument
6566for the above formula to work (5 is a much safer value for @cite{z}).
6567Fortunately, we can compute @c{$\psi(1)$}
6568@cite{psi(1)} from @c{$\psi(5)$}
6569@cite{psi(5)} using
6570the recurrence @c{$\psi(z+1) = \psi(z) + {1 \over z}$}
6571@cite{psi(z+1) = psi(z) + 1/z}. Your task: Develop
6572a program to compute @c{$\psi(z)$}
6573@cite{psi(z)}; it should ``pump up'' @cite{z}
6574if necessary to be greater than 5, then use the above summation
6575formula. Use looping commands to compute the sum. Use your function
6576to compute @c{$\gamma$}
6577@cite{gamma} to twelve decimal places. (Calc has a built-in command
6578for Euler's constant, @kbd{I P}, which you can use to check your answer.)
6579@xref{Programming Answer 9, 9}. (@bullet{})
6580
6581@cindex Polynomial, list of coefficients
6582(@bullet{}) @strong{Exercise 10.} Given a polynomial in @cite{x} and
6583a number @cite{m} on the stack, where the polynomial is of degree
6584@cite{m} or less (i.e., does not have any terms higher than @cite{x^m}),
6585write a program to convert the polynomial into a list-of-coefficients
6586notation. For example, @cite{5 x^4 + (x + 1)^2} with @cite{m = 6}
6587should produce the list @cite{[1, 2, 1, 0, 5, 0, 0]}. Also develop
6588a way to convert from this form back to the standard algebraic form.
6589@xref{Programming Answer 10, 10}. (@bullet{})
6590
6591@cindex Recursion
6592(@bullet{}) @strong{Exercise 11.} The @dfn{Stirling numbers of the
6593first kind} are defined by the recurrences,
6594
6595@ifinfo
6596@example
6597s(n,n) = 1 for n >= 0,
6598s(n,0) = 0 for n > 0,
6599s(n+1,m) = s(n,m-1) - n s(n,m) for n >= m >= 1.
6600@end example
6601@end ifinfo
6602@tex
6603\turnoffactive
6604\beforedisplay
6605$$ \eqalign{ s(n,n) &= 1 \qquad \hbox{for } n \ge 0, \cr
6606 s(n,0) &= 0 \qquad \hbox{for } n > 0, \cr
6607 s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
6608 \hbox{for } n \ge m \ge 1.}
6609$$
6610\afterdisplay
6611\vskip5pt
6612(These numbers are also sometimes written $\displaystyle{n \brack m}$.)
6613@end tex
6614
6615This can be implemented using a @dfn{recursive} program in Calc; the
6616program must invoke itself in order to calculate the two righthand
6617terms in the general formula. Since it always invokes itself with
6618``simpler'' arguments, it's easy to see that it must eventually finish
6619the computation. Recursion is a little difficult with Emacs keyboard
6620macros since the macro is executed before its definition is complete.
6621So here's the recommended strategy: Create a ``dummy macro'' and assign
6622it to a key with, e.g., @kbd{Z K s}. Now enter the true definition,
6623using the @kbd{z s} command to call itself recursively, then assign it
6624to the same key with @kbd{Z K s}. Now the @kbd{z s} command will run
6625the complete recursive program. (Another way is to use @w{@kbd{Z E}}
6626or @kbd{M-# m} (@code{read-kbd-macro}) to read the whole macro at once,
6627thus avoiding the ``training'' phase.) The task: Write a program
6628that computes Stirling numbers of the first kind, given @cite{n} and
6629@cite{m} on the stack. Test it with @emph{small} inputs like
6630@cite{s(4,2)}. (There is a built-in command for Stirling numbers,
6631@kbd{k s}, which you can use to check your answers.)
6632@xref{Programming Answer 11, 11}. (@bullet{})
6633
6634The programming commands we've seen in this part of the tutorial
6635are low-level, general-purpose operations. Often you will find
6636that a higher-level function, such as vector mapping or rewrite
6637rules, will do the job much more easily than a detailed, step-by-step
6638program can:
6639
6640(@bullet{}) @strong{Exercise 12.} Write another program for
6641computing Stirling numbers of the first kind, this time using
6642rewrite rules. Once again, @cite{n} and @cite{m} should be taken
6643from the stack. @xref{Programming Answer 12, 12}. (@bullet{})
6644
6645@example
6646
6647@end example
6648This ends the tutorial section of the Calc manual. Now you know enough
6649about Calc to use it effectively for many kinds of calculations. But
6650Calc has many features that were not even touched upon in this tutorial.
6651@c [not-split]
6652The rest of this manual tells the whole story.
6653@c [when-split]
6654@c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
6655
6656@page
6657@node Answers to Exercises, , Programming Tutorial, Tutorial
6658@section Answers to Exercises
6659
6660@noindent
6661This section includes answers to all the exercises in the Calc tutorial.
6662
6663@menu
6664* RPN Answer 1:: 1 RET 2 RET 3 RET 4 + * -
6665* RPN Answer 2:: 2*4 + 7*9.5 + 5/4
6666* RPN Answer 3:: Operating on levels 2 and 3
6667* RPN Answer 4:: Joe's complex problems
6668* Algebraic Answer 1:: Simulating Q command
6669* Algebraic Answer 2:: Joe's algebraic woes
6670* Algebraic Answer 3:: 1 / 0
6671* Modes Answer 1:: 3#0.1 = 3#0.0222222?
6672* Modes Answer 2:: 16#f.e8fe15
6673* Modes Answer 3:: Joe's rounding bug
6674* Modes Answer 4:: Why floating point?
6675* Arithmetic Answer 1:: Why the \ command?
6676* Arithmetic Answer 2:: Tripping up the B command
6677* Vector Answer 1:: Normalizing a vector
6678* Vector Answer 2:: Average position
6679* Matrix Answer 1:: Row and column sums
6680* Matrix Answer 2:: Symbolic system of equations
6681* Matrix Answer 3:: Over-determined system
6682* List Answer 1:: Powers of two
6683* List Answer 2:: Least-squares fit with matrices
6684* List Answer 3:: Geometric mean
6685* List Answer 4:: Divisor function
6686* List Answer 5:: Duplicate factors
6687* List Answer 6:: Triangular list
6688* List Answer 7:: Another triangular list
6689* List Answer 8:: Maximum of Bessel function
6690* List Answer 9:: Integers the hard way
6691* List Answer 10:: All elements equal
6692* List Answer 11:: Estimating pi with darts
6693* List Answer 12:: Estimating pi with matchsticks
6694* List Answer 13:: Hash codes
6695* List Answer 14:: Random walk
6696* Types Answer 1:: Square root of pi times rational
6697* Types Answer 2:: Infinities
6698* Types Answer 3:: What can "nan" be?
6699* Types Answer 4:: Abbey Road
6700* Types Answer 5:: Friday the 13th
6701* Types Answer 6:: Leap years
6702* Types Answer 7:: Erroneous donut
6703* Types Answer 8:: Dividing intervals
6704* Types Answer 9:: Squaring intervals
6705* Types Answer 10:: Fermat's primality test
6706* Types Answer 11:: pi * 10^7 seconds
6707* Types Answer 12:: Abbey Road on CD
6708* Types Answer 13:: Not quite pi * 10^7 seconds
6709* Types Answer 14:: Supercomputers and c
6710* Types Answer 15:: Sam the Slug
6711* Algebra Answer 1:: Squares and square roots
6712* Algebra Answer 2:: Building polynomial from roots
6713* Algebra Answer 3:: Integral of x sin(pi x)
6714* Algebra Answer 4:: Simpson's rule
6715* Rewrites Answer 1:: Multiplying by conjugate
6716* Rewrites Answer 2:: Alternative fib rule
6717* Rewrites Answer 3:: Rewriting opt(a) + opt(b) x
6718* Rewrites Answer 4:: Sequence of integers
6719* Rewrites Answer 5:: Number of terms in sum
6720* Rewrites Answer 6:: Defining 0^0 = 1
6721* Rewrites Answer 7:: Truncated Taylor series
6722* Programming Answer 1:: Fresnel's C(x)
6723* Programming Answer 2:: Negate third stack element
6724* Programming Answer 3:: Compute sin(x) / x, etc.
6725* Programming Answer 4:: Average value of a list
6726* Programming Answer 5:: Continued fraction phi
6727* Programming Answer 6:: Matrix Fibonacci numbers
6728* Programming Answer 7:: Harmonic number greater than 4
6729* Programming Answer 8:: Newton's method
6730* Programming Answer 9:: Digamma function
6731* Programming Answer 10:: Unpacking a polynomial
6732* Programming Answer 11:: Recursive Stirling numbers
6733* Programming Answer 12:: Stirling numbers with rewrites
6734@end menu
6735
6736@c The following kludgery prevents the individual answers from
6737@c being entered on the table of contents.
6738@tex
6739\global\let\oldwrite=\write
6740\gdef\skipwrite#1#2{\let\write=\oldwrite}
6741\global\let\oldchapternofonts=\chapternofonts
6742\gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
6743@end tex
6744
6745@node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
6746@subsection RPN Tutorial Exercise 1
6747
6748@noindent
6749@kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
6750
6751The result is @c{$1 - (2 \times (3 + 4)) = -13$}
6752@cite{1 - (2 * (3 + 4)) = -13}.
6753
6754@node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
6755@subsection RPN Tutorial Exercise 2
6756
6757@noindent
6758@c{$2\times4 + 7\times9.5 + {5\over4} = 75.75$}
6759@cite{2*4 + 7*9.5 + 5/4 = 75.75}
6760
6761After computing the intermediate term @c{$2\times4 = 8$}
6762@cite{2*4 = 8}, you can leave
6763that result on the stack while you compute the second term. With
6764both of these results waiting on the stack you can then compute the
6765final term, then press @kbd{+ +} to add everything up.
6766
6767@group
6768@smallexample
67692: 2 1: 8 3: 8 2: 8
67701: 4 . 2: 7 1: 66.5
6771 . 1: 9.5 .
6772 .
6773
6774 2 RET 4 * 7 RET 9.5 *
6775
6776@end smallexample
6777@end group
6778@noindent
6779@group
6780@smallexample
67814: 8 3: 8 2: 8 1: 75.75
67823: 66.5 2: 66.5 1: 67.75 .
67832: 5 1: 1.25 .
67841: 4 .
6785 .
6786
6787 5 RET 4 / + +
6788@end smallexample
6789@end group
6790
6791Alternatively, you could add the first two terms before going on
6792with the third term.
6793
6794@group
6795@smallexample
67962: 8 1: 74.5 3: 74.5 2: 74.5 1: 75.75
67971: 66.5 . 2: 5 1: 1.25 .
6798 . 1: 4 .
6799 .
6800
6801 ... + 5 RET 4 / +
6802@end smallexample
6803@end group
6804
6805On an old-style RPN calculator this second method would have the
6806advantage of using only three stack levels. But since Calc's stack
6807can grow arbitrarily large this isn't really an issue. Which method
6808you choose is purely a matter of taste.
6809
6810@node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
6811@subsection RPN Tutorial Exercise 3
6812
6813@noindent
6814The @key{TAB} key provides a way to operate on the number in level 2.
6815
6816@group
6817@smallexample
68183: 10 3: 10 4: 10 3: 10 3: 10
68192: 20 2: 30 3: 30 2: 30 2: 21
68201: 30 1: 20 2: 20 1: 21 1: 30
6821 . . 1: 1 . .
6822 .
6823
6824 TAB 1 + TAB
6825@end smallexample
6826@end group
6827
6828Similarly, @key{M-TAB} gives you access to the number in level 3.
6829
6830@group
6831@smallexample
68323: 10 3: 21 3: 21 3: 30 3: 11
68332: 21 2: 30 2: 30 2: 11 2: 21
68341: 30 1: 10 1: 11 1: 21 1: 30
6835 . . . . .
6836
6837 M-TAB 1 + M-TAB M-TAB
6838@end smallexample
6839@end group
6840
6841@node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
6842@subsection RPN Tutorial Exercise 4
6843
6844@noindent
6845Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
6846but using both the comma and the space at once yields:
6847
6848@group
6849@smallexample
68501: ( ... 2: ( ... 1: (2, ... 2: (2, ... 2: (2, ...
6851 . 1: 2 . 1: (2, ... 1: (2, 3)
6852 . . .
6853
6854 ( 2 , SPC 3 )
6855@end smallexample
6856@end group
6857
6858Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
6859extra incomplete object to the top of the stack and delete it.
6860But a feature of Calc is that @key{DEL} on an incomplete object
6861deletes just one component out of that object, so he had to press
6862@key{DEL} twice to finish the job.
6863
6864@group
6865@smallexample
68662: (2, ... 2: (2, 3) 2: (2, 3) 1: (2, 3)
68671: (2, 3) 1: (2, ... 1: ( ... .
6868 . . .
6869
6870 TAB DEL DEL
6871@end smallexample
6872@end group
6873
6874(As it turns out, deleting the second-to-top stack entry happens often
6875enough that Calc provides a special key, @kbd{M-DEL}, to do just that.
6876@kbd{M-DEL} is just like @kbd{TAB DEL}, except that it doesn't exhibit
6877the ``feature'' that tripped poor Joe.)
6878
6879@node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
6880@subsection Algebraic Entry Tutorial Exercise 1
6881
6882@noindent
6883Type @kbd{' sqrt($) @key{RET}}.
6884
6885If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
6886Or, RPN style, @kbd{0.5 ^}.
6887
6888(Actually, @samp{$^1:2}, using the fraction one-half as the power, is
6889a closer equivalent, since @samp{9^0.5} yields @cite{3.0} whereas
6890@samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @cite{3}.)
6891
6892@node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
6893@subsection Algebraic Entry Tutorial Exercise 2
6894
6895@noindent
6896In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
6897name with @samp{1+y} as its argument. Assigning a value to a variable
6898has no relation to a function by the same name. Joe needed to use an
6899explicit @samp{*} symbol here: @samp{2 x*(1+y)}.
6900
6901@node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
6902@subsection Algebraic Entry Tutorial Exercise 3
6903
6904@noindent
6905The result from @kbd{1 @key{RET} 0 /} will be the formula @cite{1 / 0}.
6906The ``function'' @samp{/} cannot be evaluated when its second argument
6907is zero, so it is left in symbolic form. When you now type @kbd{0 *},
6908the result will be zero because Calc uses the general rule that ``zero
6909times anything is zero.''
6910
6911@c [fix-ref Infinities]
6912The @kbd{m i} command enables an @dfn{infinite mode} in which @cite{1 / 0}
6913results in a special symbol that represents ``infinity.'' If you
6914multiply infinity by zero, Calc uses another special new symbol to
6915show that the answer is ``indeterminate.'' @xref{Infinities}, for
6916further discussion of infinite and indeterminate values.
6917
6918@node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
6919@subsection Modes Tutorial Exercise 1
6920
6921@noindent
6922Calc always stores its numbers in decimal, so even though one-third has
6923an exact base-3 representation (@samp{3#0.1}), it is still stored as
69240.3333333 (chopped off after 12 or however many decimal digits) inside
6925the calculator's memory. When this inexact number is converted back
6926to base 3 for display, it may still be slightly inexact. When we
6927multiply this number by 3, we get 0.999999, also an inexact value.
6928
6929When Calc displays a number in base 3, it has to decide how many digits
6930to show. If the current precision is 12 (decimal) digits, that corresponds
6931to @samp{12 / log10(3) = 25.15} base-3 digits. Because 25.15 is not an
6932exact integer, Calc shows only 25 digits, with the result that stored
6933numbers carry a little bit of extra information that may not show up on
6934the screen. When Joe entered @samp{3#0.2}, the stored number 0.666666
6935happened to round to a pleasing value when it lost that last 0.15 of a
6936digit, but it was still inexact in Calc's memory. When he divided by 2,
6937he still got the dreaded inexact value 0.333333. (Actually, he divided
69380.666667 by 2 to get 0.333334, which is why he got something a little
6939higher than @code{3#0.1} instead of a little lower.)
6940
6941If Joe didn't want to be bothered with all this, he could have typed
6942@kbd{M-24 d n} to display with one less digit than the default. (If
6943you give @kbd{d n} a negative argument, it uses default-minus-that,
6944so @kbd{M-- d n} would be an easier way to get the same effect.) Those
6945inexact results would still be lurking there, but they would now be
6946rounded to nice, natural-looking values for display purposes. (Remember,
6947@samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
6948off one digit will round the number up to @samp{0.1}.) Depending on the
6949nature of your work, this hiding of the inexactness may be a benefit or
6950a danger. With the @kbd{d n} command, Calc gives you the choice.
6951
6952Incidentally, another consequence of all this is that if you type
6953@kbd{M-30 d n} to display more digits than are ``really there,''
6954you'll see garbage digits at the end of the number. (In decimal
6955display mode, with decimally-stored numbers, these garbage digits are
6956always zero so they vanish and you don't notice them.) Because Calc
6957rounds off that 0.15 digit, there is the danger that two numbers could
6958be slightly different internally but still look the same. If you feel
6959uneasy about this, set the @kbd{d n} precision to be a little higher
6960than normal; you'll get ugly garbage digits, but you'll always be able
6961to tell two distinct numbers apart.
6962
6963An interesting side note is that most computers store their
6964floating-point numbers in binary, and convert to decimal for display.
6965Thus everyday programs have the same problem: Decimal 0.1 cannot be
6966represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
6967comes out as an inexact approximation to 1 on some machines (though
6968they generally arrange to hide it from you by rounding off one digit as
6969we did above). Because Calc works in decimal instead of binary, you can
6970be sure that numbers that look exact @emph{are} exact as long as you stay
6971in decimal display mode.
6972
6973It's not hard to show that any number that can be represented exactly
6974in binary, octal, or hexadecimal is also exact in decimal, so the kinds
6975of problems we saw in this exercise are likely to be severe only when
6976you use a relatively unusual radix like 3.
6977
6978@node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
6979@subsection Modes Tutorial Exercise 2
6980
6981If the radix is 15 or higher, we can't use the letter @samp{e} to mark
6982the exponent because @samp{e} is interpreted as a digit. When Calc
6983needs to display scientific notation in a high radix, it writes
6984@samp{16#F.E8F*16.^15}. You can enter a number like this as an
6985algebraic entry. Also, pressing @kbd{e} without any digits before it
6986normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
6987puts you in algebraic entry: @kbd{16#f.e8f RET e 15 RET *} is another
6988way to enter this number.
6989
6990The reason Calc puts a decimal point in the @samp{16.^} is to prevent
6991huge integers from being generated if the exponent is large (consider
6992@samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
6993exact integer and then throw away most of the digits when we multiply
6994it by the floating-point @samp{16#1.23}). While this wouldn't normally
6995matter for display purposes, it could give you a nasty surprise if you
6996copied that number into a file and later moved it back into Calc.
6997
6998@node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
6999@subsection Modes Tutorial Exercise 3
7000
7001@noindent
7002The answer he got was @cite{0.5000000000006399}.
7003
7004The problem is not that the square operation is inexact, but that the
7005sine of 45 that was already on the stack was accurate to only 12 places.
7006Arbitrary-precision calculations still only give answers as good as
7007their inputs.
7008
7009The real problem is that there is no 12-digit number which, when
7010squared, comes out to 0.5 exactly. The @kbd{f [} and @kbd{f ]}
7011commands decrease or increase a number by one unit in the last
7012place (according to the current precision). They are useful for
7013determining facts like this.
7014
7015@group
7016@smallexample
70171: 0.707106781187 1: 0.500000000001
7018 . .
7019
7020 45 S 2 ^
7021
7022@end smallexample
7023@end group
7024@noindent
7025@group
7026@smallexample
70271: 0.707106781187 1: 0.707106781186 1: 0.499999999999
7028 . . .
7029
7030 U DEL f [ 2 ^
7031@end smallexample
7032@end group
7033
7034A high-precision calculation must be carried out in high precision
7035all the way. The only number in the original problem which was known
7036exactly was the quantity 45 degrees, so the precision must be raised
7037before anything is done after the number 45 has been entered in order
7038for the higher precision to be meaningful.
7039
7040@node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
7041@subsection Modes Tutorial Exercise 4
7042
7043@noindent
7044Many calculations involve real-world quantities, like the width and
7045height of a piece of wood or the volume of a jar. Such quantities
7046can't be measured exactly anyway, and if the data that is input to
7047a calculation is inexact, doing exact arithmetic on it is a waste
7048of time.
7049
7050Fractions become unwieldy after too many calculations have been
7051done with them. For example, the sum of the reciprocals of the
7052integers from 1 to 10 is 7381:2520. The sum from 1 to 30 is
70539304682830147:2329089562800. After a point it will take a long
7054time to add even one more term to this sum, but a floating-point
7055calculation of the sum will not have this problem.
7056
7057Also, rational numbers cannot express the results of all calculations.
7058There is no fractional form for the square root of two, so if you type
7059@w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
7060
7061@node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
7062@subsection Arithmetic Tutorial Exercise 1
7063
7064@noindent
7065Dividing two integers that are larger than the current precision may
7066give a floating-point result that is inaccurate even when rounded
7067down to an integer. Consider @cite{123456789 / 2} when the current
7068precision is 6 digits. The true answer is @cite{61728394.5}, but
7069with a precision of 6 this will be rounded to @c{$12345700.0/2.0 = 61728500.0$}
7070@cite{12345700.@: / 2.@: = 61728500.}.
7071The result, when converted to an integer, will be off by 106.
7072
7073Here are two solutions: Raise the precision enough that the
7074floating-point round-off error is strictly to the right of the
7075decimal point. Or, convert to fraction mode so that @cite{123456789 / 2}
7076produces the exact fraction @cite{123456789:2}, which can be rounded
7077down by the @kbd{F} command without ever switching to floating-point
7078format.
7079
7080@node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
7081@subsection Arithmetic Tutorial Exercise 2
7082
7083@noindent
7084@kbd{27 @key{RET} 9 B} could give the exact result @cite{3:2}, but it
7085does a floating-point calculation instead and produces @cite{1.5}.
7086
7087Calc will find an exact result for a logarithm if the result is an integer
7088or the reciprocal of an integer. But there is no efficient way to search
7089the space of all possible rational numbers for an exact answer, so Calc
7090doesn't try.
7091
7092@node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
7093@subsection Vector Tutorial Exercise 1
7094
7095@noindent
7096Duplicate the vector, compute its length, then divide the vector
7097by its length: @kbd{@key{RET} A /}.
7098
7099@group
7100@smallexample
71011: [1, 2, 3] 2: [1, 2, 3] 1: [0.27, 0.53, 0.80] 1: 1.
7102 . 1: 3.74165738677 . .
7103 .
7104
7105 r 1 RET A / A
7106@end smallexample
7107@end group
7108
7109The final @kbd{A} command shows that the normalized vector does
7110indeed have unit length.
7111
7112@node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
7113@subsection Vector Tutorial Exercise 2
7114
7115@noindent
7116The average position is equal to the sum of the products of the
7117positions times their corresponding probabilities. This is the
7118definition of the dot product operation. So all you need to do
7119is to put the two vectors on the stack and press @kbd{*}.
7120
7121@node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
7122@subsection Matrix Tutorial Exercise 1
7123
7124@noindent
7125The trick is to multiply by a vector of ones. Use @kbd{r 4 [1 1 1] *} to
7126get the row sum. Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
7127
7128@node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
7129@subsection Matrix Tutorial Exercise 2
7130
7131@ifinfo
7132@group
7133@example
7134 x + a y = 6
7135 x + b y = 10
7136@end example
7137@end group
7138@end ifinfo
7139@tex
7140\turnoffactive
7141\beforedisplay
7142$$ \eqalign{ x &+ a y = 6 \cr
7143 x &+ b y = 10}
7144$$
7145\afterdisplay
7146@end tex
7147
7148Just enter the righthand side vector, then divide by the lefthand side
7149matrix as usual.
7150
7151@group
7152@smallexample
71531: [6, 10] 2: [6, 10] 1: [6 - 4 a / (b - a), 4 / (b - a) ]
7154 . 1: [ [ 1, a ] .
7155 [ 1, b ] ]
7156 .
7157
7158' [6 10] RET ' [1 a; 1 b] RET /
7159@end smallexample
7160@end group
7161
7162This can be made more readable using @kbd{d B} to enable ``big'' display
7163mode:
7164
7165@group
7166@smallexample
7167 4 a 4
71681: [6 - -----, -----]
7169 b - a b - a
7170@end smallexample
7171@end group
7172
7173Type @kbd{d N} to return to ``normal'' display mode afterwards.
7174
7175@node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
7176@subsection Matrix Tutorial Exercise 3
7177
7178@noindent
7179To solve @c{$A^T A \, X = A^T B$}
7180@cite{trn(A) * A * X = trn(A) * B}, first we compute
7181@c{$A' = A^T A$}
7182@cite{A2 = trn(A) * A} and @c{$B' = A^T B$}
7183@cite{B2 = trn(A) * B}; now, we have a
7184system @c{$A' X = B'$}
7185@cite{A2 * X = B2} which we can solve using Calc's @samp{/}
7186command.
7187
7188@ifinfo
7189@group
7190@example
7191 a + 2b + 3c = 6
7192 4a + 5b + 6c = 2
7193 7a + 6b = 3
7194 2a + 4b + 6c = 11
7195@end example
7196@end group
7197@end ifinfo
7198@tex
7199\turnoffactive
7200\beforedisplayh
7201$$ \openup1\jot \tabskip=0pt plus1fil
7202\halign to\displaywidth{\tabskip=0pt
7203 $\hfil#$&$\hfil{}#{}$&
7204 $\hfil#$&$\hfil{}#{}$&
7205 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
7206 a&+&2b&+&3c&=6 \cr
7207 4a&+&5b&+&6c&=2 \cr
7208 7a&+&6b& & &=3 \cr
7209 2a&+&4b&+&6c&=11 \cr}
7210$$
7211\afterdisplayh
7212@end tex
7213
7214The first step is to enter the coefficient matrix. We'll store it in
7215quick variable number 7 for later reference. Next, we compute the
7216@c{$B'$}
7217@cite{B2} vector.
7218
7219@group
7220@smallexample
72211: [ [ 1, 2, 3 ] 2: [ [ 1, 4, 7, 2 ] 1: [57, 84, 96]
7222 [ 4, 5, 6 ] [ 2, 5, 6, 4 ] .
7223 [ 7, 6, 0 ] [ 3, 6, 0, 6 ] ]
7224 [ 2, 4, 6 ] ] 1: [6, 2, 3, 11]
7225 . .
7226
7227' [1 2 3; 4 5 6; 7 6 0; 2 4 6] RET s 7 v t [6 2 3 11] *
7228@end smallexample
7229@end group
7230
7231@noindent
7232Now we compute the matrix @c{$A'$}
7233@cite{A2} and divide.
7234
7235@group
7236@smallexample
72372: [57, 84, 96] 1: [-11.64, 14.08, -3.64]
72381: [ [ 70, 72, 39 ] .
7239 [ 72, 81, 60 ]
7240 [ 39, 60, 81 ] ]
7241 .
7242
7243 r 7 v t r 7 * /
7244@end smallexample
7245@end group
7246
7247@noindent
7248(The actual computed answer will be slightly inexact due to
7249round-off error.)
7250
7251Notice that the answers are similar to those for the @c{$3\times3$}
7252@asis{3x3} system
7253solved in the text. That's because the fourth equation that was
7254added to the system is almost identical to the first one multiplied
7255by two. (If it were identical, we would have gotten the exact same
7256answer since the @c{$4\times3$}
7257@asis{4x3} system would be equivalent to the original @c{$3\times3$}
7258@asis{3x3}
7259system.)
7260
7261Since the first and fourth equations aren't quite equivalent, they
7262can't both be satisfied at once. Let's plug our answers back into
7263the original system of equations to see how well they match.
7264
7265@group
7266@smallexample
72672: [-11.64, 14.08, -3.64] 1: [5.6, 2., 3., 11.2]
72681: [ [ 1, 2, 3 ] .
7269 [ 4, 5, 6 ]
7270 [ 7, 6, 0 ]
7271 [ 2, 4, 6 ] ]
7272 .
7273
7274 r 7 TAB *
7275@end smallexample
7276@end group
7277
7278@noindent
7279This is reasonably close to our original @cite{B} vector,
7280@cite{[6, 2, 3, 11]}.
7281
7282@node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
7283@subsection List Tutorial Exercise 1
7284
7285@noindent
7286We can use @kbd{v x} to build a vector of integers. This needs to be
7287adjusted to get the range of integers we desire. Mapping @samp{-}
7288across the vector will accomplish this, although it turns out the
7289plain @samp{-} key will work just as well.
7290
7291@group
7292@smallexample
72932: 2 2: 2
72941: [1, 2, 3, 4, 5, 6, 7, 8, 9] 1: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
7295 . .
7296
7297 2 v x 9 RET 5 V M - or 5 -
7298@end smallexample
7299@end group
7300
7301@noindent
7302Now we use @kbd{V M ^} to map the exponentiation operator across the
7303vector.
7304
7305@group
7306@smallexample
73071: [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
7308 .
7309
7310 V M ^
7311@end smallexample
7312@end group
7313
7314@node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
7315@subsection List Tutorial Exercise 2
7316
7317@noindent
7318Given @cite{x} and @cite{y} vectors in quick variables 1 and 2 as before,
7319the first job is to form the matrix that describes the problem.
7320
7321@ifinfo
7322@example
7323 m*x + b*1 = y
7324@end example
7325@end ifinfo
7326@tex
7327\turnoffactive
7328\beforedisplay
7329$$ m \times x + b \times 1 = y $$
7330\afterdisplay
7331@end tex
7332
7333Thus we want a @c{$19\times2$}
7334@asis{19x2} matrix with our @cite{x} vector as one column and
7335ones as the other column. So, first we build the column of ones, then
7336we combine the two columns to form our @cite{A} matrix.
7337
7338@group
7339@smallexample
73402: [1.34, 1.41, 1.49, ... ] 1: [ [ 1.34, 1 ]
73411: [1, 1, 1, ...] [ 1.41, 1 ]
7342 . [ 1.49, 1 ]
7343 @dots{}
7344
7345 r 1 1 v b 19 RET M-2 v p v t s 3
7346@end smallexample
7347@end group
7348
7349@noindent
7350Now we compute @c{$A^T y$}
7351@cite{trn(A) * y} and @c{$A^T A$}
7352@cite{trn(A) * A} and divide.
7353
7354@group
7355@smallexample
73561: [33.36554, 13.613] 2: [33.36554, 13.613]
7357 . 1: [ [ 98.0003, 41.63 ]
7358 [ 41.63, 19 ] ]
7359 .
7360
7361 v t r 2 * r 3 v t r 3 *
7362@end smallexample
7363@end group
7364
7365@noindent
7366(Hey, those numbers look familiar!)
7367
7368@group
7369@smallexample
73701: [0.52141679, -0.425978]
7371 .
7372
7373 /
7374@end smallexample
7375@end group
7376
7377Since we were solving equations of the form @c{$m \times x + b \times 1 = y$}
7378@cite{m*x + b*1 = y}, these
7379numbers should be @cite{m} and @cite{b}, respectively. Sure enough, they
7380agree exactly with the result computed using @kbd{V M} and @kbd{V R}!
7381
7382The moral of this story: @kbd{V M} and @kbd{V R} will probably solve
7383your problem, but there is often an easier way using the higher-level
7384arithmetic functions!
7385
7386@c [fix-ref Curve Fitting]
7387In fact, there is a built-in @kbd{a F} command that does least-squares
7388fits. @xref{Curve Fitting}.
7389
7390@node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
7391@subsection List Tutorial Exercise 3
7392
7393@noindent
7394Move to one end of the list and press @kbd{C-@@} (or @kbd{C-SPC} or
7395whatever) to set the mark, then move to the other end of the list
7396and type @w{@kbd{M-# g}}.
7397
7398@group
7399@smallexample
74001: [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
7401 .
7402@end smallexample
7403@end group
7404
7405To make things interesting, let's assume we don't know at a glance
7406how many numbers are in this list. Then we could type:
7407
7408@group
7409@smallexample
74102: [2.3, 6, 22, ... ] 2: [2.3, 6, 22, ... ]
74111: [2.3, 6, 22, ... ] 1: 126356422.5
7412 . .
7413
7414 RET V R *
7415
7416@end smallexample
7417@end group
7418@noindent
7419@group
7420@smallexample
74212: 126356422.5 2: 126356422.5 1: 7.94652913734
74221: [2.3, 6, 22, ... ] 1: 9 .
7423 . .
7424
7425 TAB v l I ^
7426@end smallexample
7427@end group
7428
7429@noindent
7430(The @kbd{I ^} command computes the @var{n}th root of a number.
7431You could also type @kbd{& ^} to take the reciprocal of 9 and
7432then raise the number to that power.)
7433
7434@node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
7435@subsection List Tutorial Exercise 4
7436
7437@noindent
7438A number @cite{j} is a divisor of @cite{n} if @c{$n \mathbin{\hbox{\code{\%}}} j = 0$}
7439@samp{n % j = 0}. The first
7440step is to get a vector that identifies the divisors.
7441
7442@group
7443@smallexample
74442: 30 2: [0, 0, 0, 2, ...] 1: [1, 1, 1, 0, ...]
74451: [1, 2, 3, 4, ...] 1: 0 .
7446 . .
7447
7448 30 RET v x 30 RET s 1 V M % 0 V M a = s 2
7449@end smallexample
7450@end group
7451
7452@noindent
7453This vector has 1's marking divisors of 30 and 0's marking non-divisors.
7454
7455The zeroth divisor function is just the total number of divisors.
7456The first divisor function is the sum of the divisors.
7457
7458@group
7459@smallexample
74601: 8 3: 8 2: 8 2: 8
7461 2: [1, 2, 3, 4, ...] 1: [1, 2, 3, 0, ...] 1: 72
7462 1: [1, 1, 1, 0, ...] . .
7463 .
7464
7465 V R + r 1 r 2 V M * V R +
7466@end smallexample
7467@end group
7468
7469@noindent
7470Once again, the last two steps just compute a dot product for which
7471a simple @kbd{*} would have worked equally well.
7472
7473@node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
7474@subsection List Tutorial Exercise 5
7475
7476@noindent
7477The obvious first step is to obtain the list of factors with @kbd{k f}.
7478This list will always be in sorted order, so if there are duplicates
7479they will be right next to each other. A suitable method is to compare
7480the list with a copy of itself shifted over by one.
7481
7482@group
7483@smallexample
74841: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19, 0]
7485 . 1: [3, 7, 7, 7, 19, 0] 1: [0, 3, 7, 7, 7, 19]
7486 . .
7487
7488 19551 k f RET 0 | TAB 0 TAB |
7489
7490@end smallexample
7491@end group
7492@noindent
7493@group
7494@smallexample
74951: [0, 0, 1, 1, 0, 0] 1: 2 1: 0
7496 . . .
7497
7498 V M a = V R + 0 a =
7499@end smallexample
7500@end group
7501
7502@noindent
7503Note that we have to arrange for both vectors to have the same length
7504so that the mapping operation works; no prime factor will ever be
7505zero, so adding zeros on the left and right is safe. From then on
7506the job is pretty straightforward.
7507
7508Incidentally, Calc provides the @c{\dfn{M\"obius} $\mu$}
7509@dfn{Moebius mu} function which is
7510zero if and only if its argument is square-free. It would be a much
7511more convenient way to do the above test in practice.
7512
7513@node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
7514@subsection List Tutorial Exercise 6
7515
7516@noindent
7517First use @kbd{v x 6 RET} to get a list of integers, then @kbd{V M v x}
7518to get a list of lists of integers!
7519
7520@node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
7521@subsection List Tutorial Exercise 7
7522
7523@noindent
7524Here's one solution. First, compute the triangular list from the previous
7525exercise and type @kbd{1 -} to subtract one from all the elements.
7526
7527@group
7528@smallexample
75291: [ [0],
7530 [0, 1],
7531 [0, 1, 2],
7532 @dots{}
7533
7534 1 -
7535@end smallexample
7536@end group
7537
7538The numbers down the lefthand edge of the list we desire are called
7539the ``triangular numbers'' (now you know why!). The @cite{n}th
7540triangular number is the sum of the integers from 1 to @cite{n}, and
7541can be computed directly by the formula @c{$n (n+1) \over 2$}
7542@cite{n * (n+1) / 2}.
7543
7544@group
7545@smallexample
75462: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
75471: [0, 1, 2, 3, 4, 5] 1: [0, 1, 3, 6, 10, 15]
7548 . .
7549
7550 v x 6 RET 1 - V M ' $ ($+1)/2 RET
7551@end smallexample
7552@end group
7553
7554@noindent
7555Adding this list to the above list of lists produces the desired
7556result:
7557
7558@group
7559@smallexample
75601: [ [0],
7561 [1, 2],
7562 [3, 4, 5],
7563 [6, 7, 8, 9],
7564 [10, 11, 12, 13, 14],
7565 [15, 16, 17, 18, 19, 20] ]
7566 .
7567
7568 V M +
7569@end smallexample
7570@end group
7571
7572If we did not know the formula for triangular numbers, we could have
7573computed them using a @kbd{V U +} command. We could also have
7574gotten them the hard way by mapping a reduction across the original
7575triangular list.
7576
7577@group
7578@smallexample
75792: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
75801: [ [0], [0, 1], ... ] 1: [0, 1, 3, 6, 10, 15]
7581 . .
7582
7583 RET V M V R +
7584@end smallexample
7585@end group
7586
7587@noindent
7588(This means ``map a @kbd{V R +} command across the vector,'' and
7589since each element of the main vector is itself a small vector,
7590@kbd{V R +} computes the sum of its elements.)
7591
7592@node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
7593@subsection List Tutorial Exercise 8
7594
7595@noindent
7596The first step is to build a list of values of @cite{x}.
7597
7598@group
7599@smallexample
76001: [1, 2, 3, ..., 21] 1: [0, 1, 2, ..., 20] 1: [0, 0.25, 0.5, ..., 5]
7601 . . .
7602
7603 v x 21 RET 1 - 4 / s 1
7604@end smallexample
7605@end group
7606
7607Next, we compute the Bessel function values.
7608
7609@group
7610@smallexample
76111: [0., 0.124, 0.242, ..., -0.328]
7612 .
7613
7614 V M ' besJ(1,$) RET
7615@end smallexample
7616@end group
7617
7618@noindent
7619(Another way to do this would be @kbd{1 TAB V M f j}.)
7620
7621A way to isolate the maximum value is to compute the maximum using
7622@kbd{V R X}, then compare all the Bessel values with that maximum.
7623
7624@group
7625@smallexample
76262: [0., 0.124, 0.242, ... ] 1: [0, 0, 0, ... ] 2: [0, 0, 0, ... ]
76271: 0.5801562 . 1: 1
7628 . .
7629
7630 RET V R X V M a = RET V R + DEL
7631@end smallexample
7632@end group
7633
7634@noindent
7635It's a good idea to verify, as in the last step above, that only
7636one value is equal to the maximum. (After all, a plot of @c{$\sin x$}
7637@cite{sin(x)}
7638might have many points all equal to the maximum value, 1.)
7639
7640The vector we have now has a single 1 in the position that indicates
7641the maximum value of @cite{x}. Now it is a simple matter to convert
7642this back into the corresponding value itself.
7643
7644@group
7645@smallexample
76462: [0, 0, 0, ... ] 1: [0, 0., 0., ... ] 1: 1.75
76471: [0, 0.25, 0.5, ... ] . .
7648 .
7649
7650 r 1 V M * V R +
7651@end smallexample
7652@end group
7653
7654If @kbd{a =} had produced more than one @cite{1} value, this method
7655would have given the sum of all maximum @cite{x} values; not very
7656useful! In this case we could have used @kbd{v m} (@code{calc-mask-vector})
7657instead. This command deletes all elements of a ``data'' vector that
7658correspond to zeros in a ``mask'' vector, leaving us with, in this
7659example, a vector of maximum @cite{x} values.
7660
7661The built-in @kbd{a X} command maximizes a function using more
7662efficient methods. Just for illustration, let's use @kbd{a X}
7663to maximize @samp{besJ(1,x)} over this same interval.
7664
7665@group
7666@smallexample
76672: besJ(1, x) 1: [1.84115, 0.581865]
76681: [0 .. 5] .
7669 .
7670
7671' besJ(1,x), [0..5] RET a X x RET
7672@end smallexample
7673@end group
7674
7675@noindent
7676The output from @kbd{a X} is a vector containing the value of @cite{x}
7677that maximizes the function, and the function's value at that maximum.
7678As you can see, our simple search got quite close to the right answer.
7679
7680@node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
7681@subsection List Tutorial Exercise 9
7682
7683@noindent
7684Step one is to convert our integer into vector notation.
7685
7686@group
7687@smallexample
76881: 25129925999 3: 25129925999
7689 . 2: 10
7690 1: [11, 10, 9, ..., 1, 0]
7691 .
7692
7693 25129925999 RET 10 RET 12 RET v x 12 RET -
7694
7695@end smallexample
7696@end group
7697@noindent
7698@group
7699@smallexample
77001: 25129925999 1: [0, 2, 25, 251, 2512, ... ]
77012: [100000000000, ... ] .
7702 .
7703
7704 V M ^ s 1 V M \
7705@end smallexample
7706@end group
7707
7708@noindent
7709(Recall, the @kbd{\} command computes an integer quotient.)
7710
7711@group
7712@smallexample
77131: [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
7714 .
7715
7716 10 V M % s 2
7717@end smallexample
7718@end group
7719
7720Next we must increment this number. This involves adding one to
7721the last digit, plus handling carries. There is a carry to the
7722left out of a digit if that digit is a nine and all the digits to
7723the right of it are nines.
7724
7725@group
7726@smallexample
77271: [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1] 1: [1, 1, 1, 0, 0, 1, ... ]
7728 . .
7729
7730 9 V M a = v v
7731
7732@end smallexample
7733@end group
7734@noindent
7735@group
7736@smallexample
77371: [1, 1, 1, 0, 0, 0, ... ] 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
7738 . .
7739
7740 V U * v v 1 |
7741@end smallexample
7742@end group
7743
7744@noindent
7745Accumulating @kbd{*} across a vector of ones and zeros will preserve
7746only the initial run of ones. These are the carries into all digits
7747except the rightmost digit. Concatenating a one on the right takes
7748care of aligning the carries properly, and also adding one to the
7749rightmost digit.
7750
7751@group
7752@smallexample
77532: [0, 0, 0, 0, ... ] 1: [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
77541: [0, 0, 2, 5, ... ] .
7755 .
7756
7757 0 r 2 | V M + 10 V M %
7758@end smallexample
7759@end group
7760
7761@noindent
7762Here we have concatenated 0 to the @emph{left} of the original number;
7763this takes care of shifting the carries by one with respect to the
7764digits that generated them.
7765
7766Finally, we must convert this list back into an integer.
7767
7768@group
7769@smallexample
77703: [0, 0, 2, 5, ... ] 2: [0, 0, 2, 5, ... ]
77712: 1000000000000 1: [1000000000000, 100000000000, ... ]
77721: [100000000000, ... ] .
7773 .
7774
7775 10 RET 12 ^ r 1 |
7776
7777@end smallexample
7778@end group
7779@noindent
7780@group
7781@smallexample
77821: [0, 0, 20000000000, 5000000000, ... ] 1: 25129926000
7783 . .
7784
7785 V M * V R +
7786@end smallexample
7787@end group
7788
7789@noindent
7790Another way to do this final step would be to reduce the formula
7791@w{@samp{10 $$ + $}} across the vector of digits.
7792
7793@group
7794@smallexample
77951: [0, 0, 2, 5, ... ] 1: 25129926000
7796 . .
7797
7798 V R ' 10 $$ + $ RET
7799@end smallexample
7800@end group
7801
7802@node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
7803@subsection List Tutorial Exercise 10
7804
7805@noindent
7806For the list @cite{[a, b, c, d]}, the result is @cite{((a = b) = c) = d},
7807which will compare @cite{a} and @cite{b} to produce a 1 or 0, which is
7808then compared with @cite{c} to produce another 1 or 0, which is then
7809compared with @cite{d}. This is not at all what Joe wanted.
7810
7811Here's a more correct method:
7812
7813@group
7814@smallexample
78151: [7, 7, 7, 8, 7] 2: [7, 7, 7, 8, 7]
7816 . 1: 7
7817 .
7818
7819 ' [7,7,7,8,7] RET RET v r 1 RET
7820
7821@end smallexample
7822@end group
7823@noindent
7824@group
7825@smallexample
78261: [1, 1, 1, 0, 1] 1: 0
7827 . .
7828
7829 V M a = V R *
7830@end smallexample
7831@end group
7832
7833@node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
7834@subsection List Tutorial Exercise 11
7835
7836@noindent
7837The circle of unit radius consists of those points @cite{(x,y)} for which
7838@cite{x^2 + y^2 < 1}. We start by generating a vector of @cite{x^2}
7839and a vector of @cite{y^2}.
7840
7841We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7842commands.
7843
7844@group
7845@smallexample
78462: [2., 2., ..., 2.] 2: [2., 2., ..., 2.]
78471: [2., 2., ..., 2.] 1: [1.16, 1.98, ..., 0.81]
7848 . .
7849
7850 v . t . 2. v b 100 RET RET V M k r
7851
7852@end smallexample
7853@end group
7854@noindent
7855@group
7856@smallexample
78572: [2., 2., ..., 2.] 1: [0.026, 0.96, ..., 0.036]
78581: [0.026, 0.96, ..., 0.036] 2: [0.53, 0.81, ..., 0.094]
7859 . .
7860
7861 1 - 2 V M ^ TAB V M k r 1 - 2 V M ^
7862@end smallexample
7863@end group
7864
7865Now we sum the @cite{x^2} and @cite{y^2} values, compare with 1 to
7866get a vector of 1/0 truth values, then sum the truth values.
7867
7868@group
7869@smallexample
78701: [0.56, 1.78, ..., 0.13] 1: [1, 0, ..., 1] 1: 84
7871 . . .
7872
7873 + 1 V M a < V R +
7874@end smallexample
7875@end group
7876
7877@noindent
7878The ratio @cite{84/100} should approximate the ratio @c{$\pi/4$}
7879@cite{pi/4}.
7880
7881@group
7882@smallexample
78831: 0.84 1: 3.36 2: 3.36 1: 1.0695
7884 . . 1: 3.14159 .
7885
7886 100 / 4 * P /
7887@end smallexample
7888@end group
7889
7890@noindent
7891Our estimate, 3.36, is off by about 7%. We could get a better estimate
7892by taking more points (say, 1000), but it's clear that this method is
7893not very efficient!
7894
7895(Naturally, since this example uses random numbers your own answer
7896will be slightly different from the one shown here!)
7897
7898If you typed @kbd{v .} and @kbd{t .} before, type them again to
7899return to full-sized display of vectors.
7900
7901@node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
7902@subsection List Tutorial Exercise 12
7903
7904@noindent
7905This problem can be made a lot easier by taking advantage of some
7906symmetries. First of all, after some thought it's clear that the
7907@cite{y} axis can be ignored altogether. Just pick a random @cite{x}
7908component for one end of the match, pick a random direction @c{$\theta$}
7909@cite{theta},
7910and see if @cite{x} and @c{$x + \cos \theta$}
7911@cite{x + cos(theta)} (which is the @cite{x}
7912coordinate of the other endpoint) cross a line. The lines are at
7913integer coordinates, so this happens when the two numbers surround
7914an integer.
7915
7916Since the two endpoints are equivalent, we may as well choose the leftmost
7917of the two endpoints as @cite{x}. Then @cite{theta} is an angle pointing
7918to the right, in the range -90 to 90 degrees. (We could use radians, but
7919it would feel like cheating to refer to @c{$\pi/2$}
7920@cite{pi/2} radians while trying
7921to estimate @c{$\pi$}
7922@cite{pi}!)
7923
7924In fact, since the field of lines is infinite we can choose the
7925coordinates 0 and 1 for the lines on either side of the leftmost
7926endpoint. The rightmost endpoint will be between 0 and 1 if the
7927match does not cross a line, or between 1 and 2 if it does. So:
7928Pick random @cite{x} and @c{$\theta$}
7929@cite{theta}, compute @c{$x + \cos \theta$}
7930@cite{x + cos(theta)},
7931and count how many of the results are greater than one. Simple!
7932
7933We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7934commands.
7935
7936@group
7937@smallexample
79381: [0.52, 0.71, ..., 0.72] 2: [0.52, 0.71, ..., 0.72]
7939 . 1: [78.4, 64.5, ..., -42.9]
7940 .
7941
7942v . t . 1. v b 100 RET V M k r 180. v b 100 RET V M k r 90 -
7943@end smallexample
7944@end group
7945
7946@noindent
7947(The next step may be slow, depending on the speed of your computer.)
7948
7949@group
7950@smallexample
79512: [0.52, 0.71, ..., 0.72] 1: [0.72, 1.14, ..., 1.45]
79521: [0.20, 0.43, ..., 0.73] .
7953 .
7954
7955 m d V M C +
7956
7957@end smallexample
7958@end group
7959@noindent
7960@group
7961@smallexample
79621: [0, 1, ..., 1] 1: 0.64 1: 3.125
7963 . . .
7964
7965 1 V M a > V R + 100 / 2 TAB /
7966@end smallexample
7967@end group
7968
7969Let's try the third method, too. We'll use random integers up to
7970one million. The @kbd{k r} command with an integer argument picks
7971a random integer.
7972
7973@group
7974@smallexample
79752: [1000000, 1000000, ..., 1000000] 2: [78489, 527587, ..., 814975]
79761: [1000000, 1000000, ..., 1000000] 1: [324014, 358783, ..., 955450]
7977 . .
7978
7979 1000000 v b 100 RET RET V M k r TAB V M k r
7980
7981@end smallexample
7982@end group
7983@noindent
7984@group
7985@smallexample
79861: [1, 1, ..., 25] 1: [1, 1, ..., 0] 1: 0.56
7987 . . .
7988
7989 V M k g 1 V M a = V R + 100 /
7990
7991@end smallexample
7992@end group
7993@noindent
7994@group
7995@smallexample
79961: 10.714 1: 3.273
7997 . .
7998
7999 6 TAB / Q
8000@end smallexample
8001@end group
8002
8003For a proof of this property of the GCD function, see section 4.5.2,
8004exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
8005
8006If you typed @kbd{v .} and @kbd{t .} before, type them again to
8007return to full-sized display of vectors.
8008
8009@node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
8010@subsection List Tutorial Exercise 13
8011
8012@noindent
8013First, we put the string on the stack as a vector of ASCII codes.
8014
8015@group
8016@smallexample
80171: [84, 101, 115, ..., 51]
8018 .
8019
8020 "Testing, 1, 2, 3 RET
8021@end smallexample
8022@end group
8023
8024@noindent
8025Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
8026there was no need to type an apostrophe. Also, Calc didn't mind that
8027we omitted the closing @kbd{"}. (The same goes for all closing delimiters
8028like @kbd{)} and @kbd{]} at the end of a formula.
8029
8030We'll show two different approaches here. In the first, we note that
8031if the input vector is @cite{[a, b, c, d]}, then the hash code is
8032@cite{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}. In other words,
8033it's a sum of descending powers of three times the ASCII codes.
8034
8035@group
8036@smallexample
80372: [84, 101, 115, ..., 51] 2: [84, 101, 115, ..., 51]
80381: 16 1: [15, 14, 13, ..., 0]
8039 . .
8040
8041 RET v l v x 16 RET -
8042
8043@end smallexample
8044@end group
8045@noindent
8046@group
8047@smallexample
80482: [84, 101, 115, ..., 51] 1: 1960915098 1: 121
80491: [14348907, ..., 1] . .
8050 .
8051
8052 3 TAB V M ^ * 511 %
8053@end smallexample
8054@end group
8055
8056@noindent
8057Once again, @kbd{*} elegantly summarizes most of the computation.
8058But there's an even more elegant approach: Reduce the formula
8059@kbd{3 $$ + $} across the vector. Recall that this represents a
8060function of two arguments that computes its first argument times three
8061plus its second argument.
8062
8063@group
8064@smallexample
80651: [84, 101, 115, ..., 51] 1: 1960915098
8066 . .
8067
8068 "Testing, 1, 2, 3 RET V R ' 3$$+$ RET
8069@end smallexample
8070@end group
8071
8072@noindent
8073If you did the decimal arithmetic exercise, this will be familiar.
8074Basically, we're turning a base-3 vector of digits into an integer,
8075except that our ``digits'' are much larger than real digits.
8076
8077Instead of typing @kbd{511 %} again to reduce the result, we can be
8078cleverer still and notice that rather than computing a huge integer
8079and taking the modulo at the end, we can take the modulo at each step
8080without affecting the result. While this means there are more
8081arithmetic operations, the numbers we operate on remain small so
8082the operations are faster.
8083
8084@group
8085@smallexample
80861: [84, 101, 115, ..., 51] 1: 121
8087 . .
8088
8089 "Testing, 1, 2, 3 RET V R ' (3$$+$)%511 RET
8090@end smallexample
8091@end group
8092
8093Why does this work? Think about a two-step computation:
8094@w{@cite{3 (3a + b) + c}}. Taking a result modulo 511 basically means
8095subtracting off enough 511's to put the result in the desired range.
8096So the result when we take the modulo after every step is,
8097
8098@ifinfo
8099@example
81003 (3 a + b - 511 m) + c - 511 n
8101@end example
8102@end ifinfo
8103@tex
8104\turnoffactive
8105\beforedisplay
8106$$ 3 (3 a + b - 511 m) + c - 511 n $$
8107\afterdisplay
8108@end tex
8109
8110@noindent
8111for some suitable integers @cite{m} and @cite{n}. Expanding out by
8112the distributive law yields
8113
8114@ifinfo
8115@example
81169 a + 3 b + c - 511*3 m - 511 n
8117@end example
8118@end ifinfo
8119@tex
8120\turnoffactive
8121\beforedisplay
8122$$ 9 a + 3 b + c - 511\times3 m - 511 n $$
8123\afterdisplay
8124@end tex
8125
8126@noindent
8127The @cite{m} term in the latter formula is redundant because any
8128contribution it makes could just as easily be made by the @cite{n}
8129term. So we can take it out to get an equivalent formula with
8130@cite{n' = 3m + n},
8131
8132@ifinfo
8133@example
81349 a + 3 b + c - 511 n'
8135@end example
8136@end ifinfo
8137@tex
8138\turnoffactive
8139\beforedisplay
8140$$ 9 a + 3 b + c - 511 n' $$
8141\afterdisplay
8142@end tex
8143
8144@noindent
8145which is just the formula for taking the modulo only at the end of
8146the calculation. Therefore the two methods are essentially the same.
8147
8148Later in the tutorial we will encounter @dfn{modulo forms}, which
8149basically automate the idea of reducing every intermediate result
8150modulo some value @i{M}.
8151
8152@node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
8153@subsection List Tutorial Exercise 14
8154
8155We want to use @kbd{H V U} to nest a function which adds a random
8156step to an @cite{(x,y)} coordinate. The function is a bit long, but
8157otherwise the problem is quite straightforward.
8158
8159@group
8160@smallexample
81612: [0, 0] 1: [ [ 0, 0 ]
81621: 50 [ 0.4288, -0.1695 ]
8163 . [ -0.4787, -0.9027 ]
8164 ...
8165
8166 [0,0] 50 H V U ' <# + [random(2.0)-1, random(2.0)-1]> RET
8167@end smallexample
8168@end group
8169
8170Just as the text recommended, we used @samp{< >} nameless function
8171notation to keep the two @code{random} calls from being evaluated
8172before nesting even begins.
8173
8174We now have a vector of @cite{[x, y]} sub-vectors, which by Calc's
8175rules acts like a matrix. We can transpose this matrix and unpack
8176to get a pair of vectors, @cite{x} and @cite{y}, suitable for graphing.
8177
8178@group
8179@smallexample
81802: [ 0, 0.4288, -0.4787, ... ]
81811: [ 0, -0.1696, -0.9027, ... ]
8182 .
8183
8184 v t v u g f
8185@end smallexample
8186@end group
8187
8188Incidentally, because the @cite{x} and @cite{y} are completely
8189independent in this case, we could have done two separate commands
8190to create our @cite{x} and @cite{y} vectors of numbers directly.
8191
8192To make a random walk of unit steps, we note that @code{sincos} of
8193a random direction exactly gives us an @cite{[x, y]} step of unit
8194length; in fact, the new nesting function is even briefer, though
8195we might want to lower the precision a bit for it.
8196
8197@group
8198@smallexample
81992: [0, 0] 1: [ [ 0, 0 ]
82001: 50 [ 0.1318, 0.9912 ]
8201 . [ -0.5965, 0.3061 ]
8202 ...
8203
8204 [0,0] 50 m d p 6 RET H V U ' <# + sincos(random(360.0))> RET
8205@end smallexample
8206@end group
8207
8208Another @kbd{v t v u g f} sequence will graph this new random walk.
8209
8210An interesting twist on these random walk functions would be to use
8211complex numbers instead of 2-vectors to represent points on the plane.
8212In the first example, we'd use something like @samp{random + random*(0,1)},
8213and in the second we could use polar complex numbers with random phase
8214angles. (This exercise was first suggested in this form by Randal
8215Schwartz.)
8216
8217@node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
8218@subsection Types Tutorial Exercise 1
8219
8220@noindent
8221If the number is the square root of @c{$\pi$}
8222@cite{pi} times a rational number,
8223then its square, divided by @c{$\pi$}
8224@cite{pi}, should be a rational number.
8225
8226@group
8227@smallexample
82281: 1.26508260337 1: 0.509433962268 1: 2486645810:4881193627
8229 . . .
8230
8231 2 ^ P / c F
8232@end smallexample
8233@end group
8234
8235@noindent
8236Technically speaking this is a rational number, but not one that is
8237likely to have arisen in the original problem. More likely, it just
8238happens to be the fraction which most closely represents some
8239irrational number to within 12 digits.
8240
8241But perhaps our result was not quite exact. Let's reduce the
8242precision slightly and try again:
8243
8244@group
8245@smallexample
82461: 0.509433962268 1: 27:53
8247 . .
8248
8249 U p 10 RET c F
8250@end smallexample
8251@end group
8252
8253@noindent
8254Aha! It's unlikely that an irrational number would equal a fraction
8255this simple to within ten digits, so our original number was probably
8256@c{$\sqrt{27 \pi / 53}$}
8257@cite{sqrt(27 pi / 53)}.
8258
8259Notice that we didn't need to re-round the number when we reduced the
8260precision. Remember, arithmetic operations always round their inputs
8261to the current precision before they begin.
8262
8263@node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
8264@subsection Types Tutorial Exercise 2
8265
8266@noindent
8267@samp{inf / inf = nan}. Perhaps @samp{1} is the ``obvious'' answer.
8268But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
8269
8270@samp{exp(inf) = inf}. It's tempting to say that the exponential
8271of infinity must be ``bigger'' than ``regular'' infinity, but as
8272far as Calc is concerned all infinities are as just as big.
8273In other words, as @cite{x} goes to infinity, @cite{e^x} also goes
8274to infinity, but the fact the @cite{e^x} grows much faster than
8275@cite{x} is not relevant here.
8276
8277@samp{exp(-inf) = 0}. Here we have a finite answer even though
8278the input is infinite.
8279
8280@samp{sqrt(-inf) = (0, 1) inf}. Remember that @cite{(0, 1)}
8281represents the imaginary number @cite{i}. Here's a derivation:
8282@samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
8283The first part is, by definition, @cite{i}; the second is @code{inf}
8284because, once again, all infinities are the same size.
8285
8286@samp{sqrt(uinf) = uinf}. In fact, we do know something about the
8287direction because @code{sqrt} is defined to return a value in the
8288right half of the complex plane. But Calc has no notation for this,
8289so it settles for the conservative answer @code{uinf}.
8290
8291@samp{abs(uinf) = inf}. No matter which direction @cite{x} points,
8292@samp{abs(x)} always points along the positive real axis.
8293
8294@samp{ln(0) = -inf}. Here we have an infinite answer to a finite
8295input. As in the @cite{1 / 0} case, Calc will only use infinities
8296here if you have turned on ``infinite'' mode. Otherwise, it will
8297treat @samp{ln(0)} as an error.
8298
8299@node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
8300@subsection Types Tutorial Exercise 3
8301
8302@noindent
8303We can make @samp{inf - inf} be any real number we like, say,
8304@cite{a}, just by claiming that we added @cite{a} to the first
8305infinity but not to the second. This is just as true for complex
8306values of @cite{a}, so @code{nan} can stand for a complex number.
8307(And, similarly, @code{uinf} can stand for an infinity that points
8308in any direction in the complex plane, such as @samp{(0, 1) inf}).
8309
8310In fact, we can multiply the first @code{inf} by two. Surely
8311@w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
8312So @code{nan} can even stand for infinity. Obviously it's just
8313as easy to make it stand for minus infinity as for plus infinity.
8314
8315The moral of this story is that ``infinity'' is a slippery fish
8316indeed, and Calc tries to handle it by having a very simple model
8317for infinities (only the direction counts, not the ``size''); but
8318Calc is careful to write @code{nan} any time this simple model is
8319unable to tell what the true answer is.
8320
8321@node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
8322@subsection Types Tutorial Exercise 4
8323
8324@group
8325@smallexample
83262: 0@@ 47' 26" 1: 0@@ 2' 47.411765"
83271: 17 .
8328 .
8329
8330 0@@ 47' 26" RET 17 /
8331@end smallexample
8332@end group
8333
8334@noindent
8335The average song length is two minutes and 47.4 seconds.
8336
8337@group
8338@smallexample
83392: 0@@ 2' 47.411765" 1: 0@@ 3' 7.411765" 1: 0@@ 53' 6.000005"
83401: 0@@ 0' 20" . .
8341 .
8342
8343 20" + 17 *
8344@end smallexample
8345@end group
8346
8347@noindent
8348The album would be 53 minutes and 6 seconds long.
8349
8350@node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
8351@subsection Types Tutorial Exercise 5
8352
8353@noindent
8354Let's suppose it's January 14, 1991. The easiest thing to do is
8355to keep trying 13ths of months until Calc reports a Friday.
8356We can do this by manually entering dates, or by using @kbd{t I}:
8357
8358@group
8359@smallexample
83601: <Wed Feb 13, 1991> 1: <Wed Mar 13, 1991> 1: <Sat Apr 13, 1991>
8361 . . .
8362
8363 ' <2/13> RET DEL ' <3/13> RET t I
8364@end smallexample
8365@end group
8366
8367@noindent
8368(Calc assumes the current year if you don't say otherwise.)
8369
8370This is getting tedious---we can keep advancing the date by typing
8371@kbd{t I} over and over again, but let's automate the job by using
8372vector mapping. The @kbd{t I} command actually takes a second
8373``how-many-months'' argument, which defaults to one. This
8374argument is exactly what we want to map over:
8375
8376@group
8377@smallexample
83782: <Sat Apr 13, 1991> 1: [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
83791: [1, 2, 3, 4, 5, 6] <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
8380 . <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
8381 .
8382
8383 v x 6 RET V M t I
8384@end smallexample
8385@end group
8386
8387@ifinfo
8388@noindent
8389Et voila, September 13, 1991 is a Friday.
8390@end ifinfo
8391@tex
8392\noindent
8393{\it Et voil{\accent"12 a}}, September 13, 1991 is a Friday.
8394@end tex
8395
8396@group
8397@smallexample
83981: 242
8399 .
8400
8401' <sep 13> - <jan 14> RET
8402@end smallexample
8403@end group
8404
8405@noindent
8406And the answer to our original question: 242 days to go.
8407
8408@node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
8409@subsection Types Tutorial Exercise 6
8410
8411@noindent
8412The full rule for leap years is that they occur in every year divisible
8413by four, except that they don't occur in years divisible by 100, except
8414that they @emph{do} in years divisible by 400. We could work out the
8415answer by carefully counting the years divisible by four and the
8416exceptions, but there is a much simpler way that works even if we
8417don't know the leap year rule.
8418
8419Let's assume the present year is 1991. Years have 365 days, except
8420that leap years (whenever they occur) have 366 days. So let's count
8421the number of days between now and then, and compare that to the
8422number of years times 365. The number of extra days we find must be
8423equal to the number of leap years there were.
8424
8425@group
8426@smallexample
84271: <Mon Jan 1, 10001> 2: <Mon Jan 1, 10001> 1: 2925593
8428 . 1: <Tue Jan 1, 1991> .
8429 .
8430
8431 ' <jan 1 10001> RET ' <jan 1 1991> RET -
8432
8433@end smallexample
8434@end group
8435@noindent
8436@group
8437@smallexample
84383: 2925593 2: 2925593 2: 2925593 1: 1943
84392: 10001 1: 8010 1: 2923650 .
84401: 1991 . .
8441 .
8442
8443 10001 RET 1991 - 365 * -
8444@end smallexample
8445@end group
8446
8447@c [fix-ref Date Forms]
8448@noindent
8449There will be 1943 leap years before the year 10001. (Assuming,
8450of course, that the algorithm for computing leap years remains
8451unchanged for that long. @xref{Date Forms}, for some interesting
8452background information in that regard.)
8453
8454@node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
8455@subsection Types Tutorial Exercise 7
8456
8457@noindent
8458The relative errors must be converted to absolute errors so that
8459@samp{+/-} notation may be used.
8460
8461@group
8462@smallexample
84631: 1. 2: 1.
8464 . 1: 0.2
8465 .
8466
8467 20 RET .05 * 4 RET .05 *
8468@end smallexample
8469@end group
8470
8471Now we simply chug through the formula.
8472
8473@group
8474@smallexample
84751: 19.7392088022 1: 394.78 +/- 19.739 1: 6316.5 +/- 706.21
8476 . . .
8477
8478 2 P 2 ^ * 20 p 1 * 4 p .2 RET 2 ^ *
8479@end smallexample
8480@end group
8481
8482It turns out the @kbd{v u} command will unpack an error form as
8483well as a vector. This saves us some retyping of numbers.
8484
8485@group
8486@smallexample
84873: 6316.5 +/- 706.21 2: 6316.5 +/- 706.21
84882: 6316.5 1: 0.1118
84891: 706.21 .
8490 .
8491
8492 RET v u TAB /
8493@end smallexample
8494@end group
8495
8496@noindent
8497Thus the volume is 6316 cubic centimeters, within about 11 percent.
8498
8499@node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
8500@subsection Types Tutorial Exercise 8
8501
8502@noindent
8503The first answer is pretty simple: @samp{1 / (0 .. 10) = (0.1 .. inf)}.
8504Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
8505close to zero, its reciprocal can get arbitrarily large, so the answer
8506is an interval that effectively means, ``any number greater than 0.1''
8507but with no upper bound.
8508
8509The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
8510
8511Calc normally treats division by zero as an error, so that the formula
8512@w{@samp{1 / 0}} is left unsimplified. Our third problem,
8513@w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
8514is now a member of the interval. So Calc leaves this one unevaluated, too.
8515
8516If you turn on ``infinite'' mode by pressing @kbd{m i}, you will
8517instead get the answer @samp{[0.1 .. inf]}, which includes infinity
8518as a possible value.
8519
8520The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
8521Zero is buried inside the interval, but it's still a possible value.
8522It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
8523will be either greater than @i{0.1}, or less than @i{-0.1}. Thus
8524the interval goes from minus infinity to plus infinity, with a ``hole''
8525in it from @i{-0.1} to @i{0.1}. Calc doesn't have any way to
8526represent this, so it just reports @samp{[-inf .. inf]} as the answer.
8527It may be disappointing to hear ``the answer lies somewhere between
8528minus infinity and plus infinity, inclusive,'' but that's the best
8529that interval arithmetic can do in this case.
8530
8531@node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
8532@subsection Types Tutorial Exercise 9
8533
8534@group
8535@smallexample
85361: [-3 .. 3] 2: [-3 .. 3] 2: [0 .. 9]
8537 . 1: [0 .. 9] 1: [-9 .. 9]
8538 . .
8539
8540 [ 3 n .. 3 ] RET 2 ^ TAB RET *
8541@end smallexample
8542@end group
8543
8544@noindent
8545In the first case the result says, ``if a number is between @i{-3} and
85463, its square is between 0 and 9.'' The second case says, ``the product
8547of two numbers each between @i{-3} and 3 is between @i{-9} and 9.''
8548
8549An interval form is not a number; it is a symbol that can stand for
8550many different numbers. Two identical-looking interval forms can stand
8551for different numbers.
8552
8553The same issue arises when you try to square an error form.
8554
8555@node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
8556@subsection Types Tutorial Exercise 10
8557
8558@noindent
8559Testing the first number, we might arbitrarily choose 17 for @cite{x}.
8560
8561@group
8562@smallexample
85631: 17 mod 811749613 2: 17 mod 811749613 1: 533694123 mod 811749613
8564 . 811749612 .
8565 .
8566
8567 17 M 811749613 RET 811749612 ^
8568@end smallexample
8569@end group
8570
8571@noindent
8572Since 533694123 is (considerably) different from 1, the number 811749613
8573must not be prime.
8574
8575It's awkward to type the number in twice as we did above. There are
8576various ways to avoid this, and algebraic entry is one. In fact, using
8577a vector mapping operation we can perform several tests at once. Let's
8578use this method to test the second number.
8579
8580@group
8581@smallexample
85822: [17, 42, 100000] 1: [1 mod 15485863, 1 mod ... ]
85831: 15485863 .
8584 .
8585
8586 [17 42 100000] 15485863 RET V M ' ($$ mod $)^($-1) RET
8587@end smallexample
8588@end group
8589
8590@noindent
8591The result is three ones (modulo @cite{n}), so it's very probable that
859215485863 is prime. (In fact, this number is the millionth prime.)
8593
8594Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
8595would have been hopelessly inefficient, since they would have calculated
8596the power using full integer arithmetic.
8597
8598Calc has a @kbd{k p} command that does primality testing. For small
8599numbers it does an exact test; for large numbers it uses a variant
8600of the Fermat test we used here. You can use @kbd{k p} repeatedly
8601to prove that a large integer is prime with any desired probability.
8602
8603@node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
8604@subsection Types Tutorial Exercise 11
8605
8606@noindent
8607There are several ways to insert a calculated number into an HMS form.
8608One way to convert a number of seconds to an HMS form is simply to
8609multiply the number by an HMS form representing one second:
8610
8611@group
8612@smallexample
86131: 31415926.5359 2: 31415926.5359 1: 8726@@ 38' 46.5359"
8614 . 1: 0@@ 0' 1" .
8615 .
8616
8617 P 1e7 * 0@@ 0' 1" *
8618
8619@end smallexample
8620@end group
8621@noindent
8622@group
8623@smallexample
86242: 8726@@ 38' 46.5359" 1: 6@@ 6' 2.5359" mod 24@@ 0' 0"
86251: 15@@ 27' 16" mod 24@@ 0' 0" .
8626 .
8627
8628 x time RET +
8629@end smallexample
8630@end group
8631
8632@noindent
8633It will be just after six in the morning.
8634
8635The algebraic @code{hms} function can also be used to build an
8636HMS form:
8637
8638@group
8639@smallexample
86401: hms(0, 0, 10000000. pi) 1: 8726@@ 38' 46.5359"
8641 . .
8642
8643 ' hms(0, 0, 1e7 pi) RET =
8644@end smallexample
8645@end group
8646
8647@noindent
8648The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
8649the actual number 3.14159...
8650
8651@node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
8652@subsection Types Tutorial Exercise 12
8653
8654@noindent
8655As we recall, there are 17 songs of about 2 minutes and 47 seconds
8656each.
8657
8658@group
8659@smallexample
86602: 0@@ 2' 47" 1: [0@@ 3' 7" .. 0@@ 3' 47"]
86611: [0@@ 0' 20" .. 0@@ 1' 0"] .
8662 .
8663
8664 [ 0@@ 20" .. 0@@ 1' ] +
8665
8666@end smallexample
8667@end group
8668@noindent
8669@group
8670@smallexample
86711: [0@@ 52' 59." .. 1@@ 4' 19."]
8672 .
8673
8674 17 *
8675@end smallexample
8676@end group
8677
8678@noindent
8679No matter how long it is, the album will fit nicely on one CD.
8680
8681@node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
8682@subsection Types Tutorial Exercise 13
8683
8684@noindent
8685Type @kbd{' 1 yr RET u c s RET}. The answer is 31557600 seconds.
8686
8687@node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
8688@subsection Types Tutorial Exercise 14
8689
8690@noindent
8691How long will it take for a signal to get from one end of the computer
8692to the other?
8693
8694@group
8695@smallexample
86961: m / c 1: 3.3356 ns
8697 . .
8698
8699 ' 1 m / c RET u c ns RET
8700@end smallexample
8701@end group
8702
8703@noindent
8704(Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
8705
8706@group
8707@smallexample
87081: 3.3356 ns 1: 0.81356 ns / ns 1: 0.81356
87092: 4.1 ns . .
8710 .
8711
8712 ' 4.1 ns RET / u s
8713@end smallexample
8714@end group
8715
8716@noindent
8717Thus a signal could take up to 81 percent of a clock cycle just to
8718go from one place to another inside the computer, assuming the signal
8719could actually attain the full speed of light. Pretty tight!
8720
8721@node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
8722@subsection Types Tutorial Exercise 15
8723
8724@noindent
8725The speed limit is 55 miles per hour on most highways. We want to
8726find the ratio of Sam's speed to the US speed limit.
8727
8728@group
8729@smallexample
87301: 55 mph 2: 55 mph 3: 11 hr mph / yd
8731 . 1: 5 yd / hr .
8732 .
8733
8734 ' 55 mph RET ' 5 yd/hr RET /
8735@end smallexample
8736@end group
8737
8738The @kbd{u s} command cancels out these units to get a plain
8739number. Now we take the logarithm base two to find the final
8740answer, assuming that each successive pill doubles his speed.
8741
8742@group
8743@smallexample
87441: 19360. 2: 19360. 1: 14.24
8745 . 1: 2 .
8746 .
8747
8748 u s 2 B
8749@end smallexample
8750@end group
8751
8752@noindent
8753Thus Sam can take up to 14 pills without a worry.
8754
8755@node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
8756@subsection Algebra Tutorial Exercise 1
8757
8758@noindent
8759@c [fix-ref Declarations]
8760The result @samp{sqrt(x)^2} is simplified back to @cite{x} by the
8761Calculator, but @samp{sqrt(x^2)} is not. (Consider what happens
8762if @w{@cite{x = -4}}.) If @cite{x} is real, this formula could be
8763simplified to @samp{abs(x)}, but for general complex arguments even
8764that is not safe. (@xref{Declarations}, for a way to tell Calc
8765that @cite{x} is known to be real.)
8766
8767@node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
8768@subsection Algebra Tutorial Exercise 2
8769
8770@noindent
8771Suppose our roots are @cite{[a, b, c]}. We want a polynomial which
8772is zero when @cite{x} is any of these values. The trivial polynomial
8773@cite{x-a} is zero when @cite{x=a}, so the product @cite{(x-a)(x-b)(x-c)}
8774will do the job. We can use @kbd{a c x} to write this in a more
8775familiar form.
8776
8777@group
8778@smallexample
87791: 34 x - 24 x^3 1: [1.19023, -1.19023, 0]
8780 . .
8781
8782 r 2 a P x RET
8783
8784@end smallexample
8785@end group
8786@noindent
8787@group
8788@smallexample
87891: [x - 1.19023, x + 1.19023, x] 1: (x - 1.19023) (x + 1.19023) x
8790 . .
8791
8792 V M ' x-$ RET V R *
8793
8794@end smallexample
8795@end group
8796@noindent
8797@group
8798@smallexample
87991: x^3 - 1.41666 x 1: 34 x - 24 x^3
8800 . .
8801
8802 a c x RET 24 n * a x
8803@end smallexample
8804@end group
8805
8806@noindent
8807Sure enough, our answer (multiplied by a suitable constant) is the
8808same as the original polynomial.
8809
8810@node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
8811@subsection Algebra Tutorial Exercise 3
8812
8813@group
8814@smallexample
88151: x sin(pi x) 1: (sin(pi x) - pi x cos(pi x)) / pi^2
8816 . .
8817
8818 ' x sin(pi x) RET m r a i x RET
8819
8820@end smallexample
8821@end group
8822@noindent
8823@group
8824@smallexample
88251: [y, 1]
88262: (sin(pi x) - pi x cos(pi x)) / pi^2
8827 .
8828
8829 ' [y,1] RET TAB
8830
8831@end smallexample
8832@end group
8833@noindent
8834@group
8835@smallexample
88361: [(sin(pi y) - pi y cos(pi y)) / pi^2, (sin(pi) - pi cos(pi)) / pi^2]
8837 .
8838
8839 V M $ RET
8840
8841@end smallexample
8842@end group
8843@noindent
8844@group
8845@smallexample
88461: (sin(pi y) - pi y cos(pi y)) / pi^2 + (pi cos(pi) - sin(pi)) / pi^2
8847 .
8848
8849 V R -
8850
8851@end smallexample
8852@end group
8853@noindent
8854@group
8855@smallexample
88561: (sin(3.14159 y) - 3.14159 y cos(3.14159 y)) / 9.8696 - 0.3183
8857 .
8858
8859 =
8860
8861@end smallexample
8862@end group
8863@noindent
8864@group
8865@smallexample
88661: [0., -0.95493, 0.63662, -1.5915, 1.2732]
8867 .
8868
8869 v x 5 RET TAB V M $ RET
8870@end smallexample
8871@end group
8872
8873@node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
8874@subsection Algebra Tutorial Exercise 4
8875
8876@noindent
8877The hard part is that @kbd{V R +} is no longer sufficient to add up all
8878the contributions from the slices, since the slices have varying
8879coefficients. So first we must come up with a vector of these
8880coefficients. Here's one way:
8881
8882@group
8883@smallexample
88842: -1 2: 3 1: [4, 2, ..., 4]
88851: [1, 2, ..., 9] 1: [-1, 1, ..., -1] .
8886 . .
8887
8888 1 n v x 9 RET V M ^ 3 TAB -
8889
8890@end smallexample
8891@end group
8892@noindent
8893@group
8894@smallexample
88951: [4, 2, ..., 4, 1] 1: [1, 4, 2, ..., 4, 1]
8896 . .
8897
8898 1 | 1 TAB |
8899@end smallexample
8900@end group
8901
8902@noindent
8903Now we compute the function values. Note that for this method we need
8904eleven values, including both endpoints of the desired interval.
8905
8906@group
8907@smallexample
89082: [1, 4, 2, ..., 4, 1]
89091: [1, 1.1, 1.2, ... , 1.8, 1.9, 2.]
8910 .
8911
8912 11 RET 1 RET .1 RET C-u v x
8913
8914@end smallexample
8915@end group
8916@noindent
8917@group
8918@smallexample
89192: [1, 4, 2, ..., 4, 1]
89201: [0., 0.084941, 0.16993, ... ]
8921 .
8922
8923 ' sin(x) ln(x) RET m r p 5 RET V M $ RET
8924@end smallexample
8925@end group
8926
8927@noindent
8928Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
8929same thing.
8930
8931@group
8932@smallexample
89331: 11.22 1: 1.122 1: 0.374
8934 . . .
8935
8936 * .1 * 3 /
8937@end smallexample
8938@end group
8939
8940@noindent
8941Wow! That's even better than the result from the Taylor series method.
8942
8943@node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
8944@subsection Rewrites Tutorial Exercise 1
8945
8946@noindent
8947We'll use Big mode to make the formulas more readable.
8948
8949@group
8950@smallexample
8951 ___
8952 2 + V 2
89531: (2 + sqrt(2)) / (1 + sqrt(2)) 1: --------
8954 . ___
8955 1 + V 2
8956
8957 .
8958
8959 ' (2+sqrt(2)) / (1+sqrt(2)) RET d B
8960@end smallexample
8961@end group
8962
8963@noindent
8964Multiplying by the conjugate helps because @cite{(a+b) (a-b) = a^2 - b^2}.
8965
8966@group
8967@smallexample
8968 ___ ___
89691: (2 + V 2 ) (V 2 - 1)
8970 .
8971
8972 a r a/(b+c) := a*(b-c) / (b^2-c^2) RET
8973
8974@end smallexample
8975@end group
8976@noindent
8977@group
8978@smallexample
8979 ___ ___
89801: 2 + V 2 - 2 1: V 2
8981 . .
8982
8983 a r a*(b+c) := a*b + a*c a s
8984@end smallexample
8985@end group
8986
8987@noindent
8988(We could have used @kbd{a x} instead of a rewrite rule for the
8989second step.)
8990
8991The multiply-by-conjugate rule turns out to be useful in many
8992different circumstances, such as when the denominator involves
8993sines and cosines or the imaginary constant @code{i}.
8994
8995@node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
8996@subsection Rewrites Tutorial Exercise 2
8997
8998@noindent
8999Here is the rule set:
9000
9001@group
9002@smallexample
9003[ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
9004 fib(1, x, y) := x,
9005 fib(n, x, y) := fib(n-1, y, x+y) ]
9006@end smallexample
9007@end group
9008
9009@noindent
9010The first rule turns a one-argument @code{fib} that people like to write
9011into a three-argument @code{fib} that makes computation easier. The
9012second rule converts back from three-argument form once the computation
9013is done. The third rule does the computation itself. It basically
9014says that if @cite{x} and @cite{y} are two consecutive Fibonacci numbers,
9015then @cite{y} and @cite{x+y} are the next (overlapping) pair of Fibonacci
9016numbers.
9017
9018Notice that because the number @cite{n} was ``validated'' by the
9019conditions on the first rule, there is no need to put conditions on
9020the other rules because the rule set would never get that far unless
9021the input were valid. That further speeds computation, since no
9022extra conditions need to be checked at every step.
9023
9024Actually, a user with a nasty sense of humor could enter a bad
9025three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
9026which would get the rules into an infinite loop. One thing that would
9027help keep this from happening by accident would be to use something like
9028@samp{ZzFib} instead of @code{fib} as the name of the three-argument
9029function.
9030
9031@node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
9032@subsection Rewrites Tutorial Exercise 3
9033
9034@noindent
9035He got an infinite loop. First, Calc did as expected and rewrote
9036@w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}. Then it looked for ways to
9037apply the rule again, and found that @samp{f(2, 3, x)} looks like
9038@samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
9039@samp{f(0, 1, f(2, 3, x))}. It then wrapped another @samp{f(0, 1, ...)}
9040around that, and so on, ad infinitum. Joe should have used @kbd{M-1 a r}
9041to make sure the rule applied only once.
9042
9043(Actually, even the first step didn't work as he expected. What Calc
9044really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
9045treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
9046to it. While this may seem odd, it's just as valid a solution as the
9047``obvious'' one. One way to fix this would be to add the condition
9048@samp{:: variable(x)} to the rule, to make sure the thing that matches
9049@samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
9050on the lefthand side, so that the rule matches the actual variable
9051@samp{x} rather than letting @samp{x} stand for something else.)
9052
9053@node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
9054@subsection Rewrites Tutorial Exercise 4
9055
9056@noindent
9057@c @starindex
9058@tindex seq
9059Here is a suitable set of rules to solve the first part of the problem:
9060
9061@group
9062@smallexample
9063[ seq(n, c) := seq(n/2, c+1) :: n%2 = 0,
9064 seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
9065@end smallexample
9066@end group
9067
9068Given the initial formula @samp{seq(6, 0)}, application of these
9069rules produces the following sequence of formulas:
9070
9071@example
9072seq( 3, 1)
9073seq(10, 2)
9074seq( 5, 3)
9075seq(16, 4)
9076seq( 8, 5)
9077seq( 4, 6)
9078seq( 2, 7)
9079seq( 1, 8)
9080@end example
9081
9082@noindent
9083whereupon neither of the rules match, and rewriting stops.
9084
9085We can pretty this up a bit with a couple more rules:
9086
9087@group
9088@smallexample
9089[ seq(n) := seq(n, 0),
9090 seq(1, c) := c,
9091 ... ]
9092@end smallexample
9093@end group
9094
9095@noindent
9096Now, given @samp{seq(6)} as the starting configuration, we get 8
9097as the result.
9098
9099The change to return a vector is quite simple:
9100
9101@group
9102@smallexample
9103[ seq(n) := seq(n, []) :: integer(n) :: n > 0,
9104 seq(1, v) := v | 1,
9105 seq(n, v) := seq(n/2, v | n) :: n%2 = 0,
9106 seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
9107@end smallexample
9108@end group
9109
9110@noindent
9111Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
9112
9113Notice that the @cite{n > 1} guard is no longer necessary on the last
9114rule since the @cite{n = 1} case is now detected by another rule.
9115But a guard has been added to the initial rule to make sure the
9116initial value is suitable before the computation begins.
9117
9118While still a good idea, this guard is not as vitally important as it
9119was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
9120will not get into an infinite loop. Calc will not be able to prove
9121the symbol @samp{x} is either even or odd, so none of the rules will
9122apply and the rewrites will stop right away.
9123
9124@node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
9125@subsection Rewrites Tutorial Exercise 5
9126
9127@noindent
9128@c @starindex
9129@tindex nterms
9130If @cite{x} is the sum @cite{a + b}, then `@t{nterms(}@i{x}@t{)}' must
9131be `@t{nterms(}@i{a}@t{)}' plus `@t{nterms(}@i{b}@t{)}'. If @cite{x}
9132is not a sum, then `@t{nterms(}@i{x}@t{)}' = 1.
9133
9134@group
9135@smallexample
9136[ nterms(a + b) := nterms(a) + nterms(b),
9137 nterms(x) := 1 ]
9138@end smallexample
9139@end group
9140
9141@noindent
9142Here we have taken advantage of the fact that earlier rules always
9143match before later rules; @samp{nterms(x)} will only be tried if we
9144already know that @samp{x} is not a sum.
9145
9146@node Rewrites Answer 6, Rewrites Answer 7, Rewrites Answer 5, Answers to Exercises
9147@subsection Rewrites Tutorial Exercise 6
9148
9149Just put the rule @samp{0^0 := 1} into @code{EvalRules}. For example,
9150before making this definition we have:
9151
9152@group
9153@smallexample
91542: [-2, -1, 0, 1, 2] 1: [1, 1, 0^0, 1, 1]
91551: 0 .
9156 .
9157
9158 v x 5 RET 3 - 0 V M ^
9159@end smallexample
9160@end group
9161
9162@noindent
9163But then:
9164
9165@group
9166@smallexample
91672: [-2, -1, 0, 1, 2] 1: [1, 1, 1, 1, 1]
91681: 0 .
9169 .
9170
9171 U ' 0^0:=1 RET s t EvalRules RET V M ^
9172@end smallexample
9173@end group
9174
9175Perhaps more surprisingly, this rule still works with infinite mode
9176turned on. Calc tries @code{EvalRules} before any built-in rules for
9177a function. This allows you to override the default behavior of any
9178Calc feature: Even though Calc now wants to evaluate @cite{0^0} to
9179@code{nan}, your rule gets there first and evaluates it to 1 instead.
9180
9181Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
9182What happens? (Be sure to remove this rule afterward, or you might get
9183a nasty surprise when you use Calc to balance your checkbook!)
9184
9185@node Rewrites Answer 7, Programming Answer 1, Rewrites Answer 6, Answers to Exercises
9186@subsection Rewrites Tutorial Exercise 7
9187
9188@noindent
9189Here is a rule set that will do the job:
9190
9191@group
9192@smallexample
9193[ a*(b + c) := a*b + a*c,
9194 opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
9195 :: constant(a) :: constant(b),
9196 opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
9197 :: constant(a) :: constant(b),
9198 a O(x^n) := O(x^n) :: constant(a),
9199 x^opt(m) O(x^n) := O(x^(n+m)),
9200 O(x^n) O(x^m) := O(x^(n+m)) ]
9201@end smallexample
9202@end group
9203
9204If we really want the @kbd{+} and @kbd{*} keys to operate naturally
9205on power series, we should put these rules in @code{EvalRules}. For
9206testing purposes, it is better to put them in a different variable,
9207say, @code{O}, first.
9208
9209The first rule just expands products of sums so that the rest of the
9210rules can assume they have an expanded-out polynomial to work with.
9211Note that this rule does not mention @samp{O} at all, so it will
9212apply to any product-of-sum it encounters---this rule may surprise
9213you if you put it into @code{EvalRules}!
9214
9215In the second rule, the sum of two O's is changed to the smaller O.
9216The optional constant coefficients are there mostly so that
9217@samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
9218as well as @samp{O(x^2) + O(x^3)}.
9219
9220The third rule absorbs higher powers of @samp{x} into O's.
9221
9222The fourth rule says that a constant times a negligible quantity
9223is still negligible. (This rule will also match @samp{O(x^3) / 4},
9224with @samp{a = 1/4}.)
9225
9226The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
9227(It is easy to see that if one of these forms is negligible, the other
9228is, too.) Notice the @samp{x^opt(m)} to pick up terms like
9229@w{@samp{x O(x^3)}}. Optional powers will match @samp{x} as @samp{x^1}
9230but not 1 as @samp{x^0}. This turns out to be exactly what we want here.
9231
9232The sixth rule is the corresponding rule for products of two O's.
9233
9234Another way to solve this problem would be to create a new ``data type''
9235that represents truncated power series. We might represent these as
9236function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
9237a vector of coefficients for @cite{x^0}, @cite{x^1}, @cite{x^2}, and so
9238on. Rules would exist for sums and products of such @code{series}
9239objects, and as an optional convenience could also know how to combine a
9240@code{series} object with a normal polynomial. (With this, and with a
9241rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
9242you could still enter power series in exactly the same notation as
9243before.) Operations on such objects would probably be more efficient,
9244although the objects would be a bit harder to read.
9245
9246@c [fix-ref Compositions]
9247Some other symbolic math programs provide a power series data type
9248similar to this. Mathematica, for example, has an object that looks
9249like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
9250@var{nmax}, @var{den}]}, where @var{x0} is the point about which the
9251power series is taken (we've been assuming this was always zero),
9252and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
9253with fractional or negative powers. Also, the @code{PowerSeries}
9254objects have a special display format that makes them look like
9255@samp{2 x^2 + O(x^4)} when they are printed out. (@xref{Compositions},
9256for a way to do this in Calc, although for something as involved as
9257this it would probably be better to write the formatting routine
9258in Lisp.)
9259
9260@node Programming Answer 1, Programming Answer 2, Rewrites Answer 7, Answers to Exercises
9261@subsection Programming Tutorial Exercise 1
9262
9263@noindent
9264Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
9265@kbd{Z F}, and answer the questions. Since this formula contains two
9266variables, the default argument list will be @samp{(t x)}. We want to
9267change this to @samp{(x)} since @cite{t} is really a dummy variable
9268to be used within @code{ninteg}.
9269
9270The exact keystrokes are @kbd{Z F s Si RET RET C-b C-b DEL DEL RET y}.
9271(The @kbd{C-b C-b DEL DEL} are what fix the argument list.)
9272
9273@node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
9274@subsection Programming Tutorial Exercise 2
9275
9276@noindent
9277One way is to move the number to the top of the stack, operate on
9278it, then move it back: @kbd{C-x ( M-TAB n M-TAB M-TAB C-x )}.
9279
9280Another way is to negate the top three stack entries, then negate
9281again the top two stack entries: @kbd{C-x ( M-3 n M-2 n C-x )}.
9282
9283Finally, it turns out that a negative prefix argument causes a
9284command like @kbd{n} to operate on the specified stack entry only,
9285which is just what we want: @kbd{C-x ( M-- 3 n C-x )}.
9286
9287Just for kicks, let's also do it algebraically:
9288@w{@kbd{C-x ( ' -$$$, $$, $ RET C-x )}}.
9289
9290@node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
9291@subsection Programming Tutorial Exercise 3
9292
9293@noindent
9294Each of these functions can be computed using the stack, or using
9295algebraic entry, whichever way you prefer:
9296
9297@noindent
9298Computing @c{$\displaystyle{\sin x \over x}$}
9299@cite{sin(x) / x}:
9300
9301Using the stack: @kbd{C-x ( RET S TAB / C-x )}.
9302
9303Using algebraic entry: @kbd{C-x ( ' sin($)/$ RET C-x )}.
9304
9305@noindent
9306Computing the logarithm:
9307
9308Using the stack: @kbd{C-x ( TAB B C-x )}
9309
9310Using algebraic entry: @kbd{C-x ( ' log($,$$) RET C-x )}.
9311
9312@noindent
9313Computing the vector of integers:
9314
9315Using the stack: @kbd{C-x ( 1 RET 1 C-u v x C-x )}. (Recall that
9316@kbd{C-u v x} takes the vector size, starting value, and increment
9317from the stack.)
9318
9319Alternatively: @kbd{C-x ( ~ v x C-x )}. (The @kbd{~} key pops a
9320number from the stack and uses it as the prefix argument for the
9321next command.)
9322
9323Using algebraic entry: @kbd{C-x ( ' index($) RET C-x )}.
9324
9325@node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
9326@subsection Programming Tutorial Exercise 4
9327
9328@noindent
9329Here's one way: @kbd{C-x ( RET V R + TAB v l / C-x )}.
9330
9331@node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
9332@subsection Programming Tutorial Exercise 5
9333
9334@group
9335@smallexample
93362: 1 1: 1.61803398502 2: 1.61803398502
93371: 20 . 1: 1.61803398875
9338 . .
9339
9340 1 RET 20 Z < & 1 + Z > I H P
9341@end smallexample
9342@end group
9343
9344@noindent
9345This answer is quite accurate.
9346
9347@node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
9348@subsection Programming Tutorial Exercise 6
9349
9350@noindent
9351Here is the matrix:
9352
9353@example
9354[ [ 0, 1 ] * [a, b] = [b, a + b]
9355 [ 1, 1 ] ]
9356@end example
9357
9358@noindent
9359Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @cite{n+1}
9360and @cite{n+2}. Here's one program that does the job:
9361
9362@example
9363C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] RET v u DEL C-x )
9364@end example
9365
9366@noindent
9367This program is quite efficient because Calc knows how to raise a
9368matrix (or other value) to the power @cite{n} in only @c{$\log_2 n$}
9369@cite{log(n,2)}
9370steps. For example, this program can compute the 1000th Fibonacci
9371number (a 209-digit integer!) in about 10 steps; even though the
9372@kbd{Z < ... Z >} solution had much simpler steps, it would have
9373required so many steps that it would not have been practical.
9374
9375@node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
9376@subsection Programming Tutorial Exercise 7
9377
9378@noindent
9379The trick here is to compute the harmonic numbers differently, so that
9380the loop counter itself accumulates the sum of reciprocals. We use
9381a separate variable to hold the integer counter.
9382
9383@group
9384@smallexample
93851: 1 2: 1 1: .
9386 . 1: 4
9387 .
9388
9389 1 t 1 1 RET 4 Z ( t 2 r 1 1 + s 1 & Z )
9390@end smallexample
9391@end group
9392
9393@noindent
9394The body of the loop goes as follows: First save the harmonic sum
9395so far in variable 2. Then delete it from the stack; the for loop
9396itself will take care of remembering it for us. Next, recall the
9397count from variable 1, add one to it, and feed its reciprocal to
9398the for loop to use as the step value. The for loop will increase
9399the ``loop counter'' by that amount and keep going until the
9400loop counter exceeds 4.
9401
9402@group
9403@smallexample
94042: 31 3: 31
94051: 3.99498713092 2: 3.99498713092
9406 . 1: 4.02724519544
9407 .
9408
9409 r 1 r 2 RET 31 & +
9410@end smallexample
9411@end group
9412
9413Thus we find that the 30th harmonic number is 3.99, and the 31st
9414harmonic number is 4.02.
9415
9416@node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
9417@subsection Programming Tutorial Exercise 8
9418
9419@noindent
9420The first step is to compute the derivative @cite{f'(x)} and thus
9421the formula @c{$\displaystyle{x - {f(x) \over f'(x)}}$}
9422@cite{x - f(x)/f'(x)}.
9423
9424(Because this definition is long, it will be repeated in concise form
9425below. You can use @w{@kbd{M-# m}} to load it from there. While you are
9426entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9427keystrokes without executing them. In the following diagrams we'll
9428pretend Calc actually executed the keystrokes as you typed them,
9429just for purposes of illustration.)
9430
9431@group
9432@smallexample
94332: sin(cos(x)) - 0.5 3: 4.5
94341: 4.5 2: sin(cos(x)) - 0.5
9435 . 1: -(sin(x) cos(cos(x)))
9436 .
9437
9438' sin(cos(x))-0.5 RET 4.5 m r C-x ( Z ` TAB RET a d x RET
9439
9440@end smallexample
9441@end group
9442@noindent
9443@group
9444@smallexample
94452: 4.5
94461: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
9447 .
9448
9449 / ' x RET TAB - t 1
9450@end smallexample
9451@end group
9452
9453Now, we enter the loop. We'll use a repeat loop with a 20-repetition
9454limit just in case the method fails to converge for some reason.
9455(Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
9456repetitions are done.)
9457
9458@group
9459@smallexample
94601: 4.5 3: 4.5 2: 4.5
9461 . 2: x + (sin(cos(x)) ... 1: 5.24196456928
9462 1: 4.5 .
9463 .
9464
9465 20 Z < RET r 1 TAB s l x RET
9466@end smallexample
9467@end group
9468
9469This is the new guess for @cite{x}. Now we compare it with the
9470old one to see if we've converged.
9471
9472@group
9473@smallexample
94743: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348
94752: 5.24196 1: 0 . .
94761: 4.5 .
9477 .
9478
9479 RET M-TAB a = Z / Z > Z ' C-x )
9480@end smallexample
9481@end group
9482
9483The loop converges in just a few steps to this value. To check
9484the result, we can simply substitute it back into the equation.
9485
9486@group
9487@smallexample
94882: 5.26345856348
94891: 0.499999999997
9490 .
9491
9492 RET ' sin(cos($)) RET
9493@end smallexample
9494@end group
9495
9496Let's test the new definition again:
9497
9498@group
9499@smallexample
95002: x^2 - 9 1: 3.
95011: 1 .
9502 .
9503
9504 ' x^2-9 RET 1 X
9505@end smallexample
9506@end group
9507
9508Once again, here's the full Newton's Method definition:
9509
9510@group
9511@example
9512C-x ( Z ` TAB RET a d x RET / ' x RET TAB - t 1
9513 20 Z < RET r 1 TAB s l x RET
9514 RET M-TAB a = Z /
9515 Z >
9516 Z '
9517C-x )
9518@end example
9519@end group
9520
9521@c [fix-ref Nesting and Fixed Points]
9522It turns out that Calc has a built-in command for applying a formula
9523repeatedly until it converges to a number. @xref{Nesting and Fixed Points},
9524to see how to use it.
9525
9526@c [fix-ref Root Finding]
9527Also, of course, @kbd{a R} is a built-in command that uses Newton's
9528method (among others) to look for numerical solutions to any equation.
9529@xref{Root Finding}.
9530
9531@node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
9532@subsection Programming Tutorial Exercise 9
9533
9534@noindent
9535The first step is to adjust @cite{z} to be greater than 5. A simple
9536``for'' loop will do the job here. If @cite{z} is less than 5, we
9537reduce the problem using @c{$\psi(z) = \psi(z+1) - 1/z$}
9538@cite{psi(z) = psi(z+1) - 1/z}. We go
9539on to compute @c{$\psi(z+1)$}
9540@cite{psi(z+1)}, and remember to add back a factor of
9541@cite{-1/z} when we're done. This step is repeated until @cite{z > 5}.
9542
9543(Because this definition is long, it will be repeated in concise form
9544below. You can use @w{@kbd{M-# m}} to load it from there. While you are
9545entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9546keystrokes without executing them. In the following diagrams we'll
9547pretend Calc actually executed the keystrokes as you typed them,
9548just for purposes of illustration.)
9549
9550@group
9551@smallexample
95521: 1. 1: 1.
9553 . .
9554
9555 1.0 RET C-x ( Z ` s 1 0 t 2
9556@end smallexample
9557@end group
9558
9559Here, variable 1 holds @cite{z} and variable 2 holds the adjustment
9560factor. If @cite{z < 5}, we use a loop to increase it.
9561
9562(By the way, we started with @samp{1.0} instead of the integer 1 because
9563otherwise the calculation below will try to do exact fractional arithmetic,
9564and will never converge because fractions compare equal only if they
9565are exactly equal, not just equal to within the current precision.)
9566
9567@group
9568@smallexample
95693: 1. 2: 1. 1: 6.
95702: 1. 1: 1 .
95711: 5 .
9572 .
9573
9574 RET 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9575@end smallexample
9576@end group
9577
9578Now we compute the initial part of the sum: @c{$\ln z - {1 \over 2z}$}
9579@cite{ln(z) - 1/2z}
9580minus the adjustment factor.
9581
9582@group
9583@smallexample
95842: 1.79175946923 2: 1.7084261359 1: -0.57490719743
95851: 0.0833333333333 1: 2.28333333333 .
9586 . .
9587
9588 L r 1 2 * & - r 2 -
9589@end smallexample
9590@end group
9591
9592Now we evaluate the series. We'll use another ``for'' loop counting
9593up the value of @cite{2 n}. (Calc does have a summation command,
9594@kbd{a +}, but we'll use loops just to get more practice with them.)
9595
9596@group
9597@smallexample
95983: -0.5749 3: -0.5749 4: -0.5749 2: -0.5749
95992: 2 2: 1:6 3: 1:6 1: 2.3148e-3
96001: 40 1: 2 2: 2 .
9601 . . 1: 36.
9602 .
9603
9604 2 RET 40 Z ( RET k b TAB RET r 1 TAB ^ * /
9605
9606@end smallexample
9607@end group
9608@noindent
9609@group
9610@smallexample
96113: -0.5749 3: -0.5772 2: -0.5772 1: -0.577215664892
96122: -0.5749 2: -0.5772 1: 0 .
96131: 2.3148e-3 1: -0.5749 .
9614 . .
9615
9616 TAB RET M-TAB - RET M-TAB a = Z / 2 Z ) Z ' C-x )
9617@end smallexample
9618@end group
9619
9620This is the value of @c{$-\gamma$}
9621@cite{- gamma}, with a slight bit of roundoff error.
9622To get a full 12 digits, let's use a higher precision:
9623
9624@group
9625@smallexample
96262: -0.577215664892 2: -0.577215664892
96271: 1. 1: -0.577215664901532
9628
9629 1. RET p 16 RET X
9630@end smallexample
9631@end group
9632
9633Here's the complete sequence of keystrokes:
9634
9635@group
9636@example
9637C-x ( Z ` s 1 0 t 2
9638 RET 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9639 L r 1 2 * & - r 2 -
9640 2 RET 40 Z ( RET k b TAB RET r 1 TAB ^ * /
9641 TAB RET M-TAB - RET M-TAB a = Z /
9642 2 Z )
9643 Z '
9644C-x )
9645@end example
9646@end group
9647
9648@node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
9649@subsection Programming Tutorial Exercise 10
9650
9651@noindent
9652Taking the derivative of a term of the form @cite{x^n} will produce
9653a term like @c{$n x^{n-1}$}
9654@cite{n x^(n-1)}. Taking the derivative of a constant
9655produces zero. From this it is easy to see that the @cite{n}th
9656derivative of a polynomial, evaluated at @cite{x = 0}, will equal the
9657coefficient on the @cite{x^n} term times @cite{n!}.
9658
9659(Because this definition is long, it will be repeated in concise form
9660below. You can use @w{@kbd{M-# m}} to load it from there. While you are
9661entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9662keystrokes without executing them. In the following diagrams we'll
9663pretend Calc actually executed the keystrokes as you typed them,
9664just for purposes of illustration.)
9665
9666@group
9667@smallexample
96682: 5 x^4 + (x + 1)^2 3: 5 x^4 + (x + 1)^2
96691: 6 2: 0
9670 . 1: 6
9671 .
9672
9673 ' 5 x^4 + (x+1)^2 RET 6 C-x ( Z ` [ ] t 1 0 TAB
9674@end smallexample
9675@end group
9676
9677@noindent
9678Variable 1 will accumulate the vector of coefficients.
9679
9680@group
9681@smallexample
96822: 0 3: 0 2: 5 x^4 + ...
96831: 5 x^4 + ... 2: 5 x^4 + ... 1: 1
9684 . 1: 1 .
9685 .
9686
9687 Z ( TAB RET 0 s l x RET M-TAB ! / s | 1
9688@end smallexample
9689@end group
9690
9691@noindent
9692Note that @kbd{s | 1} appends the top-of-stack value to the vector
9693in a variable; it is completely analogous to @kbd{s + 1}. We could
9694have written instead, @kbd{r 1 TAB | t 1}.
9695
9696@group
9697@smallexample
96981: 20 x^3 + 2 x + 2 1: 0 1: [1, 2, 1, 0, 5, 0, 0]
9699 . . .
9700
9701 a d x RET 1 Z ) DEL r 1 Z ' C-x )
9702@end smallexample
9703@end group
9704
9705To convert back, a simple method is just to map the coefficients
9706against a table of powers of @cite{x}.
9707
9708@group
9709@smallexample
97102: [1, 2, 1, 0, 5, 0, 0] 2: [1, 2, 1, 0, 5, 0, 0]
97111: 6 1: [0, 1, 2, 3, 4, 5, 6]
9712 . .
9713
9714 6 RET 1 + 0 RET 1 C-u v x
9715
9716@end smallexample
9717@end group
9718@noindent
9719@group
9720@smallexample
97212: [1, 2, 1, 0, 5, 0, 0] 2: 1 + 2 x + x^2 + 5 x^4
97221: [1, x, x^2, x^3, ... ] .
9723 .
9724
9725 ' x RET TAB V M ^ *
9726@end smallexample
9727@end group
9728
9729Once again, here are the whole polynomial to/from vector programs:
9730
9731@group
9732@example
9733C-x ( Z ` [ ] t 1 0 TAB
9734 Z ( TAB RET 0 s l x RET M-TAB ! / s | 1
9735 a d x RET
9736 1 Z ) r 1
9737 Z '
9738C-x )
9739
9740C-x ( 1 + 0 RET 1 C-u v x ' x RET TAB V M ^ * C-x )
9741@end example
9742@end group
9743
9744@node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
9745@subsection Programming Tutorial Exercise 11
9746
9747@noindent
9748First we define a dummy program to go on the @kbd{z s} key. The true
9749@w{@kbd{z s}} key is supposed to take two numbers from the stack and
9750return one number, so @kbd{DEL} as a dummy definition will make
9751sure the stack comes out right.
9752
9753@group
9754@smallexample
97552: 4 1: 4 2: 4
97561: 2 . 1: 2
9757 . .
9758
9759 4 RET 2 C-x ( DEL C-x ) Z K s RET 2
9760@end smallexample
9761@end group
9762
9763The last step replaces the 2 that was eaten during the creation
9764of the dummy @kbd{z s} command. Now we move on to the real
9765definition. The recurrence needs to be rewritten slightly,
9766to the form @cite{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
9767
9768(Because this definition is long, it will be repeated in concise form
9769below. You can use @kbd{M-# m} to load it from there.)
9770
9771@group
9772@smallexample
97732: 4 4: 4 3: 4 2: 4
97741: 2 3: 2 2: 2 1: 2
9775 . 2: 4 1: 0 .
9776 1: 2 .
9777 .
9778
9779 C-x ( M-2 RET a = Z [ DEL DEL 1 Z :
9780
9781@end smallexample
9782@end group
9783@noindent
9784@group
9785@smallexample
97864: 4 2: 4 2: 3 4: 3 4: 3 3: 3
97873: 2 1: 2 1: 2 3: 2 3: 2 2: 2
97882: 2 . . 2: 3 2: 3 1: 3
97891: 0 1: 2 1: 1 .
9790 . . .
9791
9792 RET 0 a = Z [ DEL DEL 0 Z : TAB 1 - TAB M-2 RET 1 - z s
9793@end smallexample
9794@end group
9795
9796@noindent
9797(Note that the value 3 that our dummy @kbd{z s} produces is not correct;
9798it is merely a placeholder that will do just as well for now.)
9799
9800@group
9801@smallexample
98023: 3 4: 3 3: 3 2: 3 1: -6
98032: 3 3: 3 2: 3 1: 9 .
98041: 2 2: 3 1: 3 .
9805 . 1: 2 .
9806 .
9807
9808 M-TAB M-TAB TAB RET M-TAB z s * -
9809
9810@end smallexample
9811@end group
9812@noindent
9813@group
9814@smallexample
98151: -6 2: 4 1: 11 2: 11
9816 . 1: 2 . 1: 11
9817 . .
9818
9819 Z ] Z ] C-x ) Z K s RET DEL 4 RET 2 z s M-RET k s
9820@end smallexample
9821@end group
9822
9823Even though the result that we got during the definition was highly
9824bogus, once the definition is complete the @kbd{z s} command gets
9825the right answers.
9826
9827Here's the full program once again:
9828
9829@group
9830@example
9831C-x ( M-2 RET a =
9832 Z [ DEL DEL 1
9833 Z : RET 0 a =
9834 Z [ DEL DEL 0
9835 Z : TAB 1 - TAB M-2 RET 1 - z s
9836 M-TAB M-TAB TAB RET M-TAB z s * -
9837 Z ]
9838 Z ]
9839C-x )
9840@end example
9841@end group
9842
9843You can read this definition using @kbd{M-# m} (@code{read-kbd-macro})
9844followed by @kbd{Z K s}, without having to make a dummy definition
9845first, because @code{read-kbd-macro} doesn't need to execute the
9846definition as it reads it in. For this reason, @code{M-# m} is often
9847the easiest way to create recursive programs in Calc.
9848
9849@node Programming Answer 12, , Programming Answer 11, Answers to Exercises
9850@subsection Programming Tutorial Exercise 12
9851
9852@noindent
9853This turns out to be a much easier way to solve the problem. Let's
9854denote Stirling numbers as calls of the function @samp{s}.
9855
9856First, we store the rewrite rules corresponding to the definition of
9857Stirling numbers in a convenient variable:
9858
9859@smallexample
9860s e StirlingRules RET
9861[ s(n,n) := 1 :: n >= 0,
9862 s(n,0) := 0 :: n > 0,
9863 s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
9864C-c C-c
9865@end smallexample
9866
9867Now, it's just a matter of applying the rules:
9868
9869@group
9870@smallexample
98712: 4 1: s(4, 2) 1: 11
98721: 2 . .
9873 .
9874
9875 4 RET 2 C-x ( ' s($$,$) RET a r StirlingRules RET C-x )
9876@end smallexample
9877@end group
9878
9879As in the case of the @code{fib} rules, it would be useful to put these
9880rules in @code{EvalRules} and to add a @samp{:: remember} condition to
9881the last rule.
9882
9883@c This ends the table-of-contents kludge from above:
9884@tex
9885\global\let\chapternofonts=\oldchapternofonts
9886@end tex
9887
9888@c [reference]
9889
9890@node Introduction, Data Types, Tutorial, Top
9891@chapter Introduction
9892
9893@noindent
9894This chapter is the beginning of the Calc reference manual.
9895It covers basic concepts such as the stack, algebraic and
9896numeric entry, undo, numeric prefix arguments, etc.
9897
9898@c [when-split]
9899@c (Chapter 2, the Tutorial, has been printed in a separate volume.)
9900
9901@menu
9902* Basic Commands::
9903* Help Commands::
9904* Stack Basics::
9905* Numeric Entry::
9906* Algebraic Entry::
9907* Quick Calculator::
9908* Keypad Mode::
9909* Prefix Arguments::
9910* Undo::
9911* Error Messages::
9912* Multiple Calculators::
9913* Troubleshooting Commands::
9914@end menu
9915
9916@node Basic Commands, Help Commands, Introduction, Introduction
9917@section Basic Commands
9918
9919@noindent
9920@pindex calc
9921@pindex calc-mode
9922@cindex Starting the Calculator
9923@cindex Running the Calculator
9924To start the Calculator in its standard interface, type @kbd{M-x calc}.
9925By default this creates a pair of small windows, @samp{*Calculator*}
9926and @samp{*Calc Trail*}. The former displays the contents of the
9927Calculator stack and is manipulated exclusively through Calc commands.
9928It is possible (though not usually necessary) to create several Calc
9929Mode buffers each of which has an independent stack, undo list, and
9930mode settings. There is exactly one Calc Trail buffer; it records a
9931list of the results of all calculations that have been done. The
9932Calc Trail buffer uses a variant of Calc Mode, so Calculator commands
9933still work when the trail buffer's window is selected. It is possible
9934to turn the trail window off, but the @samp{*Calc Trail*} buffer itself
9935still exists and is updated silently. @xref{Trail Commands}.@refill
9936
9937@kindex M-# c
9938@kindex M-# M-#
9939@c @mindex @null
9940@kindex M-# #
9941In most installations, the @kbd{M-# c} key sequence is a more
9942convenient way to start the Calculator. Also, @kbd{M-# M-#} and
9943@kbd{M-# #} are synonyms for @kbd{M-# c} unless you last used Calc
9944in its ``keypad'' mode.
9945
9946@kindex x
9947@kindex M-x
9948@pindex calc-execute-extended-command
9949Most Calc commands use one or two keystrokes. Lower- and upper-case
9950letters are distinct. Commands may also be entered in full @kbd{M-x} form;
9951for some commands this is the only form. As a convenience, the @kbd{x}
9952key (@code{calc-execute-extended-command})
9953is like @kbd{M-x} except that it enters the initial string @samp{calc-}
9954for you. For example, the following key sequences are equivalent:
9955@kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.@refill
9956
9957@cindex Extensions module
9958@cindex @file{calc-ext} module
9959The Calculator exists in many parts. When you type @kbd{M-# c}, the
9960Emacs ``auto-load'' mechanism will bring in only the first part, which
9961contains the basic arithmetic functions. The other parts will be
9962auto-loaded the first time you use the more advanced commands like trig
9963functions or matrix operations. This is done to improve the response time
9964of the Calculator in the common case when all you need to do is a
9965little arithmetic. If for some reason the Calculator fails to load an
9966extension module automatically, you can force it to load all the
9967extensions by using the @kbd{M-# L} (@code{calc-load-everything})
9968command. @xref{Mode Settings}.@refill
9969
9970If you type @kbd{M-x calc} or @kbd{M-# c} with any numeric prefix argument,
9971the Calculator is loaded if necessary, but it is not actually started.
9972If the argument is positive, the @file{calc-ext} extensions are also
9973loaded if necessary. User-written Lisp code that wishes to make use
9974of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
9975to auto-load the Calculator.@refill
9976
9977@kindex M-# b
9978@pindex full-calc
9979If you type @kbd{M-# b}, then next time you use @kbd{M-# c} you
9980will get a Calculator that uses the full height of the Emacs screen.
9981When full-screen mode is on, @kbd{M-# c} runs the @code{full-calc}
9982command instead of @code{calc}. From the Unix shell you can type
9983@samp{emacs -f full-calc} to start a new Emacs specifically for use
9984as a calculator. When Calc is started from the Emacs command line
9985like this, Calc's normal ``quit'' commands actually quit Emacs itself.
9986
9987@kindex M-# o
9988@pindex calc-other-window
9989The @kbd{M-# o} command is like @kbd{M-# c} except that the Calc
9990window is not actually selected. If you are already in the Calc
9991window, @kbd{M-# o} switches you out of it. (The regular Emacs
9992@kbd{C-x o} command would also work for this, but it has a
9993tendency to drop you into the Calc Trail window instead, which
9994@kbd{M-# o} takes care not to do.)
9995
9996@c @mindex M-# q
9997For one quick calculation, you can type @kbd{M-# q} (@code{quick-calc})
9998which prompts you for a formula (like @samp{2+3/4}). The result is
9999displayed at the bottom of the Emacs screen without ever creating
10000any special Calculator windows. @xref{Quick Calculator}.
10001
10002@c @mindex M-# k
10003Finally, if you are using the X window system you may want to try
10004@kbd{M-# k} (@code{calc-keypad}) which runs Calc with a
10005``calculator keypad'' picture as well as a stack display. Click on
10006the keys with the mouse to operate the calculator. @xref{Keypad Mode}.
10007
10008@kindex q
10009@pindex calc-quit
10010@cindex Quitting the Calculator
10011@cindex Exiting the Calculator
10012The @kbd{q} key (@code{calc-quit}) exits Calc Mode and closes the
10013Calculator's window(s). It does not delete the Calculator buffers.
10014If you type @kbd{M-x calc} again, the Calculator will reappear with the
10015contents of the stack intact. Typing @kbd{M-# c} or @kbd{M-# M-#}
10016again from inside the Calculator buffer is equivalent to executing
10017@code{calc-quit}; you can think of @kbd{M-# M-#} as toggling the
10018Calculator on and off.@refill
10019
10020@kindex M-# x
10021The @kbd{M-# x} command also turns the Calculator off, no matter which
10022user interface (standard, Keypad, or Embedded) is currently active.
10023It also cancels @code{calc-edit} mode if used from there.
10024
10025@kindex d SPC
10026@pindex calc-refresh
10027@cindex Refreshing a garbled display
10028@cindex Garbled displays, refreshing
10029The @kbd{d SPC} key sequence (@code{calc-refresh}) redraws the contents
10030of the Calculator buffer from memory. Use this if the contents of the
10031buffer have been damaged somehow.
10032
10033@c @mindex o
10034The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
10035``home'' position at the bottom of the Calculator buffer.
10036
10037@kindex <
10038@kindex >
10039@pindex calc-scroll-left
10040@pindex calc-scroll-right
10041@cindex Horizontal scrolling
10042@cindex Scrolling
10043@cindex Wide text, scrolling
10044The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
10045@code{calc-scroll-right}. These are just like the normal horizontal
10046scrolling commands except that they scroll one half-screen at a time by
10047default. (Calc formats its output to fit within the bounds of the
10048window whenever it can.)@refill
10049
10050@kindex @{
10051@kindex @}
10052@pindex calc-scroll-down
10053@pindex calc-scroll-up
10054@cindex Vertical scrolling
10055The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
10056and @code{calc-scroll-up}. They scroll up or down by one-half the
10057height of the Calc window.@refill
10058
10059@kindex M-# 0
10060@pindex calc-reset
10061The @kbd{M-# 0} command (@code{calc-reset}; that's @kbd{M-#} followed
10062by a zero) resets the Calculator to its default state. This clears
10063the stack, resets all the modes, clears the caches (@pxref{Caches}),
10064and so on. (It does @emph{not} erase the values of any variables.)
10065With a numeric prefix argument, @kbd{M-# 0} preserves the contents
10066of the stack but resets everything else.
10067
10068@pindex calc-version
10069The @kbd{M-x calc-version} command displays the current version number
10070of Calc and the name of the person who installed it on your system.
10071(This information is also present in the @samp{*Calc Trail*} buffer,
10072and in the output of the @kbd{h h} command.)
10073
10074@node Help Commands, Stack Basics, Basic Commands, Introduction
10075@section Help Commands
10076
10077@noindent
10078@cindex Help commands
10079@kindex ?
10080@pindex calc-help
10081The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
10082Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs'
10083@key{ESC} and @kbd{C-x} prefixes. You can type
10084@kbd{?} after a prefix to see a list of commands beginning with that
10085prefix. (If the message includes @samp{[MORE]}, press @kbd{?} again
10086to see additional commands for that prefix.)
10087
10088@kindex h h
10089@pindex calc-full-help
10090The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
10091responses at once. When printed, this makes a nice, compact (three pages)
10092summary of Calc keystrokes.
10093
10094In general, the @kbd{h} key prefix introduces various commands that
10095provide help within Calc. Many of the @kbd{h} key functions are
10096Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
10097
10098@kindex h i
10099@kindex M-# i
10100@kindex i
10101@pindex calc-info
10102The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
10103to read this manual on-line. This is basically the same as typing
10104@kbd{C-h i} (the regular way to run the Info system), then, if Info
10105is not already in the Calc manual, selecting the beginning of the
10106manual. The @kbd{M-# i} command is another way to read the Calc
10107manual; it is different from @kbd{h i} in that it works any time,
10108not just inside Calc. The plain @kbd{i} key is also equivalent to
10109@kbd{h i}, though this key is obsolete and may be replaced with a
10110different command in a future version of Calc.
10111
10112@kindex h t
10113@kindex M-# t
10114@pindex calc-tutorial
10115The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
10116the Tutorial section of the Calc manual. It is like @kbd{h i},
10117except that it selects the starting node of the tutorial rather
10118than the beginning of the whole manual. (It actually selects the
10119node ``Interactive Tutorial'' which tells a few things about
10120using the Info system before going on to the actual tutorial.)
10121The @kbd{M-# t} key is equivalent to @kbd{h t} (but it works at
10122all times).
10123
10124@kindex h s
10125@kindex M-# s
10126@pindex calc-info-summary
10127The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
10128on the Summary node of the Calc manual. @xref{Summary}. The @kbd{M-# s}
10129key is equivalent to @kbd{h s}.
10130
10131@kindex h k
10132@pindex calc-describe-key
10133The @kbd{h k} (@code{calc-describe-key}) command looks up a key
10134sequence in the Calc manual. For example, @kbd{h k H a S} looks
10135up the documentation on the @kbd{H a S} (@code{calc-solve-for})
10136command. This works by looking up the textual description of
10137the key(s) in the Key Index of the manual, then jumping to the
10138node indicated by the index.
10139
10140Most Calc commands do not have traditional Emacs documentation
10141strings, since the @kbd{h k} command is both more convenient and
10142more instructive. This means the regular Emacs @kbd{C-h k}
10143(@code{describe-key}) command will not be useful for Calc keystrokes.
10144
10145@kindex h c
10146@pindex calc-describe-key-briefly
10147The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
10148key sequence and displays a brief one-line description of it at
10149the bottom of the screen. It looks for the key sequence in the
10150Summary node of the Calc manual; if it doesn't find the sequence
10151there, it acts just like its regular Emacs counterpart @kbd{C-h c}
10152(@code{describe-key-briefly}). For example, @kbd{h c H a S}
10153gives the description:
10154
10155@smallexample
10156H a S runs calc-solve-for: a `H a S' v => fsolve(a,v) (?=notes)
10157@end smallexample
10158
10159@noindent
10160which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
10161takes a value @cite{a} from the stack, prompts for a value @cite{v},
10162then applies the algebraic function @code{fsolve} to these values.
10163The @samp{?=notes} message means you can now type @kbd{?} to see
10164additional notes from the summary that apply to this command.
10165
10166@kindex h f
10167@pindex calc-describe-function
10168The @kbd{h f} (@code{calc-describe-function}) command looks up an
10169algebraic function or a command name in the Calc manual. The
10170prompt initially contains @samp{calcFunc-}; follow this with an
10171algebraic function name to look up that function in the Function
10172Index. Or, backspace and enter a command name beginning with
10173@samp{calc-} to look it up in the Command Index. This command
10174will also look up operator symbols that can appear in algebraic
10175formulas, like @samp{%} and @samp{=>}.
10176
10177@kindex h v
10178@pindex calc-describe-variable
10179The @kbd{h v} (@code{calc-describe-variable}) command looks up a
10180variable in the Calc manual. The prompt initially contains the
10181@samp{var-} prefix; just add a variable name like @code{pi} or
10182@code{PlotRejects}.
10183
10184@kindex h b
10185@pindex describe-bindings
10186The @kbd{h b} (@code{calc-describe-bindings}) command is just like
10187@kbd{C-h b}, except that only local (Calc-related) key bindings are
10188listed.
10189
10190@kindex h n
10191The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
10192the ``news'' or change history of Calc. This is kept in the file
10193@file{README}, which Calc looks for in the same directory as the Calc
10194source files.
10195
10196@kindex h C-c
10197@kindex h C-d
10198@kindex h C-w
10199The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
10200distribution, and warranty information about Calc. These work by
10201pulling up the appropriate parts of the ``Copying'' or ``Reporting
10202Bugs'' sections of the manual.
10203
10204@node Stack Basics, Numeric Entry, Help Commands, Introduction
10205@section Stack Basics
10206
10207@noindent
10208@cindex Stack basics
10209@c [fix-tut RPN Calculations and the Stack]
10210Calc uses RPN notation. If you are not familar with RPN, @pxref{RPN
10211Tutorial}.
10212
10213To add the numbers 1 and 2 in Calc you would type the keys:
10214@kbd{1 @key{RET} 2 +}.
10215(@key{RET} corresponds to the @key{ENTER} key on most calculators.)
10216The first three keystrokes ``push'' the numbers 1 and 2 onto the stack. The
10217@kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
10218and pushes the result (3) back onto the stack. This number is ready for
10219further calculations: @kbd{5 -} pushes 5 onto the stack, then pops the
102203 and 5, subtracts them, and pushes the result (@i{-2}).@refill
10221
10222Note that the ``top'' of the stack actually appears at the @emph{bottom}
10223of the buffer. A line containing a single @samp{.} character signifies
10224the end of the buffer; Calculator commands operate on the number(s)
10225directly above this line. The @kbd{d t} (@code{calc-truncate-stack})
10226command allows you to move the @samp{.} marker up and down in the stack;
10227@pxref{Truncating the Stack}.
10228
10229@kindex d l
10230@pindex calc-line-numbering
10231Stack elements are numbered consecutively, with number 1 being the top of
10232the stack. These line numbers are ordinarily displayed on the lefthand side
10233of the window. The @kbd{d l} (@code{calc-line-numbering}) command controls
10234whether these numbers appear. (Line numbers may be turned off since they
10235slow the Calculator down a bit and also clutter the display.)
10236
10237@kindex o
10238@pindex calc-realign
10239The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
10240the cursor to its top-of-stack ``home'' position. It also undoes any
10241horizontal scrolling in the window. If you give it a numeric prefix
10242argument, it instead moves the cursor to the specified stack element.
10243
10244The @key{RET} (or equivalent @key{SPC}) key is only required to separate
10245two consecutive numbers.
10246(After all, if you typed @kbd{1 2} by themselves the Calculator
10247would enter the number 12.) If you press @kbd{RET} or @kbd{SPC} @emph{not}
10248right after typing a number, the key duplicates the number on the top of
10249the stack. @kbd{@key{RET} *} is thus a handy way to square a number.@refill
10250
10251The @key{DEL} key pops and throws away the top number on the stack.
10252The @key{TAB} key swaps the top two objects on the stack.
10253@xref{Stack and Trail}, for descriptions of these and other stack-related
10254commands.@refill
10255
10256@node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
10257@section Numeric Entry
10258
10259@noindent
10260@kindex 0-9
10261@kindex .
10262@kindex e
10263@cindex Numeric entry
10264@cindex Entering numbers
10265Pressing a digit or other numeric key begins numeric entry using the
10266minibuffer. The number is pushed on the stack when you press the @key{RET}
10267or @key{SPC} keys. If you press any other non-numeric key, the number is
10268pushed onto the stack and the appropriate operation is performed. If
10269you press a numeric key which is not valid, the key is ignored.
10270
10271@cindex Minus signs
10272@cindex Negative numbers, entering
10273@kindex _
10274There are three different concepts corresponding to the word ``minus,''
10275typified by @cite{a-b} (subtraction), @cite{-x}
10276(change-sign), and @cite{-5} (negative number). Calc uses three
10277different keys for these operations, respectively:
10278@kbd{-}, @kbd{n}, and @kbd{_} (the underscore). The @kbd{-} key subtracts
10279the two numbers on the top of the stack. The @kbd{n} key changes the sign
10280of the number on the top of the stack or the number currently being entered.
10281The @kbd{_} key begins entry of a negative number or changes the sign of
10282the number currently being entered. The following sequences all enter the
10283number @i{-5} onto the stack: @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
10284@kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.@refill
10285
10286Some other keys are active during numeric entry, such as @kbd{#} for
10287non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
10288These notations are described later in this manual with the corresponding
10289data types. @xref{Data Types}.
10290
10291During numeric entry, the only editing key available is @kbd{DEL}.
10292
10293@node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
10294@section Algebraic Entry
10295
10296@noindent
10297@kindex '
10298@pindex calc-algebraic-entry
10299@cindex Algebraic notation
10300@cindex Formulas, entering
10301Calculations can also be entered in algebraic form. This is accomplished
10302by typing the apostrophe key, @kbd{'}, followed by the expression in
10303standard format: @kbd{@key{'} 2+3*4 @key{RET}} computes
10304@c{$2+(3\times4) = 14$}
10305@cite{2+(3*4) = 14} and pushes that on the stack. If you wish you can
10306ignore the RPN aspect of Calc altogether and simply enter algebraic
10307expressions in this way. You may want to use @key{DEL} every so often to
10308clear previous results off the stack.@refill
10309
10310You can press the apostrophe key during normal numeric entry to switch
10311the half-entered number into algebraic entry mode. One reason to do this
10312would be to use the full Emacs cursor motion and editing keys, which are
10313available during algebraic entry but not during numeric entry.
10314
10315In the same vein, during either numeric or algebraic entry you can
10316press @kbd{`} (backquote) to switch to @code{calc-edit} mode, where
10317you complete your half-finished entry in a separate buffer.
10318@xref{Editing Stack Entries}.
10319
10320@kindex m a
10321@pindex calc-algebraic-mode
10322@cindex Algebraic mode
10323If you prefer algebraic entry, you can use the command @kbd{m a}
10324(@code{calc-algebraic-mode}) to set Algebraic mode. In this mode,
10325digits and other keys that would normally start numeric entry instead
10326start full algebraic entry; as long as your formula begins with a digit
10327you can omit the apostrophe. Open parentheses and square brackets also
10328begin algebraic entry. You can still do RPN calculations in this mode,
10329but you will have to press @key{RET} to terminate every number:
10330@kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
10331thing as @kbd{2*3+4 @key{RET}}.@refill
10332
10333@cindex Incomplete algebraic mode
10334If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
10335command, it enables Incomplete Algebraic mode; this is like regular
10336Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
10337only. Numeric keys still begin a numeric entry in this mode.
10338
10339@kindex m t
10340@pindex calc-total-algebraic-mode
10341@cindex Total algebraic mode
10342The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
10343stronger algebraic-entry mode, in which @emph{all} regular letter and
10344punctuation keys begin algebraic entry. Use this if you prefer typing
10345@w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
10346@kbd{a f}, and so on. To type regular Calc commands when you are in
10347``total'' algebraic mode, hold down the @key{META} key. Thus @kbd{M-q}
10348is the command to quit Calc, @kbd{M-p} sets the precision, and
10349@kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns total algebraic
10350mode back off again. Meta keys also terminate algebraic entry, so
10351that @kbd{2+3 M-S} is equivalent to @kbd{2+3 RET M-S}. The symbol
10352@samp{Alg*} will appear in the mode line whenever you are in this mode.
10353
10354Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
10355algebraic formula. You can then use the normal Emacs editing keys to
10356modify this formula to your liking before pressing @key{RET}.
10357
10358@kindex $
10359@cindex Formulas, referring to stack
10360Within a formula entered from the keyboard, the symbol @kbd{$}
10361represents the number on the top of the stack. If an entered formula
10362contains any @kbd{$} characters, the Calculator replaces the top of
10363stack with that formula rather than simply pushing the formula onto the
10364stack. Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
10365@key{RET}} replaces it with 6. Note that the @kbd{$} key always
10366initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
10367first character in the new formula.@refill
10368
10369Higher stack elements can be accessed from an entered formula with the
10370symbols @kbd{$$}, @kbd{$$$}, and so on. The number of stack elements
10371removed (to be replaced by the entered values) equals the number of dollar
10372signs in the longest such symbol in the formula. For example, @samp{$$+$$$}
10373adds the second and third stack elements, replacing the top three elements
10374with the answer. (All information about the top stack element is thus lost
10375since no single @samp{$} appears in this formula.)@refill
10376
10377A slightly different way to refer to stack elements is with a dollar
10378sign followed by a number: @samp{$1}, @samp{$2}, and so on are much
10379like @samp{$}, @samp{$$}, etc., except that stack entries referred
10380to numerically are not replaced by the algebraic entry. That is, while
10381@samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
10382on the stack and pushes an additional 6.
10383
10384If a sequence of formulas are entered separated by commas, each formula
10385is pushed onto the stack in turn. For example, @samp{1,2,3} pushes
10386those three numbers onto the stack (leaving the 3 at the top), and
10387@samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6. Also,
10388@samp{$,$$} exchanges the top two elements of the stack, just like the
10389@key{TAB} key.
10390
10391You can finish an algebraic entry with @kbd{M-=} or @kbd{M-RET} instead
10392of @key{RET}. This uses @kbd{=} to evaluate the variables in each
10393formula that goes onto the stack. (Thus @kbd{' pi @key{RET}} pushes
10394the variable @samp{pi}, but @kbd{' pi M-RET} pushes 3.1415.)
10395
10396If you finish your algebraic entry by pressing @kbd{LFD} (or @kbd{C-j})
10397instead of @key{RET}, Calc disables the default simplifications
10398(as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
10399is being pushed on the stack. Thus @kbd{' 1+2 @key{RET}} pushes 3
10400on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @cite{1+2};
10401you might then press @kbd{=} when it is time to evaluate this formula.
10402
10403@node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
10404@section ``Quick Calculator'' Mode
10405
10406@noindent
10407@kindex M-# q
10408@pindex quick-calc
10409@cindex Quick Calculator
10410There is another way to invoke the Calculator if all you need to do
10411is make one or two quick calculations. Type @kbd{M-# q} (or
10412@kbd{M-x quick-calc}), then type any formula as an algebraic entry.
10413The Calculator will compute the result and display it in the echo
10414area, without ever actually putting up a Calc window.
10415
10416You can use the @kbd{$} character in a Quick Calculator formula to
10417refer to the previous Quick Calculator result. Older results are
10418not retained; the Quick Calculator has no effect on the full
10419Calculator's stack or trail. If you compute a result and then
10420forget what it was, just run @code{M-# q} again and enter
10421@samp{$} as the formula.
10422
10423If this is the first time you have used the Calculator in this Emacs
10424session, the @kbd{M-# q} command will create the @code{*Calculator*}
10425buffer and perform all the usual initializations; it simply will
10426refrain from putting that buffer up in a new window. The Quick
10427Calculator refers to the @code{*Calculator*} buffer for all mode
10428settings. Thus, for example, to set the precision that the Quick
10429Calculator uses, simply run the full Calculator momentarily and use
10430the regular @kbd{p} command.
10431
10432If you use @code{M-# q} from inside the Calculator buffer, the
10433effect is the same as pressing the apostrophe key (algebraic entry).
10434
10435The result of a Quick calculation is placed in the Emacs ``kill ring''
10436as well as being displayed. A subsequent @kbd{C-y} command will
10437yank the result into the editing buffer. You can also use this
10438to yank the result into the next @kbd{M-# q} input line as a more
10439explicit alternative to @kbd{$} notation, or to yank the result
10440into the Calculator stack after typing @kbd{M-# c}.
10441
10442If you finish your formula by typing @key{LFD} (or @kbd{C-j}) instead
10443of @key{RET}, the result is inserted immediately into the current
10444buffer rather than going into the kill ring.
10445
10446Quick Calculator results are actually evaluated as if by the @kbd{=}
10447key (which replaces variable names by their stored values, if any).
10448If the formula you enter is an assignment to a variable using the
10449@samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
10450then the result of the evaluation is stored in that Calc variable.
10451@xref{Store and Recall}.
10452
10453If the result is an integer and the current display radix is decimal,
10454the number will also be displayed in hex and octal formats. If the
10455integer is in the range from 1 to 126, it will also be displayed as
10456an ASCII character.
10457
10458For example, the quoted character @samp{"x"} produces the vector
10459result @samp{[120]} (because 120 is the ASCII code of the lower-case
10460`x'; @pxref{Strings}). Since this is a vector, not an integer, it
10461is displayed only according to the current mode settings. But
10462running Quick Calc again and entering @samp{120} will produce the
10463result @samp{120 (16#78, 8#170, x)} which shows the number in its
10464decimal, hexadecimal, octal, and ASCII forms.
10465
10466Please note that the Quick Calculator is not any faster at loading
10467or computing the answer than the full Calculator; the name ``quick''
10468merely refers to the fact that it's much less hassle to use for
10469small calculations.
10470
10471@node Prefix Arguments, Undo, Quick Calculator, Introduction
10472@section Numeric Prefix Arguments
10473
10474@noindent
10475Many Calculator commands use numeric prefix arguments. Some, such as
10476@kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
10477the prefix argument or use a default if you don't use a prefix.
10478Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
10479and prompt for a number if you don't give one as a prefix.@refill
10480
10481As a rule, stack-manipulation commands accept a numeric prefix argument
10482which is interpreted as an index into the stack. A positive argument
10483operates on the top @var{n} stack entries; a negative argument operates
10484on the @var{n}th stack entry in isolation; and a zero argument operates
10485on the entire stack.
10486
10487Most commands that perform computations (such as the arithmetic and
10488scientific functions) accept a numeric prefix argument that allows the
10489operation to be applied across many stack elements. For unary operations
10490(that is, functions of one argument like absolute value or complex
10491conjugate), a positive prefix argument applies that function to the top
10492@var{n} stack entries simultaneously, and a negative argument applies it
10493to the @var{n}th stack entry only. For binary operations (functions of
10494two arguments like addition, GCD, and vector concatenation), a positive
10495prefix argument ``reduces'' the function across the top @var{n}
10496stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
10497@pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
10498@var{n} stack elements with the top stack element as a second argument
10499(for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
10500This feature is not available for operations which use the numeric prefix
10501argument for some other purpose.
10502
10503Numeric prefixes are specified the same way as always in Emacs: Press
10504a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
10505or press @kbd{C-u} followed by digits. Some commands treat plain
10506@kbd{C-u} (without any actual digits) specially.@refill
10507
10508@kindex ~
10509@pindex calc-num-prefix
10510You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
10511top of the stack and enter it as the numeric prefix for the next command.
10512For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
10513(silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
10514to the fourth power and set the precision to that value.@refill
10515
10516Conversely, if you have typed a numeric prefix argument the @kbd{~} key
10517pushes it onto the stack in the form of an integer.
10518
10519@node Undo, Error Messages, Prefix Arguments, Introduction
10520@section Undoing Mistakes
10521
10522@noindent
10523@kindex U
10524@kindex C-_
10525@pindex calc-undo
10526@cindex Mistakes, undoing
10527@cindex Undoing mistakes
10528@cindex Errors, undoing
10529The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
10530If that operation added or dropped objects from the stack, those objects
10531are removed or restored. If it was a ``store'' operation, you are
10532queried whether or not to restore the variable to its original value.
10533The @kbd{U} key may be pressed any number of times to undo successively
10534farther back in time; with a numeric prefix argument it undoes a
10535specified number of operations. The undo history is cleared only by the
10536@kbd{q} (@code{calc-quit}) command. (Recall that @kbd{M-# c} is
10537synonymous with @code{calc-quit} while inside the Calculator; this
10538also clears the undo history.)
10539
10540Currently the mode-setting commands (like @code{calc-precision}) are not
10541undoable. You can undo past a point where you changed a mode, but you
10542will need to reset the mode yourself.
10543
10544@kindex D
10545@pindex calc-redo
10546@cindex Redoing after an Undo
10547The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
10548mistakenly undone. Pressing @kbd{U} with a negative prefix argument is
10549equivalent to executing @code{calc-redo}. You can redo any number of
10550times, up to the number of recent consecutive undo commands. Redo
10551information is cleared whenever you give any command that adds new undo
10552information, i.e., if you undo, then enter a number on the stack or make
10553any other change, then it will be too late to redo.
10554
10555@kindex M-RET
10556@pindex calc-last-args
10557@cindex Last-arguments feature
10558@cindex Arguments, restoring
10559The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
10560it restores the arguments of the most recent command onto the stack;
10561however, it does not remove the result of that command. Given a numeric
10562prefix argument, this command applies to the @cite{n}th most recent
10563command which removed items from the stack; it pushes those items back
10564onto the stack.
10565
10566The @kbd{K} (@code{calc-keep-args}) command provides a related function
10567to @kbd{M-@key{RET}}. @xref{Stack and Trail}.
10568
10569It is also possible to recall previous results or inputs using the trail.
10570@xref{Trail Commands}.
10571
10572The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
10573
10574@node Error Messages, Multiple Calculators, Undo, Introduction
10575@section Error Messages
10576
10577@noindent
10578@kindex w
10579@pindex calc-why
10580@cindex Errors, messages
10581@cindex Why did an error occur?
10582Many situations that would produce an error message in other calculators
10583simply create unsimplified formulas in the Emacs Calculator. For example,
10584@kbd{1 @key{RET} 0 /} pushes the formula @cite{1 / 0}; @w{@kbd{0 L}} pushes
10585the formula @samp{ln(0)}. Floating-point overflow and underflow are also
10586reasons for this to happen.
10587
10588When a function call must be left in symbolic form, Calc usually
10589produces a message explaining why. Messages that are probably
10590surprising or indicative of user errors are displayed automatically.
10591Other messages are simply kept in Calc's memory and are displayed only
10592if you type @kbd{w} (@code{calc-why}). You can also press @kbd{w} if
10593the same computation results in several messages. (The first message
10594will end with @samp{[w=more]} in this case.)
10595
10596@kindex d w
10597@pindex calc-auto-why
10598The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
10599are displayed automatically. (Calc effectively presses @kbd{w} for you
10600after your computation finishes.) By default, this occurs only for
10601``important'' messages. The other possible modes are to report
10602@emph{all} messages automatically, or to report none automatically (so
10603that you must always press @kbd{w} yourself to see the messages).
10604
10605@node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
10606@section Multiple Calculators
10607
10608@noindent
10609@pindex another-calc
10610It is possible to have any number of Calc Mode buffers at once.
10611Usually this is done by executing @kbd{M-x another-calc}, which
10612is similar to @kbd{M-# c} except that if a @samp{*Calculator*}
10613buffer already exists, a new, independent one with a name of the
10614form @samp{*Calculator*<@var{n}>} is created. You can also use the
10615command @code{calc-mode} to put any buffer into Calculator mode, but
10616this would ordinarily never be done.
10617
10618The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
10619it only closes its window. Use @kbd{M-x kill-buffer} to destroy a
10620Calculator buffer.
10621
10622Each Calculator buffer keeps its own stack, undo list, and mode settings
10623such as precision, angular mode, and display formats. In Emacs terms,
10624variables such as @code{calc-stack} are buffer-local variables. The
10625global default values of these variables are used only when a new
10626Calculator buffer is created. The @code{calc-quit} command saves
10627the stack and mode settings of the buffer being quit as the new defaults.
10628
10629There is only one trail buffer, @samp{*Calc Trail*}, used by all
10630Calculator buffers.
10631
10632@node Troubleshooting Commands, , Multiple Calculators, Introduction
10633@section Troubleshooting Commands
10634
10635@noindent
10636This section describes commands you can use in case a computation
10637incorrectly fails or gives the wrong answer.
10638
10639@xref{Reporting Bugs}, if you find a problem that appears to be due
10640to a bug or deficiency in Calc.
10641
10642@menu
10643* Autoloading Problems::
10644* Recursion Depth::
10645* Caches::
10646* Debugging Calc::
10647@end menu
10648
10649@node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
10650@subsection Autoloading Problems
10651
10652@noindent
10653The Calc program is split into many component files; components are
10654loaded automatically as you use various commands that require them.
10655Occasionally Calc may lose track of when a certain component is
10656necessary; typically this means you will type a command and it won't
10657work because some function you've never heard of was undefined.
10658
10659@kindex M-# L
10660@pindex calc-load-everything
10661If this happens, the easiest workaround is to type @kbd{M-# L}
10662(@code{calc-load-everything}) to force all the parts of Calc to be
10663loaded right away. This will cause Emacs to take up a lot more
10664memory than it would otherwise, but it's guaranteed to fix the problem.
10665
10666If you seem to run into this problem no matter what you do, or if
10667even the @kbd{M-# L} command crashes, Calc may have been improperly
10668installed. @xref{Installation}, for details of the installation
10669process.
10670
10671@node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
10672@subsection Recursion Depth
10673
10674@noindent
10675@kindex M
10676@kindex I M
10677@pindex calc-more-recursion-depth
10678@pindex calc-less-recursion-depth
10679@cindex Recursion depth
10680@cindex ``Computation got stuck'' message
10681@cindex @code{max-lisp-eval-depth}
10682@cindex @code{max-specpdl-size}
10683Calc uses recursion in many of its calculations. Emacs Lisp keeps a
10684variable @code{max-lisp-eval-depth} which limits the amount of recursion
10685possible in an attempt to recover from program bugs. If a calculation
10686ever halts incorrectly with the message ``Computation got stuck or
10687ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
10688to increase this limit. (Of course, this will not help if the
10689calculation really did get stuck due to some problem inside Calc.)@refill
10690
10691The limit is always increased (multiplied) by a factor of two. There
10692is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
10693decreases this limit by a factor of two, down to a minimum value of 200.
10694The default value is 1000.
10695
10696These commands also double or halve @code{max-specpdl-size}, another
10697internal Lisp recursion limit. The minimum value for this limit is 600.
10698
10699@node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
10700@subsection Caches
10701
10702@noindent
10703@cindex Caches
10704@cindex Flushing caches
10705Calc saves certain values after they have been computed once. For
10706example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
10707constant @c{$\pi$}
10708@cite{pi} to about 20 decimal places; if the current precision
10709is greater than this, it will recompute @c{$\pi$}
10710@cite{pi} using a series
10711approximation. This value will not need to be recomputed ever again
10712unless you raise the precision still further. Many operations such as
10713logarithms and sines make use of similarly cached values such as
10714@c{$\pi \over 4$}
10715@cite{pi/4} and @c{$\ln 2$}
10716@cite{ln(2)}. The visible effect of caching is that
10717high-precision computations may seem to do extra work the first time.
10718Other things cached include powers of two (for the binary arithmetic
10719functions), matrix inverses and determinants, symbolic integrals, and
10720data points computed by the graphing commands.
10721
10722@pindex calc-flush-caches
10723If you suspect a Calculator cache has become corrupt, you can use the
10724@code{calc-flush-caches} command to reset all caches to the empty state.
10725(This should only be necessary in the event of bugs in the Calculator.)
10726The @kbd{M-# 0} (with the zero key) command also resets caches along
10727with all other aspects of the Calculator's state.
10728
10729@node Debugging Calc, , Caches, Troubleshooting Commands
10730@subsection Debugging Calc
10731
10732@noindent
10733A few commands exist to help in the debugging of Calc commands.
10734@xref{Programming}, to see the various ways that you can write
10735your own Calc commands.
10736
10737@kindex Z T
10738@pindex calc-timing
10739The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
10740in which the timing of slow commands is reported in the Trail.
10741Any Calc command that takes two seconds or longer writes a line
10742to the Trail showing how many seconds it took. This value is
10743accurate only to within one second.
10744
10745All steps of executing a command are included; in particular, time
10746taken to format the result for display in the stack and trail is
10747counted. Some prompts also count time taken waiting for them to
10748be answered, while others do not; this depends on the exact
10749implementation of the command. For best results, if you are timing
10750a sequence that includes prompts or multiple commands, define a
10751keyboard macro to run the whole sequence at once. Calc's @kbd{X}
10752command (@pxref{Keyboard Macros}) will then report the time taken
10753to execute the whole macro.
10754
10755Another advantage of the @kbd{X} command is that while it is
10756executing, the stack and trail are not updated from step to step.
10757So if you expect the output of your test sequence to leave a result
10758that may take a long time to format and you don't wish to count
10759this formatting time, end your sequence with a @key{DEL} keystroke
10760to clear the result from the stack. When you run the sequence with
10761@kbd{X}, Calc will never bother to format the large result.
10762
10763Another thing @kbd{Z T} does is to increase the Emacs variable
10764@code{gc-cons-threshold} to a much higher value (two million; the
10765usual default in Calc is 250,000) for the duration of each command.
10766This generally prevents garbage collection during the timing of
10767the command, though it may cause your Emacs process to grow
10768abnormally large. (Garbage collection time is a major unpredictable
10769factor in the timing of Emacs operations.)
10770
10771Another command that is useful when debugging your own Lisp
10772extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
10773the error handler that changes the ``@code{max-lisp-eval-depth}
10774exceeded'' message to the much more friendly ``Computation got
10775stuck or ran too long.'' This handler interferes with the Emacs
10776Lisp debugger's @code{debug-on-error} mode. Errors are reported
10777in the handler itself rather than at the true location of the
10778error. After you have executed @code{calc-pass-errors}, Lisp
10779errors will be reported correctly but the user-friendly message
10780will be lost.
10781
10782@node Data Types, Stack and Trail, Introduction, Top
10783@chapter Data Types
10784
10785@noindent
10786This chapter discusses the various types of objects that can be placed
10787on the Calculator stack, how they are displayed, and how they are
10788entered. (@xref{Data Type Formats}, for information on how these data
10789types are represented as underlying Lisp objects.)@refill
10790
10791Integers, fractions, and floats are various ways of describing real
10792numbers. HMS forms also for many purposes act as real numbers. These
10793types can be combined to form complex numbers, modulo forms, error forms,
10794or interval forms. (But these last four types cannot be combined
10795arbitrarily:@: error forms may not contain modulo forms, for example.)
10796Finally, all these types of numbers may be combined into vectors,
10797matrices, or algebraic formulas.
10798
10799@menu
10800* Integers:: The most basic data type.
10801* Fractions:: This and above are called @dfn{rationals}.
10802* Floats:: This and above are called @dfn{reals}.
10803* Complex Numbers:: This and above are called @dfn{numbers}.
10804* Infinities::
10805* Vectors and Matrices::
10806* Strings::
10807* HMS Forms::
10808* Date Forms::
10809* Modulo Forms::
10810* Error Forms::
10811* Interval Forms::
10812* Incomplete Objects::
10813* Variables::
10814* Formulas::
10815@end menu
10816
10817@node Integers, Fractions, Data Types, Data Types
10818@section Integers
10819
10820@noindent
10821@cindex Integers
10822The Calculator stores integers to arbitrary precision. Addition,
10823subtraction, and multiplication of integers always yields an exact
10824integer result. (If the result of a division or exponentiation of
10825integers is not an integer, it is expressed in fractional or
10826floating-point form according to the current Fraction Mode.
10827@xref{Fraction Mode}.)
10828
10829A decimal integer is represented as an optional sign followed by a
10830sequence of digits. Grouping (@pxref{Grouping Digits}) can be used to
10831insert a comma at every third digit for display purposes, but you
10832must not type commas during the entry of numbers.@refill
10833
10834@kindex #
10835A non-decimal integer is represented as an optional sign, a radix
10836between 2 and 36, a @samp{#} symbol, and one or more digits. For radix 11
10837and above, the letters A through Z (upper- or lower-case) count as
10838digits and do not terminate numeric entry mode. @xref{Radix Modes}, for how
10839to set the default radix for display of integers. Numbers of any radix
10840may be entered at any time. If you press @kbd{#} at the beginning of a
10841number, the current display radix is used.@refill
10842
10843@node Fractions, Floats, Integers, Data Types
10844@section Fractions
10845
10846@noindent
10847@cindex Fractions
10848A @dfn{fraction} is a ratio of two integers. Fractions are traditionally
10849written ``2/3'' but Calc uses the notation @samp{2:3}. (The @kbd{/} key
10850performs RPN division; the following two sequences push the number
10851@samp{2:3} on the stack: @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
10852assuming Fraction Mode has been enabled.)
10853When the Calculator produces a fractional result it always reduces it to
10854simplest form, which may in fact be an integer.@refill
10855
10856Fractions may also be entered in a three-part form, where @samp{2:3:4}
10857represents two-and-three-quarters. @xref{Fraction Formats}, for fraction
10858display formats.@refill
10859
10860Non-decimal fractions are entered and displayed as
10861@samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
10862form). The numerator and denominator always use the same radix.@refill
10863
10864@node Floats, Complex Numbers, Fractions, Data Types
10865@section Floats
10866
10867@noindent
10868@cindex Floating-point numbers
10869A floating-point number or @dfn{float} is a number stored in scientific
10870notation. The number of significant digits in the fractional part is
10871governed by the current floating precision (@pxref{Precision}). The
10872range of acceptable values is from @c{$10^{-3999999}$}
10873@cite{10^-3999999} (inclusive)
10874to @c{$10^{4000000}$}
10875@cite{10^4000000}
10876(exclusive), plus the corresponding negative
10877values and zero.
10878
10879Calculations that would exceed the allowable range of values (such
10880as @samp{exp(exp(20))}) are left in symbolic form by Calc. The
10881messages ``floating-point overflow'' or ``floating-point underflow''
10882indicate that during the calculation a number would have been produced
10883that was too large or too close to zero, respectively, to be represented
10884by Calc. This does not necessarily mean the final result would have
10885overflowed, just that an overflow occurred while computing the result.
10886(In fact, it could report an underflow even though the final result
10887would have overflowed!)
10888
10889If a rational number and a float are mixed in a calculation, the result
10890will in general be expressed as a float. Commands that require an integer
10891value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
10892floats, i.e., floating-point numbers with nothing after the decimal point.
10893
10894Floats are identified by the presence of a decimal point and/or an
10895exponent. In general a float consists of an optional sign, digits
10896including an optional decimal point, and an optional exponent consisting
10897of an @samp{e}, an optional sign, and up to seven exponent digits.
10898For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
10899or 0.235.
10900
10901Floating-point numbers are normally displayed in decimal notation with
10902all significant figures shown. Exceedingly large or small numbers are
10903displayed in scientific notation. Various other display options are
10904available. @xref{Float Formats}.
10905
10906@cindex Accuracy of calculations
10907Floating-point numbers are stored in decimal, not binary. The result
10908of each operation is rounded to the nearest value representable in the
10909number of significant digits specified by the current precision,
10910rounding away from zero in the case of a tie. Thus (in the default
10911display mode) what you see is exactly what you get. Some operations such
10912as square roots and transcendental functions are performed with several
10913digits of extra precision and then rounded down, in an effort to make the
10914final result accurate to the full requested precision. However,
10915accuracy is not rigorously guaranteed. If you suspect the validity of a
10916result, try doing the same calculation in a higher precision. The
10917Calculator's arithmetic is not intended to be IEEE-conformant in any
10918way.@refill
10919
10920While floats are always @emph{stored} in decimal, they can be entered
10921and displayed in any radix just like integers and fractions. The
10922notation @samp{@var{radix}#@var{ddd}.@var{ddd}} is a floating-point
10923number whose digits are in the specified radix. Note that the @samp{.}
10924is more aptly referred to as a ``radix point'' than as a decimal
10925point in this case. The number @samp{8#123.4567} is defined as
10926@samp{8#1234567 * 8^-4}. If the radix is 14 or less, you can use
10927@samp{e} notation to write a non-decimal number in scientific notation.
10928The exponent is written in decimal, and is considered to be a power
10929of the radix: @samp{8#1234567e-4}. If the radix is 15 or above, the
10930letter @samp{e} is a digit, so scientific notation must be written
10931out, e.g., @samp{16#123.4567*16^2}. The first two exercises of the
10932Modes Tutorial explore some of the properties of non-decimal floats.
10933
10934@node Complex Numbers, Infinities, Floats, Data Types
10935@section Complex Numbers
10936
10937@noindent
10938@cindex Complex numbers
10939There are two supported formats for complex numbers: rectangular and
10940polar. The default format is rectangular, displayed in the form
10941@samp{(@var{real},@var{imag})} where @var{real} is the real part and
10942@var{imag} is the imaginary part, each of which may be any real number.
10943Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
10944notation; @pxref{Complex Formats}.@refill
10945
10946Polar complex numbers are displayed in the form `@t{(}@var{r}@t{;}@c{$\theta$}
10947@var{theta}@t{)}'
10948where @var{r} is the nonnegative magnitude and @c{$\theta$}
10949@var{theta} is the argument
10950or phase angle. The range of @c{$\theta$}
10951@var{theta} depends on the current angular
10952mode (@pxref{Angular Modes}); it is generally between @i{-180} and
10953@i{+180} degrees or the equivalent range in radians.@refill
10954
10955Complex numbers are entered in stages using incomplete objects.
10956@xref{Incomplete Objects}.
10957
10958Operations on rectangular complex numbers yield rectangular complex
10959results, and similarly for polar complex numbers. Where the two types
10960are mixed, or where new complex numbers arise (as for the square root of
10961a negative real), the current @dfn{Polar Mode} is used to determine the
10962type. @xref{Polar Mode}.
10963
10964A complex result in which the imaginary part is zero (or the phase angle
10965is 0 or 180 degrees or @c{$\pi$}
10966@cite{pi} radians) is automatically converted to a real
10967number.
10968
10969@node Infinities, Vectors and Matrices, Complex Numbers, Data Types
10970@section Infinities
10971
10972@noindent
10973@cindex Infinity
10974@cindex @code{inf} variable
10975@cindex @code{uinf} variable
10976@cindex @code{nan} variable
10977@vindex inf
10978@vindex uinf
10979@vindex nan
10980The word @code{inf} represents the mathematical concept of @dfn{infinity}.
10981Calc actually has three slightly different infinity-like values:
10982@code{inf}, @code{uinf}, and @code{nan}. These are just regular
10983variable names (@pxref{Variables}); you should avoid using these
10984names for your own variables because Calc gives them special
10985treatment. Infinities, like all variable names, are normally
10986entered using algebraic entry.
10987
10988Mathematically speaking, it is not rigorously correct to treat
10989``infinity'' as if it were a number, but mathematicians often do
10990so informally. When they say that @samp{1 / inf = 0}, what they
10991really mean is that @cite{1 / x}, as @cite{x} becomes larger and
10992larger, becomes arbitrarily close to zero. So you can imagine
10993that if @cite{x} got ``all the way to infinity,'' then @cite{1 / x}
10994would go all the way to zero. Similarly, when they say that
10995@samp{exp(inf) = inf}, they mean that @c{$e^x$}
10996@cite{exp(x)} grows without
10997bound as @cite{x} grows. The symbol @samp{-inf} likewise stands
10998for an infinitely negative real value; for example, we say that
10999@samp{exp(-inf) = 0}. You can have an infinity pointing in any
11000direction on the complex plane: @samp{sqrt(-inf) = i inf}.
11001
11002The same concept of limits can be used to define @cite{1 / 0}. We
11003really want the value that @cite{1 / x} approaches as @cite{x}
11004approaches zero. But if all we have is @cite{1 / 0}, we can't
11005tell which direction @cite{x} was coming from. If @cite{x} was
11006positive and decreasing toward zero, then we should say that
11007@samp{1 / 0 = inf}. But if @cite{x} was negative and increasing
11008toward zero, the answer is @samp{1 / 0 = -inf}. In fact, @cite{x}
11009could be an imaginary number, giving the answer @samp{i inf} or
11010@samp{-i inf}. Calc uses the special symbol @samp{uinf} to mean
11011@dfn{undirected infinity}, i.e., a value which is infinitely
11012large but with an unknown sign (or direction on the complex plane).
11013
11014Calc actually has three modes that say how infinities are handled.
11015Normally, infinities never arise from calculations that didn't
11016already have them. Thus, @cite{1 / 0} is treated simply as an
11017error and left unevaluated. The @kbd{m i} (@code{calc-infinite-mode})
11018command (@pxref{Infinite Mode}) enables a mode in which
11019@cite{1 / 0} evaluates to @code{uinf} instead. There is also
11020an alternative type of infinite mode which says to treat zeros
11021as if they were positive, so that @samp{1 / 0 = inf}. While this
11022is less mathematically correct, it may be the answer you want in
11023some cases.
11024
11025Since all infinities are ``as large'' as all others, Calc simplifies,
11026e.g., @samp{5 inf} to @samp{inf}. Another example is
11027@samp{5 - inf = -inf}, where the @samp{-inf} is so large that
11028adding a finite number like five to it does not affect it.
11029Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
11030that variables like @code{a} always stand for finite quantities.
11031Just to show that infinities really are all the same size,
11032note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
11033notation.
11034
11035It's not so easy to define certain formulas like @samp{0 * inf} and
11036@samp{inf / inf}. Depending on where these zeros and infinities
11037came from, the answer could be literally anything. The latter
11038formula could be the limit of @cite{x / x} (giving a result of one),
11039or @cite{2 x / x} (giving two), or @cite{x^2 / x} (giving @code{inf}),
11040or @cite{x / x^2} (giving zero). Calc uses the symbol @code{nan}
11041to represent such an @dfn{indeterminate} value. (The name ``nan''
11042comes from analogy with the ``NAN'' concept of IEEE standard
11043arithmetic; it stands for ``Not A Number.'' This is somewhat of a
11044misnomer, since @code{nan} @emph{does} stand for some number or
11045infinity, it's just that @emph{which} number it stands for
11046cannot be determined.) In Calc's notation, @samp{0 * inf = nan}
11047and @samp{inf / inf = nan}. A few other common indeterminate
11048expressions are @samp{inf - inf} and @samp{inf ^ 0}. Also,
11049@samp{0 / 0 = nan} if you have turned on ``infinite mode''
11050(as described above).
11051
11052Infinities are especially useful as parts of @dfn{intervals}.
11053@xref{Interval Forms}.
11054
11055@node Vectors and Matrices, Strings, Infinities, Data Types
11056@section Vectors and Matrices
11057
11058@noindent
11059@cindex Vectors
11060@cindex Plain vectors
11061@cindex Matrices
11062The @dfn{vector} data type is flexible and general. A vector is simply a
11063list of zero or more data objects. When these objects are numbers, the
11064whole is a vector in the mathematical sense. When these objects are
11065themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
11066A vector which is not a matrix is referred to here as a @dfn{plain vector}.
11067
11068A vector is displayed as a list of values separated by commas and enclosed
11069in square brackets: @samp{[1, 2, 3]}. Thus the following is a 2 row by
110703 column matrix: @samp{[[1, 2, 3], [4, 5, 6]]}. Vectors, like complex
11071numbers, are entered as incomplete objects. @xref{Incomplete Objects}.
11072During algebraic entry, vectors are entered all at once in the usual
11073brackets-and-commas form. Matrices may be entered algebraically as nested
11074vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
11075with rows separated by semicolons. The commas may usually be omitted
11076when entering vectors: @samp{[1 2 3]}. Curly braces may be used in
11077place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
11078this case.
11079
11080Traditional vector and matrix arithmetic is also supported;
11081@pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
11082Many other operations are applied to vectors element-wise. For example,
11083the complex conjugate of a vector is a vector of the complex conjugates
11084of its elements.@refill
11085
11086@c @starindex
11087@tindex vec
11088Algebraic functions for building vectors include @samp{vec(a, b, c)}
11089to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an @c{$n\times m$}
11090@asis{@var{n}x@var{m}}
11091matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
11092from 1 to @samp{n}.
11093
11094@node Strings, HMS Forms, Vectors and Matrices, Data Types
11095@section Strings
11096
11097@noindent
11098@kindex "
11099@cindex Strings
11100@cindex Character strings
11101Character strings are not a special data type in the Calculator.
11102Rather, a string is represented simply as a vector all of whose
11103elements are integers in the range 0 to 255 (ASCII codes). You can
11104enter a string at any time by pressing the @kbd{"} key. Quotation
11105marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
11106inside strings. Other notations introduced by backslashes are:
11107
11108@group
11109@example
11110\a 7 \^@@ 0
11111\b 8 \^a-z 1-26
11112\e 27 \^[ 27
11113\f 12 \^\\ 28
11114\n 10 \^] 29
11115\r 13 \^^ 30
11116\t 9 \^_ 31
11117 \^? 127
11118@end example
11119@end group
11120
11121@noindent
11122Finally, a backslash followed by three octal digits produces any
11123character from its ASCII code.
11124
11125@kindex d "
11126@pindex calc-display-strings
11127Strings are normally displayed in vector-of-integers form. The
11128@w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
11129which any vectors of small integers are displayed as quoted strings
11130instead.
11131
11132The backslash notations shown above are also used for displaying
11133strings. Characters 128 and above are not translated by Calc; unless
11134you have an Emacs modified for 8-bit fonts, these will show up in
11135backslash-octal-digits notation. For characters below 32, and
11136for character 127, Calc uses the backslash-letter combination if
11137there is one, or otherwise uses a @samp{\^} sequence.
11138
11139The only Calc feature that uses strings is @dfn{compositions};
11140@pxref{Compositions}. Strings also provide a convenient
11141way to do conversions between ASCII characters and integers.
11142
11143@c @starindex
11144@tindex string
11145There is a @code{string} function which provides a different display
11146format for strings. Basically, @samp{string(@var{s})}, where @var{s}
11147is a vector of integers in the proper range, is displayed as the
11148corresponding string of characters with no surrounding quotation
11149marks or other modifications. Thus @samp{string("ABC")} (or
11150@samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
11151This happens regardless of whether @w{@kbd{d "}} has been used. The
11152only way to turn it off is to use @kbd{d U} (unformatted language
11153mode) which will display @samp{string("ABC")} instead.
11154
11155Control characters are displayed somewhat differently by @code{string}.
11156Characters below 32, and character 127, are shown using @samp{^} notation
11157(same as shown above, but without the backslash). The quote and
11158backslash characters are left alone, as are characters 128 and above.
11159
11160@c @starindex
11161@tindex bstring
11162The @code{bstring} function is just like @code{string} except that
11163the resulting string is breakable across multiple lines if it doesn't
11164fit all on one line. Potential break points occur at every space
11165character in the string.
11166
11167@node HMS Forms, Date Forms, Strings, Data Types
11168@section HMS Forms
11169
11170@noindent
11171@cindex Hours-minutes-seconds forms
11172@cindex Degrees-minutes-seconds forms
11173@dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
11174argument, the interpretation is Degrees-Minutes-Seconds. All functions
11175that operate on angles accept HMS forms. These are interpreted as
11176degrees regardless of the current angular mode. It is also possible to
11177use HMS as the angular mode so that calculated angles are expressed in
11178degrees, minutes, and seconds.
11179
11180@kindex @@
11181@c @mindex @null
11182@kindex ' (HMS forms)
11183@c @mindex @null
11184@kindex " (HMS forms)
11185@c @mindex @null
11186@kindex h (HMS forms)
11187@c @mindex @null
11188@kindex o (HMS forms)
11189@c @mindex @null
11190@kindex m (HMS forms)
11191@c @mindex @null
11192@kindex s (HMS forms)
11193The default format for HMS values is
11194@samp{@var{hours}@@ @var{mins}' @var{secs}"}. During entry, the letters
11195@samp{h} (for ``hours'') or
11196@samp{o} (approximating the ``degrees'' symbol) are accepted as well as
11197@samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
11198accepted in place of @samp{"}.
11199The @var{hours} value is an integer (or integer-valued float).
11200The @var{mins} value is an integer or integer-valued float between 0 and 59.
11201The @var{secs} value is a real number between 0 (inclusive) and 60
11202(exclusive). A positive HMS form is interpreted as @var{hours} +
11203@var{mins}/60 + @var{secs}/3600. A negative HMS form is interpreted
11204as @i{- @var{hours}} @i{-} @var{mins}/60 @i{-} @var{secs}/3600.
11205Display format for HMS forms is quite flexible. @xref{HMS Formats}.@refill
11206
11207HMS forms can be added and subtracted. When they are added to numbers,
11208the numbers are interpreted according to the current angular mode. HMS
11209forms can also be multiplied and divided by real numbers. Dividing
11210two HMS forms produces a real-valued ratio of the two angles.
11211
11212@pindex calc-time
11213@cindex Time of day
11214Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
11215the stack as an HMS form.
11216
11217@node Date Forms, Modulo Forms, HMS Forms, Data Types
11218@section Date Forms
11219
11220@noindent
11221@cindex Date forms
11222A @dfn{date form} represents a date and possibly an associated time.
11223Simple date arithmetic is supported: Adding a number to a date
11224produces a new date shifted by that many days; adding an HMS form to
11225a date shifts it by that many hours. Subtracting two date forms
11226computes the number of days between them (represented as a simple
11227number). Many other operations, such as multiplying two date forms,
11228are nonsensical and are not allowed by Calc.
11229
11230Date forms are entered and displayed enclosed in @samp{< >} brackets.
11231The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
11232or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
11233Input is flexible; date forms can be entered in any of the usual
11234notations for dates and times. @xref{Date Formats}.
11235
11236Date forms are stored internally as numbers, specifically the number
11237of days since midnight on the morning of January 1 of the year 1 AD.
11238If the internal number is an integer, the form represents a date only;
11239if the internal number is a fraction or float, the form represents
11240a date and time. For example, @samp{<6:00am Wed Jan 9, 1991>}
11241is represented by the number 726842.25. The standard precision of
1124212 decimal digits is enough to ensure that a (reasonable) date and
11243time can be stored without roundoff error.
11244
11245If the current precision is greater than 12, date forms will keep
11246additional digits in the seconds position. For example, if the
11247precision is 15, the seconds will keep three digits after the
11248decimal point. Decreasing the precision below 12 may cause the
11249time part of a date form to become inaccurate. This can also happen
11250if astronomically high years are used, though this will not be an
11251issue in everyday (or even everymillenium) use. Note that date
11252forms without times are stored as exact integers, so roundoff is
11253never an issue for them.
11254
11255You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
11256(@code{calc-unpack}) commands to get at the numerical representation
11257of a date form. @xref{Packing and Unpacking}.
11258
11259Date forms can go arbitrarily far into the future or past. Negative
11260year numbers represent years BC. Calc uses a combination of the
11261Gregorian and Julian calendars, following the history of Great
11262Britain and the British colonies. This is the same calendar that
11263is used by the @code{cal} program in most Unix implementations.
11264
11265@cindex Julian calendar
11266@cindex Gregorian calendar
11267Some historical background: The Julian calendar was created by
11268Julius Caesar in the year 46 BC as an attempt to fix the gradual
11269drift caused by the lack of leap years in the calendar used
11270until that time. The Julian calendar introduced an extra day in
11271all years divisible by four. After some initial confusion, the
11272calendar was adopted around the year we call 8 AD. Some centuries
11273later it became apparent that the Julian year of 365.25 days was
11274itself not quite right. In 1582 Pope Gregory XIII introduced the
11275Gregorian calendar, which added the new rule that years divisible
11276by 100, but not by 400, were not to be considered leap years
11277despite being divisible by four. Many countries delayed adoption
11278of the Gregorian calendar because of religious differences;
11279in Britain it was put off until the year 1752, by which time
11280the Julian calendar had fallen eleven days behind the true
11281seasons. So the switch to the Gregorian calendar in early
11282September 1752 introduced a discontinuity: The day after
11283Sep 2, 1752 is Sep 14, 1752. Calc follows this convention.
11284To take another example, Russia waited until 1918 before
11285adopting the new calendar, and thus needed to remove thirteen
11286days (between Feb 1, 1918 and Feb 14, 1918). This means that
11287Calc's reckoning will be inconsistent with Russian history between
112881752 and 1918, and similarly for various other countries.
11289
11290Today's timekeepers introduce an occasional ``leap second'' as
11291well, but Calc does not take these minor effects into account.
11292(If it did, it would have to report a non-integer number of days
11293between, say, @samp{<12:00am Mon Jan 1, 1900>} and
11294@samp{<12:00am Sat Jan 1, 2000>}.)
11295
11296Calc uses the Julian calendar for all dates before the year 1752,
11297including dates BC when the Julian calendar technically had not
11298yet been invented. Thus the claim that day number @i{-10000} is
11299called ``August 16, 28 BC'' should be taken with a grain of salt.
11300
11301Please note that there is no ``year 0''; the day before
11302@samp{<Sat Jan 1, +1>} is @samp{<Fri Dec 31, -1>}. These are
11303days 0 and @i{-1} respectively in Calc's internal numbering scheme.
11304
11305@cindex Julian day counting
11306Another day counting system in common use is, confusingly, also
11307called ``Julian.'' It was invented in 1583 by Joseph Justus
11308Scaliger, who named it in honor of his father Julius Caesar
11309Scaliger. For obscure reasons he chose to start his day
11310numbering on Jan 1, 4713 BC at noon, which in Calc's scheme
11311is @i{-1721423.5} (recall that Calc starts at midnight instead
11312of noon). Thus to convert a Calc date code obtained by
11313unpacking a date form into a Julian day number, simply add
113141721423.5. The Julian code for @samp{6:00am Jan 9, 1991}
11315is 2448265.75. The built-in @kbd{t J} command performs
11316this conversion for you.
11317
11318@cindex Unix time format
11319The Unix operating system measures time as an integer number of
11320seconds since midnight, Jan 1, 1970. To convert a Calc date
11321value into a Unix time stamp, first subtract 719164 (the code
11322for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
11323seconds in a day) and press @kbd{R} to round to the nearest
11324integer. If you have a date form, you can simply subtract the
11325day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
11326719164. Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
11327to convert from Unix time to a Calc date form. (Note that
11328Unix normally maintains the time in the GMT time zone; you may
11329need to subtract five hours to get New York time, or eight hours
11330for California time. The same is usually true of Julian day
11331counts.) The built-in @kbd{t U} command performs these
11332conversions.
11333
11334@node Modulo Forms, Error Forms, Date Forms, Data Types
11335@section Modulo Forms
11336
11337@noindent
11338@cindex Modulo forms
11339A @dfn{modulo form} is a real number which is taken modulo (i.e., within
11340an integer multiple of) some value @cite{M}. Arithmetic modulo @cite{M}
11341often arises in number theory. Modulo forms are written
11342`@i{a} @t{mod} @i{M}',
11343where @cite{a} and @cite{M} are real numbers or HMS forms, and
11344@c{$0 \le a < M$}
11345@cite{0 <= a < @var{M}}.
11346In many applications @cite{a} and @cite{M} will be
11347integers but this is not required.@refill
11348
11349Modulo forms are not to be confused with the modulo operator @samp{%}.
11350The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
11351the result 7. Further computations treat this 7 as just a regular integer.
11352The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
11353further computations with this value are again reduced modulo 10 so that
11354the result always lies in the desired range.
11355
11356When two modulo forms with identical @cite{M}'s are added or multiplied,
11357the Calculator simply adds or multiplies the values, then reduces modulo
11358@cite{M}. If one argument is a modulo form and the other a plain number,
11359the plain number is treated like a compatible modulo form. It is also
11360possible to raise modulo forms to powers; the result is the value raised
11361to the power, then reduced modulo @cite{M}. (When all values involved
11362are integers, this calculation is done much more efficiently than
11363actually computing the power and then reducing.)
11364
11365@cindex Modulo division
11366Two modulo forms `@i{a} @t{mod} @i{M}' and `@i{b} @t{mod} @i{M}'
11367can be divided if @cite{a}, @cite{b}, and @cite{M} are all
11368integers. The result is the modulo form which, when multiplied by
11369`@i{b} @t{mod} @i{M}', produces `@i{a} @t{mod} @i{M}'. If
11370there is no solution to this equation (which can happen only when
11371@cite{M} is non-prime), or if any of the arguments are non-integers, the
11372division is left in symbolic form. Other operations, such as square
11373roots, are not yet supported for modulo forms. (Note that, although
11374@w{`@t{(}@i{a} @t{mod} @i{M}@t{)^.5}'} will compute a ``modulo square root''
11375in the sense of reducing @c{$\sqrt a$}
11376@cite{sqrt(a)} modulo @cite{M}, this is not a
11377useful definition from the number-theoretical point of view.)@refill
11378
11379@c @mindex M
11380@kindex M (modulo forms)
11381@c @mindex mod
11382@tindex mod (operator)
11383To create a modulo form during numeric entry, press the shift-@kbd{M}
11384key to enter the word @samp{mod}. As a special convenience, pressing
11385shift-@kbd{M} a second time automatically enters the value of @cite{M}
11386that was most recently used before. During algebraic entry, either
11387type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
11388Once again, pressing this a second time enters the current modulo.@refill
11389
11390You can also use @kbd{v p} and @kbd{%} to modify modulo forms.
11391@xref{Building Vectors}. @xref{Basic Arithmetic}.
11392
11393It is possible to mix HMS forms and modulo forms. For example, an
11394HMS form modulo 24 could be used to manipulate clock times; an HMS
11395form modulo 360 would be suitable for angles. Making the modulo @cite{M}
11396also be an HMS form eliminates troubles that would arise if the angular
11397mode were inadvertently set to Radians, in which case
11398@w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
1139924 radians!
11400
11401Modulo forms cannot have variables or formulas for components. If you
11402enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
11403to each of the coefficients: @samp{(1 mod 5) x + (2 mod 5)}.
11404
11405@c @starindex
11406@tindex makemod
11407The algebraic function @samp{makemod(a, m)} builds the modulo form
11408@w{@samp{a mod m}}.
11409
11410@node Error Forms, Interval Forms, Modulo Forms, Data Types
11411@section Error Forms
11412
11413@noindent
11414@cindex Error forms
11415@cindex Standard deviations
11416An @dfn{error form} is a number with an associated standard
11417deviation, as in @samp{2.3 +/- 0.12}. The notation
11418`@i{x} @t{+/-} @c{$\sigma$}
11419@asis{sigma}' stands for an uncertain value which follows a normal or
11420Gaussian distribution of mean @cite{x} and standard deviation or
11421``error'' @c{$\sigma$}
11422@cite{sigma}. Both the mean and the error can be either numbers or
11423formulas. Generally these are real numbers but the mean may also be
11424complex. If the error is negative or complex, it is changed to its
11425absolute value. An error form with zero error is converted to a
11426regular number by the Calculator.@refill
11427
11428All arithmetic and transcendental functions accept error forms as input.
11429Operations on the mean-value part work just like operations on regular
11430numbers. The error part for any function @cite{f(x)} (such as @c{$\sin x$}
11431@cite{sin(x)})
11432is defined by the error of @cite{x} times the derivative of @cite{f}
11433evaluated at the mean value of @cite{x}. For a two-argument function
11434@cite{f(x,y)} (such as addition) the error is the square root of the sum
11435of the squares of the errors due to @cite{x} and @cite{y}.
11436@tex
11437$$ \eqalign{
11438 f(x \hbox{\code{ +/- }} \sigma)
11439 &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
11440 f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
11441 &= f(x,y) \hbox{\code{ +/- }}
11442 \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
11443 \right| \right)^2
11444 +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
11445 \right| \right)^2 } \cr
11446} $$
11447@end tex
11448Note that this
11449definition assumes the errors in @cite{x} and @cite{y} are uncorrelated.
11450A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
11451is not the same as @samp{(2 +/- 1)^2}; the former represents the product
11452of two independent values which happen to have the same probability
11453distributions, and the latter is the product of one random value with itself.
11454The former will produce an answer with less error, since on the average
11455the two independent errors can be expected to cancel out.@refill
11456
11457Consult a good text on error analysis for a discussion of the proper use
11458of standard deviations. Actual errors often are neither Gaussian-distributed
11459nor uncorrelated, and the above formulas are valid only when errors
11460are small. As an example, the error arising from
11461`@t{sin(}@i{x} @t{+/-} @c{$\sigma$}
11462@i{sigma}@t{)}' is
11463`@c{$\sigma$\nobreak}
11464@i{sigma} @t{abs(cos(}@i{x}@t{))}'. When @cite{x} is close to zero,
11465@c{$\cos x$}
11466@cite{cos(x)} is
11467close to one so the error in the sine is close to @c{$\sigma$}
11468@cite{sigma}; this makes sense, since @c{$\sin x$}
11469@cite{sin(x)} is approximately @cite{x} near zero, so a given
11470error in @cite{x} will produce about the same error in the sine. Likewise,
11471near 90 degrees @c{$\cos x$}
11472@cite{cos(x)} is nearly zero and so the computed error is
11473small: The sine curve is nearly flat in that region, so an error in @cite{x}
11474has relatively little effect on the value of @c{$\sin x$}
11475@cite{sin(x)}. However, consider
11476@samp{sin(90 +/- 1000)}. The cosine of 90 is zero, so Calc will report
11477zero error! We get an obviously wrong result because we have violated
11478the small-error approximation underlying the error analysis. If the error
11479in @cite{x} had been small, the error in @c{$\sin x$}
11480@cite{sin(x)} would indeed have been negligible.@refill
11481
11482@c @mindex p
11483@kindex p (error forms)
11484@tindex +/-
11485To enter an error form during regular numeric entry, use the @kbd{p}
11486(``plus-or-minus'') key to type the @samp{+/-} symbol. (If you try actually
11487typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
11488@kbd{+} command!) Within an algebraic formula, you can press @kbd{M-p} to
11489type the @samp{+/-} symbol, or type it out by hand.
11490
11491Error forms and complex numbers can be mixed; the formulas shown above
11492are used for complex numbers, too; note that if the error part evaluates
11493to a complex number its absolute value (or the square root of the sum of
11494the squares of the absolute values of the two error contributions) is
11495used. Mathematically, this corresponds to a radially symmetric Gaussian
11496distribution of numbers on the complex plane. However, note that Calc
11497considers an error form with real components to represent a real number,
11498not a complex distribution around a real mean.
11499
11500Error forms may also be composed of HMS forms. For best results, both
11501the mean and the error should be HMS forms if either one is.
11502
11503@c @starindex
11504@tindex sdev
11505The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
11506
11507@node Interval Forms, Incomplete Objects, Error Forms, Data Types
11508@section Interval Forms
11509
11510@noindent
11511@cindex Interval forms
11512An @dfn{interval} is a subset of consecutive real numbers. For example,
11513the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
11514inclusive. If you multiply it by the interval @samp{[0.5 ..@: 2]} you
11515obtain @samp{[1 ..@: 8]}. This calculation represents the fact that if
11516you multiply some number in the range @samp{[2 ..@: 4]} by some other
11517number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
11518from 1 to 8. Interval arithmetic is used to get a worst-case estimate
11519of the possible range of values a computation will produce, given the
11520set of possible values of the input.
11521
11522@ifinfo
11523Calc supports several varieties of intervals, including @dfn{closed}
11524intervals of the type shown above, @dfn{open} intervals such as
11525@samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
11526@emph{exclusive}, and @dfn{semi-open} intervals in which one end
11527uses a round parenthesis and the other a square bracket. In mathematical
11528terms,
11529@samp{[2 ..@: 4]} means @cite{2 <= x <= 4}, whereas
11530@samp{[2 ..@: 4)} represents @cite{2 <= x < 4},
11531@samp{(2 ..@: 4]} represents @cite{2 < x <= 4}, and
11532@samp{(2 ..@: 4)} represents @cite{2 < x < 4}.@refill
11533@end ifinfo
11534@tex
11535Calc supports several varieties of intervals, including \dfn{closed}
11536intervals of the type shown above, \dfn{open} intervals such as
11537\samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
11538\emph{exclusive}, and \dfn{semi-open} intervals in which one end
11539uses a round parenthesis and the other a square bracket. In mathematical
11540terms,
11541$$ \eqalign{
11542 [2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 \le x \le 4 \cr
11543 [2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 \le x < 4 \cr
11544 (2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 < x \le 4 \cr
11545 (2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 < x < 4 \cr
11546} $$
11547@end tex
11548
11549The lower and upper limits of an interval must be either real numbers
11550(or HMS or date forms), or symbolic expressions which are assumed to be
11551real-valued, or @samp{-inf} and @samp{inf}. In general the lower limit
11552must be less than the upper limit. A closed interval containing only
11553one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
11554automatically. An interval containing no values at all (such as
11555@samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
11556guaranteed to behave well when used in arithmetic. Note that the
11557interval @samp{[3 .. inf)} represents all real numbers greater than
11558or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
11559In fact, @samp{[-inf .. inf]} represents all real numbers including
11560the real infinities.
11561
11562Intervals are entered in the notation shown here, either as algebraic
11563formulas, or using incomplete forms. (@xref{Incomplete Objects}.)
11564In algebraic formulas, multiple periods in a row are collected from
11565left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
11566rather than @samp{1 ..@: 0.1e2}. Add spaces or zeros if you want to
11567get the other interpretation. If you omit the lower or upper limit,
11568a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
11569
11570``Infinite mode'' also affects operations on intervals
11571(@pxref{Infinities}). Calc will always introduce an open infinity,
11572as in @samp{1 / (0 .. 2] = [0.5 .. inf)}. But closed infinities,
11573@w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in infinite mode;
11574otherwise they are left unevaluated. Note that the ``direction'' of
11575a zero is not an issue in this case since the zero is always assumed
11576to be continuous with the rest of the interval. For intervals that
11577contain zero inside them Calc is forced to give the result,
11578@samp{1 / (-2 .. 2) = [-inf .. inf]}.
11579
11580While it may seem that intervals and error forms are similar, they are
11581based on entirely different concepts of inexact quantities. An error
11582form `@i{x} @t{+/-} @c{$\sigma$}
11583@i{sigma}' means a variable is random, and its value could
11584be anything but is ``probably'' within one @c{$\sigma$}
11585@i{sigma} of the mean value @cite{x}.
11586An interval `@t{[}@i{a} @t{..@:} @i{b}@t{]}' means a variable's value
11587is unknown, but guaranteed to lie in the specified range. Error forms
11588are statistical or ``average case'' approximations; interval arithmetic
11589tends to produce ``worst case'' bounds on an answer.@refill
11590
11591Intervals may not contain complex numbers, but they may contain
11592HMS forms or date forms.
11593
11594@xref{Set Operations}, for commands that interpret interval forms
11595as subsets of the set of real numbers.
11596
11597@c @starindex
11598@tindex intv
11599The algebraic function @samp{intv(n, a, b)} builds an interval form
11600from @samp{a} to @samp{b}; @samp{n} is an integer code which must
11601be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
116023 for @samp{[..]}.
11603
11604Please note that in fully rigorous interval arithmetic, care would be
11605taken to make sure that the computation of the lower bound rounds toward
11606minus infinity, while upper bound computations round toward plus
11607infinity. Calc's arithmetic always uses a round-to-nearest mode,
11608which means that roundoff errors could creep into an interval
11609calculation to produce intervals slightly smaller than they ought to
11610be. For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
11611should yield the interval @samp{[1..2]} again, but in fact it yields the
11612(slightly too small) interval @samp{[1..1.9999999]} due to roundoff
11613error.
11614
11615@node Incomplete Objects, Variables, Interval Forms, Data Types
11616@section Incomplete Objects
11617
11618@noindent
11619@c @mindex [ ]
11620@kindex [
11621@c @mindex ( )
11622@kindex (
11623@kindex ,
11624@c @mindex @null
11625@kindex ]
11626@c @mindex @null
11627@kindex )
11628@cindex Incomplete vectors
11629@cindex Incomplete complex numbers
11630@cindex Incomplete interval forms
11631When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
11632vector, respectively, the effect is to push an @dfn{incomplete} complex
11633number or vector onto the stack. The @kbd{,} key adds the value(s) at
11634the top of the stack onto the current incomplete object. The @kbd{)}
11635and @kbd{]} keys ``close'' the incomplete object after adding any values
11636on the top of the stack in front of the incomplete object.
11637
11638As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
11639pushes the vector @samp{[2, 6, 9]} onto the stack. Likewise, @kbd{( 1 , 2 Q )}
11640pushes the complex number @samp{(1, 1.414)} (approximately).
11641
11642If several values lie on the stack in front of the incomplete object,
11643all are collected and appended to the object. Thus the @kbd{,} key
11644is redundant: @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}. Some people
11645prefer the equivalent @key{SPC} key to @key{RET}.@refill
11646
11647As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
11648@kbd{,} adds a zero or duplicates the preceding value in the list being
11649formed. Typing @key{DEL} during incomplete entry removes the last item
11650from the list.
11651
11652@kindex ;
11653The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
11654numbers: @kbd{( 1 ; 2 )}. When entering a vector, @kbd{;} is useful for
11655creating a matrix. In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
11656equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
11657
11658@kindex ..
11659@pindex calc-dots
11660Incomplete entry is also used to enter intervals. For example,
11661@kbd{[ 2 ..@: 4 )} enters a semi-open interval. Note that when you type
11662the first period, it will be interpreted as a decimal point, but when
11663you type a second period immediately afterward, it is re-interpreted as
11664part of the interval symbol. Typing @kbd{..} corresponds to executing
11665the @code{calc-dots} command.
11666
11667If you find incomplete entry distracting, you may wish to enter vectors
11668and complex numbers as algebraic formulas by pressing the apostrophe key.
11669
11670@node Variables, Formulas, Incomplete Objects, Data Types
11671@section Variables
11672
11673@noindent
11674@cindex Variables, in formulas
11675A @dfn{variable} is somewhere between a storage register on a conventional
11676calculator, and a variable in a programming language. (In fact, a Calc
11677variable is really just an Emacs Lisp variable that contains a Calc number
11678or formula.) A variable's name is normally composed of letters and digits.
11679Calc also allows apostrophes and @code{#} signs in variable names.
11680The Calc variable @code{foo} corresponds to the Emacs Lisp variable
11681@code{var-foo}. Commands like @kbd{s s} (@code{calc-store}) that operate
11682on variables can be made to use any arbitrary Lisp variable simply by
11683backspacing over the @samp{var-} prefix in the minibuffer.@refill
11684
11685In a command that takes a variable name, you can either type the full
11686name of a variable, or type a single digit to use one of the special
11687convenience variables @code{var-q0} through @code{var-q9}. For example,
11688@kbd{3 s s 2} stores the number 3 in variable @code{var-q2}, and
11689@w{@kbd{3 s s foo @key{RET}}} stores that number in variable
11690@code{var-foo}.@refill
11691
11692To push a variable itself (as opposed to the variable's value) on the
11693stack, enter its name as an algebraic expression using the apostrophe
11694(@key{'}) key. Variable names in algebraic formulas implicitly have
11695@samp{var-} prefixed to their names. The @samp{#} character in variable
11696names used in algebraic formulas corresponds to a dash @samp{-} in the
11697Lisp variable name. If the name contains any dashes, the prefix @samp{var-}
11698is @emph{not} automatically added. Thus the two formulas @samp{foo + 1}
11699and @samp{var#foo + 1} both refer to the same variable.
11700
11701@kindex =
11702@pindex calc-evaluate
11703@cindex Evaluation of variables in a formula
11704@cindex Variables, evaluation
11705@cindex Formulas, evaluation
11706The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
11707replacing all variables in the formula which have been given values by a
11708@code{calc-store} or @code{calc-let} command by their stored values.
11709Other variables are left alone. Thus a variable that has not been
11710stored acts like an abstract variable in algebra; a variable that has
11711been stored acts more like a register in a traditional calculator.
11712With a positive numeric prefix argument, @kbd{=} evaluates the top
11713@var{n} stack entries; with a negative argument, @kbd{=} evaluates
11714the @var{n}th stack entry.
11715
11716@cindex @code{e} variable
11717@cindex @code{pi} variable
11718@cindex @code{i} variable
11719@cindex @code{phi} variable
11720@cindex @code{gamma} variable
11721@vindex e
11722@vindex pi
11723@vindex i
11724@vindex phi
11725@vindex gamma
11726A few variables are called @dfn{special constants}. Their names are
11727@samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
11728(@xref{Scientific Functions}.) When they are evaluated with @kbd{=},
11729their values are calculated if necessary according to the current precision
11730or complex polar mode. If you wish to use these symbols for other purposes,
11731simply undefine or redefine them using @code{calc-store}.@refill
11732
11733The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
11734infinite or indeterminate values. It's best not to use them as
11735regular variables, since Calc uses special algebraic rules when
11736it manipulates them. Calc displays a warning message if you store
11737a value into any of these special variables.
11738
11739@xref{Store and Recall}, for a discussion of commands dealing with variables.
11740
11741@node Formulas, , Variables, Data Types
11742@section Formulas
11743
11744@noindent
11745@cindex Formulas
11746@cindex Expressions
11747@cindex Operators in formulas
11748@cindex Precedence of operators
11749When you press the apostrophe key you may enter any expression or formula
11750in algebraic form. (Calc uses the terms ``expression'' and ``formula''
11751interchangeably.) An expression is built up of numbers, variable names,
11752and function calls, combined with various arithmetic operators.
11753Parentheses may
11754be used to indicate grouping. Spaces are ignored within formulas, except
11755that spaces are not permitted within variable names or numbers.
11756Arithmetic operators, in order from highest to lowest precedence, and
11757with their equivalent function names, are:
11758
11759@samp{_} [@code{subscr}] (subscripts);
11760
11761postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
11762
11763prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x})
11764and prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
11765
11766@samp{+/-} [@code{sdev}] (the standard deviation symbol) and
11767@samp{mod} [@code{makemod}] (the symbol for modulo forms);
11768
11769postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
11770and postfix @samp{!!} [@code{dfact}] (double factorial);
11771
11772@samp{^} [@code{pow}] (raised-to-the-power-of);
11773
11774@samp{*} [@code{mul}];
11775
11776@samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
11777@samp{\} [@code{idiv}] (integer division);
11778
11779infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
11780
11781@samp{|} [@code{vconcat}] (vector concatenation);
11782
11783relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
11784@samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
11785
11786@samp{&&} [@code{land}] (logical ``and'');
11787
11788@samp{||} [@code{lor}] (logical ``or'');
11789
11790the C-style ``if'' operator @samp{a?b:c} [@code{if}];
11791
11792@samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
11793
11794@samp{&&&} [@code{pand}] (rewrite pattern ``and'');
11795
11796@samp{|||} [@code{por}] (rewrite pattern ``or'');
11797
11798@samp{:=} [@code{assign}] (for assignments and rewrite rules);
11799
11800@samp{::} [@code{condition}] (rewrite pattern condition);
11801
11802@samp{=>} [@code{evalto}].
11803
11804Note that, unlike in usual computer notation, multiplication binds more
11805strongly than division: @samp{a*b/c*d} is equivalent to @c{$a b \over c d$}
11806@cite{(a*b)/(c*d)}.
11807
11808@cindex Multiplication, implicit
11809@cindex Implicit multiplication
11810The multiplication sign @samp{*} may be omitted in many cases. In particular,
11811if the righthand side is a number, variable name, or parenthesized
11812expression, the @samp{*} may be omitted. Implicit multiplication has the
11813same precedence as the explicit @samp{*} operator. The one exception to
11814the rule is that a variable name followed by a parenthesized expression,
11815as in @samp{f(x)},
11816is interpreted as a function call, not an implicit @samp{*}. In many
11817cases you must use a space if you omit the @samp{*}: @samp{2a} is the
11818same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
11819is a variable called @code{ab}, @emph{not} the product of @samp{a} and
11820@samp{b}! Also note that @samp{f (x)} is still a function call.@refill
11821
11822@cindex Implicit comma in vectors
11823The rules are slightly different for vectors written with square brackets.
11824In vectors, the space character is interpreted (like the comma) as a
11825separator of elements of the vector. Thus @w{@samp{[ 2a b+c d ]}} is
11826equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
11827to @samp{2*a*b + c*d}.
11828Note that spaces around the brackets, and around explicit commas, are
11829ignored. To force spaces to be interpreted as multiplication you can
11830enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
11831interpreted as @samp{[a*b, 2*c*d]}. An implicit comma is also inserted
11832between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.@refill
11833
11834Vectors that contain commas (not embedded within nested parentheses or
11835brackets) do not treat spaces specially: @samp{[a b, 2 c d]} is a vector
11836of two elements. Also, if it would be an error to treat spaces as
11837separators, but not otherwise, then Calc will ignore spaces:
11838@w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
11839a vector of two elements. Finally, vectors entered with curly braces
11840instead of square brackets do not give spaces any special treatment.
11841When Calc displays a vector that does not contain any commas, it will
11842insert parentheses if necessary to make the meaning clear:
11843@w{@samp{[(a b)]}}.
11844
11845The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
11846or five modulo minus-two? Calc always interprets the leftmost symbol as
11847an infix operator preferentially (modulo, in this case), so you would
11848need to write @samp{(5%)-2} to get the former interpretation.
11849
11850@cindex Function call notation
11851A function call is, e.g., @samp{sin(1+x)}. Function names follow the same
11852rules as variable names except that the default prefix @samp{calcFunc-} is
11853used (instead of @samp{var-}) for the internal Lisp form.
11854Most mathematical Calculator commands like
11855@code{calc-sin} have function equivalents like @code{sin}.
11856If no Lisp function is defined for a function called by a formula, the
11857call is left as it is during algebraic manipulation: @samp{f(x+y)} is
11858left alone. Beware that many innocent-looking short names like @code{in}
11859and @code{re} have predefined meanings which could surprise you; however,
11860single letters or single letters followed by digits are always safe to
11861use for your own function names. @xref{Function Index}.@refill
11862
11863In the documentation for particular commands, the notation @kbd{H S}
11864(@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
11865command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
11866represent the same operation.@refill
11867
11868Commands that interpret (``parse'') text as algebraic formulas include
11869algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
11870the contents of the editing buffer when you finish, the @kbd{M-# g}
11871and @w{@kbd{M-# r}} commands, the @kbd{C-y} command, the X window system
11872``paste'' mouse operation, and Embedded Mode. All of these operations
11873use the same rules for parsing formulas; in particular, language modes
11874(@pxref{Language Modes}) affect them all in the same way.
11875
11876When you read a large amount of text into the Calculator (say a vector
11877which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
11878you may wish to include comments in the text. Calc's formula parser
11879ignores the symbol @samp{%%} and anything following it on a line:
11880
11881@example
11882[ a + b, %% the sum of "a" and "b"
11883 c + d,
11884 %% last line is coming up:
11885 e + f ]
11886@end example
11887
11888@noindent
11889This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
11890
11891@xref{Syntax Tables}, for a way to create your own operators and other
11892input notations. @xref{Compositions}, for a way to create new display
11893formats.
11894
11895@xref{Algebra}, for commands for manipulating formulas symbolically.
11896
11897@node Stack and Trail, Mode Settings, Data Types, Top
11898@chapter Stack and Trail Commands
11899
11900@noindent
11901This chapter describes the Calc commands for manipulating objects on the
11902stack and in the trail buffer. (These commands operate on objects of any
11903type, such as numbers, vectors, formulas, and incomplete objects.)
11904
11905@menu
11906* Stack Manipulation::
11907* Editing Stack Entries::
11908* Trail Commands::
11909* Keep Arguments::
11910@end menu
11911
11912@node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
11913@section Stack Manipulation Commands
11914
11915@noindent
11916@kindex RET
11917@kindex SPC
11918@pindex calc-enter
11919@cindex Duplicating stack entries
11920To duplicate the top object on the stack, press @key{RET} or @key{SPC}
11921(two equivalent keys for the @code{calc-enter} command).
11922Given a positive numeric prefix argument, these commands duplicate
11923several elements at the top of the stack.
11924Given a negative argument,
11925these commands duplicate the specified element of the stack.
11926Given an argument of zero, they duplicate the entire stack.
11927For example, with @samp{10 20 30} on the stack,
11928@key{RET} creates @samp{10 20 30 30},
11929@kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
11930@kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
11931@kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.@refill
11932
11933@kindex LFD
11934@pindex calc-over
11935The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
11936have it, else on @kbd{C-j}) is like @code{calc-enter}
11937except that the sign of the numeric prefix argument is interpreted
11938oppositely. Also, with no prefix argument the default argument is 2.
11939Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
11940are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
11941@samp{10 20 30 20}.@refill
11942
11943@kindex DEL
11944@kindex C-d
11945@pindex calc-pop
11946@cindex Removing stack entries
11947@cindex Deleting stack entries
11948To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
11949The @kbd{C-d} key is a synonym for @key{DEL}.
11950(If the top element is an incomplete object with at least one element, the
11951last element is removed from it.) Given a positive numeric prefix argument,
11952several elements are removed. Given a negative argument, the specified
11953element of the stack is deleted. Given an argument of zero, the entire
11954stack is emptied.
11955For example, with @samp{10 20 30} on the stack,
11956@key{DEL} leaves @samp{10 20},
11957@kbd{C-u 2 @key{DEL}} leaves @samp{10},
11958@kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
11959@kbd{C-u 0 @key{DEL}} leaves an empty stack.@refill
11960
11961@kindex M-DEL
11962@pindex calc-pop-above
11963The @key{M-DEL} (@code{calc-pop-above}) command is to @key{DEL} what
11964@key{LFD} is to @key{RET}: It interprets the sign of the numeric
11965prefix argument in the opposite way, and the default argument is 2.
11966Thus @key{M-DEL} by itself removes the second-from-top stack element,
11967leaving the first, third, fourth, and so on; @kbd{M-3 M-DEL} deletes
11968the third stack element.
11969
11970@kindex TAB
11971@pindex calc-roll-down
11972To exchange the top two elements of the stack, press @key{TAB}
11973(@code{calc-roll-down}). Given a positive numeric prefix argument, the
11974specified number of elements at the top of the stack are rotated downward.
11975Given a negative argument, the entire stack is rotated downward the specified
11976number of times. Given an argument of zero, the entire stack is reversed
11977top-for-bottom.
11978For example, with @samp{10 20 30 40 50} on the stack,
11979@key{TAB} creates @samp{10 20 30 50 40},
11980@kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
11981@kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
11982@kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.@refill
11983
11984@kindex M-TAB
11985@pindex calc-roll-up
11986The command @key{M-TAB} (@code{calc-roll-up}) is analogous to @key{TAB}
11987except that it rotates upward instead of downward. Also, the default
11988with no prefix argument is to rotate the top 3 elements.
11989For example, with @samp{10 20 30 40 50} on the stack,
11990@key{M-TAB} creates @samp{10 20 40 50 30},
11991@kbd{C-u 4 @key{M-TAB}} creates @samp{10 30 40 50 20},
11992@kbd{C-u - 2 @key{M-TAB}} creates @samp{30 40 50 10 20}, and
11993@kbd{C-u 0 @key{M-TAB}} creates @samp{50 40 30 20 10}.@refill
11994
11995A good way to view the operation of @key{TAB} and @key{M-TAB} is in
11996terms of moving a particular element to a new position in the stack.
11997With a positive argument @i{n}, @key{TAB} moves the top stack
11998element down to level @i{n}, making room for it by pulling all the
11999intervening stack elements toward the top. @key{M-TAB} moves the
12000element at level @i{n} up to the top. (Compare with @key{LFD},
12001which copies instead of moving the element in level @i{n}.)
12002
12003With a negative argument @i{-n}, @key{TAB} rotates the stack
12004to move the object in level @i{n} to the deepest place in the
12005stack, and the object in level @i{n+1} to the top. @key{M-TAB}
12006rotates the deepest stack element to be in level @i{n}, also
12007putting the top stack element in level @i{n+1}.
12008
12009@xref{Selecting Subformulas}, for a way to apply these commands to
12010any portion of a vector or formula on the stack.
12011
12012@node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
12013@section Editing Stack Entries
12014
12015@noindent
12016@kindex `
12017@pindex calc-edit
12018@pindex calc-edit-finish
12019@cindex Editing the stack with Emacs
12020The backquote, @kbd{`} (@code{calc-edit}) command creates a temporary
12021buffer (@samp{*Calc Edit*}) for editing the top-of-stack value using
12022regular Emacs commands. With a numeric prefix argument, it edits the
12023specified number of stack entries at once. (An argument of zero edits
12024the entire stack; a negative argument edits one specific stack entry.)
12025
12026When you are done editing, press @kbd{M-# M-#} to finish and return
12027to Calc. The @key{RET} and @key{LFD} keys also work to finish most
12028sorts of editing, though in some cases Calc leaves @key{RET} with its
12029usual meaning (``insert a newline'') if it's a situation where you
12030might want to insert new lines into the editing buffer. The traditional
12031Emacs ``finish'' key sequence, @kbd{C-c C-c}, also works to finish
12032editing and may be easier to type, depending on your keyboard.
12033
12034When you finish editing, the Calculator parses the lines of text in
12035the @samp{*Calc Edit*} buffer as numbers or formulas, replaces the
12036original stack elements in the original buffer with these new values,
12037then kills the @samp{*Calc Edit*} buffer. The original Calculator buffer
12038continues to exist during editing, but for best results you should be
12039careful not to change it until you have finished the edit. You can
12040also cancel the edit by pressing @kbd{M-# x}.
12041
12042The formula is normally reevaluated as it is put onto the stack.
12043For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
12044@kbd{M-# M-#} will push 5 on the stack. If you use @key{LFD} to
12045finish, Calc will put the result on the stack without evaluating it.
12046
12047If you give a prefix argument to @kbd{M-# M-#} (or @kbd{C-c C-c}),
12048Calc will not kill the @samp{*Calc Edit*} buffer. You can switch
12049back to that buffer and continue editing if you wish. However, you
12050should understand that if you initiated the edit with @kbd{`}, the
12051@kbd{M-# M-#} operation will be programmed to replace the top of the
12052stack with the new edited value, and it will do this even if you have
12053rearranged the stack in the meanwhile. This is not so much of a problem
12054with other editing commands, though, such as @kbd{s e}
12055(@code{calc-edit-variable}; @pxref{Operations on Variables}).
12056
12057If the @code{calc-edit} command involves more than one stack entry,
12058each line of the @samp{*Calc Edit*} buffer is interpreted as a
12059separate formula. Otherwise, the entire buffer is interpreted as
12060one formula, with line breaks ignored. (You can use @kbd{C-o} or
12061@kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
12062
12063The @kbd{`} key also works during numeric or algebraic entry. The
12064text entered so far is moved to the @code{*Calc Edit*} buffer for
12065more extensive editing than is convenient in the minibuffer.
12066
12067@node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
12068@section Trail Commands
12069
12070@noindent
12071@cindex Trail buffer
12072The commands for manipulating the Calc Trail buffer are two-key sequences
12073beginning with the @kbd{t} prefix.
12074
12075@kindex t d
12076@pindex calc-trail-display
12077The @kbd{t d} (@code{calc-trail-display}) command turns display of the
12078trail on and off. Normally the trail display is toggled on if it was off,
12079off if it was on. With a numeric prefix of zero, this command always
12080turns the trail off; with a prefix of one, it always turns the trail on.
12081The other trail-manipulation commands described here automatically turn
12082the trail on. Note that when the trail is off values are still recorded
12083there; they are simply not displayed. To set Emacs to turn the trail
12084off by default, type @kbd{t d} and then save the mode settings with
12085@kbd{m m} (@code{calc-save-modes}).
12086
12087@kindex t i
12088@pindex calc-trail-in
12089@kindex t o
12090@pindex calc-trail-out
12091The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
12092(@code{calc-trail-out}) commands switch the cursor into and out of the
12093Calc Trail window. In practice they are rarely used, since the commands
12094shown below are a more convenient way to move around in the
12095trail, and they work ``by remote control'' when the cursor is still
12096in the Calculator window.@refill
12097
12098@cindex Trail pointer
12099There is a @dfn{trail pointer} which selects some entry of the trail at
12100any given time. The trail pointer looks like a @samp{>} symbol right
12101before the selected number. The following commands operate on the
12102trail pointer in various ways.
12103
12104@kindex t y
12105@pindex calc-trail-yank
12106@cindex Retrieving previous results
12107The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
12108the trail and pushes it onto the Calculator stack. It allows you to
12109re-use any previously computed value without retyping. With a numeric
12110prefix argument @var{n}, it yanks the value @var{n} lines above the current
12111trail pointer.
12112
12113@kindex t <
12114@pindex calc-trail-scroll-left
12115@kindex t >
12116@pindex calc-trail-scroll-right
12117The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
12118(@code{calc-trail-scroll-right}) commands horizontally scroll the trail
12119window left or right by one half of its width.@refill
12120
12121@kindex t n
12122@pindex calc-trail-next
12123@kindex t p
12124@pindex calc-trail-previous
12125@kindex t f
12126@pindex calc-trail-forward
12127@kindex t b
12128@pindex calc-trail-backward
12129The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
12130(@code{calc-trail-previous)} commands move the trail pointer down or up
12131one line. The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
12132(@code{calc-trail-backward}) commands move the trail pointer down or up
12133one screenful at a time. All of these commands accept numeric prefix
12134arguments to move several lines or screenfuls at a time.@refill
12135
12136@kindex t [
12137@pindex calc-trail-first
12138@kindex t ]
12139@pindex calc-trail-last
12140@kindex t h
12141@pindex calc-trail-here
12142The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
12143(@code{calc-trail-last}) commands move the trail pointer to the first or
12144last line of the trail. The @kbd{t h} (@code{calc-trail-here}) command
12145moves the trail pointer to the cursor position; unlike the other trail
12146commands, @kbd{t h} works only when Calc Trail is the selected window.@refill
12147
12148@kindex t s
12149@pindex calc-trail-isearch-forward
12150@kindex t r
12151@pindex calc-trail-isearch-backward
12152@ifinfo
12153The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12154(@code{calc-trail-isearch-backward}) commands perform an incremental
12155search forward or backward through the trail. You can press @key{RET}
12156to terminate the search; the trail pointer moves to the current line.
12157If you cancel the search with @kbd{C-g}, the trail pointer stays where
12158it was when the search began.@refill
12159@end ifinfo
12160@tex
12161The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12162(@code{calc-trail-isearch-backward}) com\-mands perform an incremental
12163search forward or backward through the trail. You can press @key{RET}
12164to terminate the search; the trail pointer moves to the current line.
12165If you cancel the search with @kbd{C-g}, the trail pointer stays where
12166it was when the search began.
12167@end tex
12168
12169@kindex t m
12170@pindex calc-trail-marker
12171The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
12172line of text of your own choosing into the trail. The text is inserted
12173after the line containing the trail pointer; this usually means it is
12174added to the end of the trail. Trail markers are useful mainly as the
12175targets for later incremental searches in the trail.
12176
12177@kindex t k
12178@pindex calc-trail-kill
12179The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
12180from the trail. The line is saved in the Emacs kill ring suitable for
12181yanking into another buffer, but it is not easy to yank the text back
12182into the trail buffer. With a numeric prefix argument, this command
12183kills the @var{n} lines below or above the selected one.
12184
12185The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
12186elsewhere; @pxref{Vector and Matrix Formats}.
12187
12188@node Keep Arguments, , Trail Commands, Stack and Trail
12189@section Keep Arguments
12190
12191@noindent
12192@kindex K
12193@pindex calc-keep-args
12194The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
12195the following command. It prevents that command from removing its
12196arguments from the stack. For example, after @kbd{2 @key{RET} 3 +},
12197the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
12198the stack contains the arguments and the result: @samp{2 3 5}.
12199
12200This works for all commands that take arguments off the stack. As
12201another example, @kbd{K a s} simplifies a formula, pushing the
12202simplified version of the formula onto the stack after the original
12203formula (rather than replacing the original formula).
12204
12205Note that you could get the same effect by typing @kbd{RET a s},
12206copying the formula and then simplifying the copy. One difference
12207is that for a very large formula the time taken to format the
12208intermediate copy in @kbd{RET a s} could be noticeable; @kbd{K a s}
12209would avoid this extra work.
12210
12211Even stack manipulation commands are affected. @key{TAB} works by
12212popping two values and pushing them back in the opposite order,
12213so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
12214
12215A few Calc commands provide other ways of doing the same thing.
12216For example, @kbd{' sin($)} replaces the number on the stack with
12217its sine using algebraic entry; to push the sine and keep the
12218original argument you could use either @kbd{' sin($1)} or
12219@kbd{K ' sin($)}. @xref{Algebraic Entry}. Also, the @kbd{s s}
12220command is effectively the same as @kbd{K s t}. @xref{Storing Variables}.
12221
12222Keyboard macros may interact surprisingly with the @kbd{K} prefix.
12223If you have defined a keyboard macro to be, say, @samp{Q +} to add
12224one number to the square root of another, then typing @kbd{K X} will
12225execute @kbd{K Q +}, probably not what you expected. The @kbd{K}
12226prefix will apply to just the first command in the macro rather than
12227the whole macro.
12228
12229If you execute a command and then decide you really wanted to keep
12230the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
12231This command pushes the last arguments that were popped by any command
12232onto the stack. Note that the order of things on the stack will be
12233different than with @kbd{K}: @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
12234@samp{5 2 3} on the stack instead of @samp{2 3 5}. @xref{Undo}.
12235
12236@node Mode Settings, Arithmetic, Stack and Trail, Top
12237@chapter Mode Settings
12238
12239@noindent
12240This chapter describes commands that set modes in the Calculator.
12241They do not affect the contents of the stack, although they may change
12242the @emph{appearance} or @emph{interpretation} of the stack's contents.
12243
12244@menu
12245* General Mode Commands::
12246* Precision::
12247* Inverse and Hyperbolic::
12248* Calculation Modes::
12249* Simplification Modes::
12250* Declarations::
12251* Display Modes::
12252* Language Modes::
12253* Modes Variable::
12254* Calc Mode Line::
12255@end menu
12256
12257@node General Mode Commands, Precision, Mode Settings, Mode Settings
12258@section General Mode Commands
12259
12260@noindent
12261@kindex m m
12262@pindex calc-save-modes
12263@cindex Continuous memory
12264@cindex Saving mode settings
12265@cindex Permanent mode settings
12266@cindex @file{.emacs} file, mode settings
12267You can save all of the current mode settings in your @file{.emacs} file
12268with the @kbd{m m} (@code{calc-save-modes}) command. This will cause
12269Emacs to reestablish these modes each time it starts up. The modes saved
12270in the file include everything controlled by the @kbd{m} and @kbd{d}
12271prefix keys, the current precision and binary word size, whether or not
12272the trail is displayed, the current height of the Calc window, and more.
12273The current interface (used when you type @kbd{M-# M-#}) is also saved.
12274If there were already saved mode settings in the file, they are replaced.
12275Otherwise, the new mode information is appended to the end of the file.
12276
12277@kindex m R
12278@pindex calc-mode-record-mode
12279The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
12280record the new mode settings (as if by pressing @kbd{m m}) every
12281time a mode setting changes. If Embedded Mode is enabled, other
12282options are available; @pxref{Mode Settings in Embedded Mode}.
12283
12284@kindex m F
12285@pindex calc-settings-file-name
12286The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
12287choose a different place than your @file{.emacs} file for @kbd{m m},
12288@kbd{Z P}, and similar commands to save permanent information.
12289You are prompted for a file name. All Calc modes are then reset to
12290their default values, then settings from the file you named are loaded
12291if this file exists, and this file becomes the one that Calc will
12292use in the future for commands like @kbd{m m}. The default settings
12293file name is @file{~/.emacs}. You can see the current file name by
12294giving a blank response to the @kbd{m F} prompt. See also the
12295discussion of the @code{calc-settings-file} variable; @pxref{Installation}.
12296
12297If the file name you give contains the string @samp{.emacs} anywhere
12298inside it, @kbd{m F} will not automatically load the new file. This
12299is because you are presumably switching to your @file{~/.emacs} file,
12300which may contain other things you don't want to reread. You can give
12301a numeric prefix argument of 1 to @kbd{m F} to force it to read the
12302file no matter what its name. Conversely, an argument of @i{-1} tells
12303@kbd{m F} @emph{not} to read the new file. An argument of 2 or @i{-2}
12304tells @kbd{m F} not to reset the modes to their defaults beforehand,
12305which is useful if you intend your new file to have a variant of the
12306modes present in the file you were using before.
12307
12308@kindex m x
12309@pindex calc-always-load-extensions
12310The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
12311in which the first use of Calc loads the entire program, including all
12312extensions modules. Otherwise, the extensions modules will not be loaded
12313until the various advanced Calc features are used. Since this mode only
12314has effect when Calc is first loaded, @kbd{m x} is usually followed by
12315@kbd{m m} to make the mode-setting permanent. To load all of Calc just
12316once, rather than always in the future, you can press @kbd{M-# L}.
12317
12318@kindex m S
12319@pindex calc-shift-prefix
12320The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
12321all of Calc's letter prefix keys may be typed shifted as well as unshifted.
12322If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
12323you might find it easier to turn this mode on so that you can type
12324@kbd{A S} instead. When this mode is enabled, the commands that used to
12325be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
12326now be invoked by pressing the shifted letter twice: @kbd{A A}. Note
12327that the @kbd{v} prefix key always works both shifted and unshifted, and
12328the @kbd{z} and @kbd{Z} prefix keys are always distinct. Also, the @kbd{h}
12329prefix is not affected by this mode. Press @kbd{m S} again to disable
12330shifted-prefix mode.
12331
12332@node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
12333@section Precision
12334
12335@noindent
12336@kindex p
12337@pindex calc-precision
12338@cindex Precision of calculations
12339The @kbd{p} (@code{calc-precision}) command controls the precision to
12340which floating-point calculations are carried. The precision must be
12341at least 3 digits and may be arbitrarily high, within the limits of
12342memory and time. This affects only floats: Integer and rational
12343calculations are always carried out with as many digits as necessary.
12344
12345The @kbd{p} key prompts for the current precision. If you wish you
12346can instead give the precision as a numeric prefix argument.
12347
12348Many internal calculations are carried to one or two digits higher
12349precision than normal. Results are rounded down afterward to the
12350current precision. Unless a special display mode has been selected,
12351floats are always displayed with their full stored precision, i.e.,
12352what you see is what you get. Reducing the current precision does not
12353round values already on the stack, but those values will be rounded
12354down before being used in any calculation. The @kbd{c 0} through
12355@kbd{c 9} commands (@pxref{Conversions}) can be used to round an
12356existing value to a new precision.@refill
12357
12358@cindex Accuracy of calculations
12359It is important to distinguish the concepts of @dfn{precision} and
12360@dfn{accuracy}. In the normal usage of these words, the number
12361123.4567 has a precision of 7 digits but an accuracy of 4 digits.
12362The precision is the total number of digits not counting leading
12363or trailing zeros (regardless of the position of the decimal point).
12364The accuracy is simply the number of digits after the decimal point
12365(again not counting trailing zeros). In Calc you control the precision,
12366not the accuracy of computations. If you were to set the accuracy
12367instead, then calculations like @samp{exp(100)} would generate many
12368more digits than you would typically need, while @samp{exp(-100)} would
12369probably round to zero! In Calc, both these computations give you
12370exactly 12 (or the requested number of) significant digits.
12371
12372The only Calc features that deal with accuracy instead of precision
12373are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
12374and the rounding functions like @code{floor} and @code{round}
12375(@pxref{Integer Truncation}). Also, @kbd{c 0} through @kbd{c 9}
12376deal with both precision and accuracy depending on the magnitudes
12377of the numbers involved.
12378
12379If you need to work with a particular fixed accuracy (say, dollars and
12380cents with two digits after the decimal point), one solution is to work
12381with integers and an ``implied'' decimal point. For example, $8.99
12382divided by 6 would be entered @kbd{899 RET 6 /}, yielding 149.833
12383(actually $1.49833 with our implied decimal point); pressing @kbd{R}
12384would round this to 150 cents, i.e., $1.50.
12385
12386@xref{Floats}, for still more on floating-point precision and related
12387issues.
12388
12389@node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
12390@section Inverse and Hyperbolic Flags
12391
12392@noindent
12393@kindex I
12394@pindex calc-inverse
12395There is no single-key equivalent to the @code{calc-arcsin} function.
12396Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
12397the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
12398The @kbd{I} key actually toggles the Inverse Flag. When this flag
12399is set, the word @samp{Inv} appears in the mode line.@refill
12400
12401@kindex H
12402@pindex calc-hyperbolic
12403Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
12404Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
12405If both of these flags are set at once, the effect will be
12406@code{calc-arcsinh}. (The Hyperbolic flag is also used by some
12407non-trigonometric commands; for example @kbd{H L} computes a base-10,
12408instead of base-@i{e}, logarithm.)@refill
12409
12410Command names like @code{calc-arcsin} are provided for completeness, and
12411may be executed with @kbd{x} or @kbd{M-x}. Their effect is simply to
12412toggle the Inverse and/or Hyperbolic flags and then execute the
12413corresponding base command (@code{calc-sin} in this case).
12414
12415The Inverse and Hyperbolic flags apply only to the next Calculator
12416command, after which they are automatically cleared. (They are also
12417cleared if the next keystroke is not a Calc command.) Digits you
12418type after @kbd{I} or @kbd{H} (or @kbd{K}) are treated as prefix
12419arguments for the next command, not as numeric entries. The same
12420is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means to
12421subtract and keep arguments).
12422
12423The third Calc prefix flag, @kbd{K} (keep-arguments), is discussed
12424elsewhere. @xref{Keep Arguments}.
12425
12426@node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
12427@section Calculation Modes
12428
12429@noindent
12430The commands in this section are two-key sequences beginning with
12431the @kbd{m} prefix. (That's the letter @kbd{m}, not the @key{META} key.)
12432The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
12433(@pxref{Algebraic Entry}).
12434
12435@menu
12436* Angular Modes::
12437* Polar Mode::
12438* Fraction Mode::
12439* Infinite Mode::
12440* Symbolic Mode::
12441* Matrix Mode::
12442* Automatic Recomputation::
12443* Working Message::
12444@end menu
12445
12446@node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
12447@subsection Angular Modes
12448
12449@noindent
12450@cindex Angular mode
12451The Calculator supports three notations for angles: radians, degrees,
12452and degrees-minutes-seconds. When a number is presented to a function
12453like @code{sin} that requires an angle, the current angular mode is
12454used to interpret the number as either radians or degrees. If an HMS
12455form is presented to @code{sin}, it is always interpreted as
12456degrees-minutes-seconds.
12457
12458Functions that compute angles produce a number in radians, a number in
12459degrees, or an HMS form depending on the current angular mode. If the
12460result is a complex number and the current mode is HMS, the number is
12461instead expressed in degrees. (Complex-number calculations would
12462normally be done in radians mode, though. Complex numbers are converted
12463to degrees by calculating the complex result in radians and then
12464multiplying by 180 over @c{$\pi$}
12465@cite{pi}.)
12466
12467@kindex m r
12468@pindex calc-radians-mode
12469@kindex m d
12470@pindex calc-degrees-mode
12471@kindex m h
12472@pindex calc-hms-mode
12473The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
12474and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
12475The current angular mode is displayed on the Emacs mode line.
12476The default angular mode is degrees.@refill
12477
12478@node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
12479@subsection Polar Mode
12480
12481@noindent
12482@cindex Polar mode
12483The Calculator normally ``prefers'' rectangular complex numbers in the
12484sense that rectangular form is used when the proper form can not be
12485decided from the input. This might happen by multiplying a rectangular
12486number by a polar one, by taking the square root of a negative real
12487number, or by entering @kbd{( 2 @key{SPC} 3 )}.
12488
12489@kindex m p
12490@pindex calc-polar-mode
12491The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
12492preference between rectangular and polar forms. In polar mode, all
12493of the above example situations would produce polar complex numbers.
12494
12495@node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
12496@subsection Fraction Mode
12497
12498@noindent
12499@cindex Fraction mode
12500@cindex Division of integers
12501Division of two integers normally yields a floating-point number if the
12502result cannot be expressed as an integer. In some cases you would
12503rather get an exact fractional answer. One way to accomplish this is
12504to multiply fractions instead: @kbd{6 @key{RET} 1:4 *} produces @cite{3:2}
12505even though @kbd{6 @key{RET} 4 /} produces @cite{1.5}.
12506
12507@kindex m f
12508@pindex calc-frac-mode
12509To set the Calculator to produce fractional results for normal integer
12510divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
12511For example, @cite{8/4} produces @cite{2} in either mode,
12512but @cite{6/4} produces @cite{3:2} in Fraction Mode, @cite{1.5} in
12513Float Mode.@refill
12514
12515At any time you can use @kbd{c f} (@code{calc-float}) to convert a
12516fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
12517float to a fraction. @xref{Conversions}.
12518
12519@node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
12520@subsection Infinite Mode
12521
12522@noindent
12523@cindex Infinite mode
12524The Calculator normally treats results like @cite{1 / 0} as errors;
12525formulas like this are left in unsimplified form. But Calc can be
12526put into a mode where such calculations instead produce ``infinite''
12527results.
12528
12529@kindex m i
12530@pindex calc-infinite-mode
12531The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
12532on and off. When the mode is off, infinities do not arise except
12533in calculations that already had infinities as inputs. (One exception
12534is that infinite open intervals like @samp{[0 .. inf)} can be
12535generated; however, intervals closed at infinity (@samp{[0 .. inf]})
12536will not be generated when infinite mode is off.)
12537
12538With infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
12539an undirected infinity. @xref{Infinities}, for a discussion of the
12540difference between @code{inf} and @code{uinf}. Also, @cite{0 / 0}
12541evaluates to @code{nan}, the ``indeterminate'' symbol. Various other
12542functions can also return infinities in this mode; for example,
12543@samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}. Once again,
12544note that @samp{exp(inf) = inf} regardless of infinite mode because
12545this calculation has infinity as an input.
12546
12547@cindex Positive infinite mode
12548The @kbd{m i} command with a numeric prefix argument of zero,
12549i.e., @kbd{C-u 0 m i}, turns on a ``positive infinite mode'' in
12550which zero is treated as positive instead of being directionless.
12551Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
12552Note that zero never actually has a sign in Calc; there are no
12553separate representations for @i{+0} and @i{-0}. Positive
12554infinite mode merely changes the interpretation given to the
12555single symbol, @samp{0}. One consequence of this is that, while
12556you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
12557is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
12558
12559@node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
12560@subsection Symbolic Mode
12561
12562@noindent
12563@cindex Symbolic mode
12564@cindex Inexact results
12565Calculations are normally performed numerically wherever possible.
12566For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
12567algebraic expression, produces a numeric answer if the argument is a
12568number or a symbolic expression if the argument is an expression:
12569@kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
12570
12571@kindex m s
12572@pindex calc-symbolic-mode
12573In @dfn{symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
12574command, functions which would produce inexact, irrational results are
12575left in symbolic form. Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
12576@samp{sqrt(2)}.
12577
12578@kindex N
12579@pindex calc-eval-num
12580The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
12581the expression at the top of the stack, by temporarily disabling
12582@code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
12583Given a numeric prefix argument, it also
12584sets the floating-point precision to the specified value for the duration
12585of the command.@refill
12586
12587To evaluate a formula numerically without expanding the variables it
12588contains, you can use the key sequence @kbd{m s a v m s} (this uses
12589@code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
12590variables.)
12591
12592@node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
12593@subsection Matrix and Scalar Modes
12594
12595@noindent
12596@cindex Matrix mode
12597@cindex Scalar mode
12598Calc sometimes makes assumptions during algebraic manipulation that
12599are awkward or incorrect when vectors and matrices are involved.
12600Calc has two modes, @dfn{matrix mode} and @dfn{scalar mode}, which
12601modify its behavior around vectors in useful ways.
12602
12603@kindex m v
12604@pindex calc-matrix-mode
12605Press @kbd{m v} (@code{calc-matrix-mode}) once to enter matrix mode.
12606In this mode, all objects are assumed to be matrices unless provably
12607otherwise. One major effect is that Calc will no longer consider
12608multiplication to be commutative. (Recall that in matrix arithmetic,
12609@samp{A*B} is not the same as @samp{B*A}.) This assumption affects
12610rewrite rules and algebraic simplification. Another effect of this
12611mode is that calculations that would normally produce constants like
126120 and 1 (e.g., @cite{a - a} and @cite{a / a}, respectively) will now
12613produce function calls that represent ``generic'' zero or identity
12614matrices: @samp{idn(0)}, @samp{idn(1)}. The @code{idn} function
12615@samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
12616identity matrix; if @var{n} is omitted, it doesn't know what
12617dimension to use and so the @code{idn} call remains in symbolic
12618form. However, if this generic identity matrix is later combined
12619with a matrix whose size is known, it will be converted into
12620a true identity matrix of the appropriate size. On the other hand,
12621if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
12622will assume it really was a scalar after all and produce, e.g., 3.
12623
12624Press @kbd{m v} a second time to get scalar mode. Here, objects are
12625assumed @emph{not} to be vectors or matrices unless provably so.
12626For example, normally adding a variable to a vector, as in
12627@samp{[x, y, z] + a}, will leave the sum in symbolic form because
12628as far as Calc knows, @samp{a} could represent either a number or
12629another 3-vector. In scalar mode, @samp{a} is assumed to be a
12630non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
12631
12632Press @kbd{m v} a third time to return to the normal mode of operation.
12633
12634If you press @kbd{m v} with a numeric prefix argument @var{n}, you
12635get a special ``dimensioned matrix mode'' in which matrices of
12636unknown size are assumed to be @var{n}x@var{n} square matrices.
12637Then, the function call @samp{idn(1)} will expand into an actual
12638matrix rather than representing a ``generic'' matrix.
12639
12640@cindex Declaring scalar variables
12641Of course these modes are approximations to the true state of
12642affairs, which is probably that some quantities will be matrices
12643and others will be scalars. One solution is to ``declare''
12644certain variables or functions to be scalar-valued.
12645@xref{Declarations}, to see how to make declarations in Calc.
12646
12647There is nothing stopping you from declaring a variable to be
12648scalar and then storing a matrix in it; however, if you do, the
12649results you get from Calc may not be valid. Suppose you let Calc
12650get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
12651@samp{[1, 2, 3]} in @samp{a}. The result would not be the same as
12652for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
12653your earlier promise to Calc that @samp{a} would be scalar.
12654
12655Another way to mix scalars and matrices is to use selections
12656(@pxref{Selecting Subformulas}). Use matrix mode when operating on
12657your formula normally; then, to apply scalar mode to a certain part
12658of the formula without affecting the rest just select that part,
12659change into scalar mode and press @kbd{=} to resimplify the part
12660under this mode, then change back to matrix mode before deselecting.
12661
12662@node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
12663@subsection Automatic Recomputation
12664
12665@noindent
12666The @dfn{evaluates-to} operator, @samp{=>}, has the special
12667property that any @samp{=>} formulas on the stack are recomputed
12668whenever variable values or mode settings that might affect them
12669are changed. @xref{Evaluates-To Operator}.
12670
12671@kindex m C
12672@pindex calc-auto-recompute
12673The @kbd{m C} (@code{calc-auto-recompute}) command turns this
12674automatic recomputation on and off. If you turn it off, Calc will
12675not update @samp{=>} operators on the stack (nor those in the
12676attached Embedded Mode buffer, if there is one). They will not
12677be updated unless you explicitly do so by pressing @kbd{=} or until
12678you press @kbd{m C} to turn recomputation back on. (While automatic
12679recomputation is off, you can think of @kbd{m C m C} as a command
12680to update all @samp{=>} operators while leaving recomputation off.)
12681
12682To update @samp{=>} operators in an Embedded buffer while
12683automatic recomputation is off, use @w{@kbd{M-# u}}.
12684@xref{Embedded Mode}.
12685
12686@node Working Message, , Automatic Recomputation, Calculation Modes
12687@subsection Working Messages
12688
12689@noindent
12690@cindex Performance
12691@cindex Working messages
12692Since the Calculator is written entirely in Emacs Lisp, which is not
12693designed for heavy numerical work, many operations are quite slow.
12694The Calculator normally displays the message @samp{Working...} in the
12695echo area during any command that may be slow. In addition, iterative
12696operations such as square roots and trigonometric functions display the
12697intermediate result at each step. Both of these types of messages can
12698be disabled if you find them distracting.
12699
12700@kindex m w
12701@pindex calc-working
12702Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
12703disable all ``working'' messages. Use a numeric prefix of 1 to enable
12704only the plain @samp{Working...} message. Use a numeric prefix of 2 to
12705see intermediate results as well. With no numeric prefix this displays
12706the current mode.@refill
12707
12708While it may seem that the ``working'' messages will slow Calc down
12709considerably, experiments have shown that their impact is actually
12710quite small. But if your terminal is slow you may find that it helps
12711to turn the messages off.
12712
12713@node Simplification Modes, Declarations, Calculation Modes, Mode Settings
12714@section Simplification Modes
12715
12716@noindent
12717The current @dfn{simplification mode} controls how numbers and formulas
12718are ``normalized'' when being taken from or pushed onto the stack.
12719Some normalizations are unavoidable, such as rounding floating-point
12720results to the current precision, and reducing fractions to simplest
12721form. Others, such as simplifying a formula like @cite{a+a} (or @cite{2+3}),
12722are done by default but can be turned off when necessary.
12723
12724When you press a key like @kbd{+} when @cite{2} and @cite{3} are on the
12725stack, Calc pops these numbers, normalizes them, creates the formula
12726@cite{2+3}, normalizes it, and pushes the result. Of course the standard
12727rules for normalizing @cite{2+3} will produce the result @cite{5}.
12728
12729Simplification mode commands consist of the lower-case @kbd{m} prefix key
12730followed by a shifted letter.
12731
12732@kindex m O
12733@pindex calc-no-simplify-mode
12734The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
12735simplifications. These would leave a formula like @cite{2+3} alone. In
12736fact, nothing except simple numbers are ever affected by normalization
12737in this mode.
12738
12739@kindex m N
12740@pindex calc-num-simplify-mode
12741The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
12742of any formulas except those for which all arguments are constants. For
12743example, @cite{1+2} is simplified to @cite{3}, and @cite{a+(2-2)} is
12744simplified to @cite{a+0} but no further, since one argument of the sum
12745is not a constant. Unfortunately, @cite{(a+2)-2} is @emph{not} simplified
12746because the top-level @samp{-} operator's arguments are not both
12747constant numbers (one of them is the formula @cite{a+2}).
12748A constant is a number or other numeric object (such as a constant
12749error form or modulo form), or a vector all of whose
12750elements are constant.@refill
12751
12752@kindex m D
12753@pindex calc-default-simplify-mode
12754The @kbd{m D} (@code{calc-default-simplify-mode}) command restores the
12755default simplifications for all formulas. This includes many easy and
12756fast algebraic simplifications such as @cite{a+0} to @cite{a}, and
12757@cite{a + 2 a} to @cite{3 a}, as well as evaluating functions like
12758@cite{@t{deriv}(x^2, x)} to @cite{2 x}.
12759
12760@kindex m B
12761@pindex calc-bin-simplify-mode
12762The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the default
12763simplifications to a result and then, if the result is an integer,
12764uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
12765to the current binary word size. @xref{Binary Functions}. Real numbers
12766are rounded to the nearest integer and then clipped; other kinds of
12767results (after the default simplifications) are left alone.
12768
12769@kindex m A
12770@pindex calc-alg-simplify-mode
12771The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does algebraic
12772simplification; it applies all the default simplifications, and also
12773the more powerful (and slower) simplifications made by @kbd{a s}
12774(@code{calc-simplify}). @xref{Algebraic Simplifications}.
12775
12776@kindex m E
12777@pindex calc-ext-simplify-mode
12778The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended''
12779algebraic simplification, as by the @kbd{a e} (@code{calc-simplify-extended})
12780command. @xref{Unsafe Simplifications}.
12781
12782@kindex m U
12783@pindex calc-units-simplify-mode
12784The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
12785simplification; it applies the command @kbd{u s}
12786(@code{calc-simplify-units}), which in turn
12787is a superset of @kbd{a s}. In this mode, variable names which
12788are identifiable as unit names (like @samp{mm} for ``millimeters'')
12789are simplified with their unit definitions in mind.@refill
12790
12791A common technique is to set the simplification mode down to the lowest
12792amount of simplification you will allow to be applied automatically, then
12793use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
12794perform higher types of simplifications on demand. @xref{Algebraic
12795Definitions}, for another sample use of no-simplification mode.@refill
12796
12797@node Declarations, Display Modes, Simplification Modes, Mode Settings
12798@section Declarations
12799
12800@noindent
12801A @dfn{declaration} is a statement you make that promises you will
12802use a certain variable or function in a restricted way. This may
12803give Calc the freedom to do things that it couldn't do if it had to
12804take the fully general situation into account.
12805
12806@menu
12807* Declaration Basics::
12808* Kinds of Declarations::
12809* Functions for Declarations::
12810@end menu
12811
12812@node Declaration Basics, Kinds of Declarations, Declarations, Declarations
12813@subsection Declaration Basics
12814
12815@noindent
12816@kindex s d
12817@pindex calc-declare-variable
12818The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
12819way to make a declaration for a variable. This command prompts for
12820the variable name, then prompts for the declaration. The default
12821at the declaration prompt is the previous declaration, if any.
12822You can edit this declaration, or press @kbd{C-k} to erase it and
12823type a new declaration. (Or, erase it and press @key{RET} to clear
12824the declaration, effectively ``undeclaring'' the variable.)
12825
12826A declaration is in general a vector of @dfn{type symbols} and
12827@dfn{range} values. If there is only one type symbol or range value,
12828you can write it directly rather than enclosing it in a vector.
12829For example, @kbd{s d foo RET real RET} declares @code{foo} to
12830be a real number, and @kbd{s d bar RET [int, const, [1..6]] RET}
12831declares @code{bar} to be a constant integer between 1 and 6.
12832(Actually, you can omit the outermost brackets and Calc will
12833provide them for you: @kbd{s d bar RET int, const, [1..6] RET}.)
12834
12835@cindex @code{Decls} variable
12836@vindex Decls
12837Declarations in Calc are kept in a special variable called @code{Decls}.
12838This variable encodes the set of all outstanding declarations in
12839the form of a matrix. Each row has two elements: A variable or
12840vector of variables declared by that row, and the declaration
12841specifier as described above. You can use the @kbd{s D} command to
12842edit this variable if you wish to see all the declarations at once.
12843@xref{Operations on Variables}, for a description of this command
12844and the @kbd{s p} command that allows you to save your declarations
12845permanently if you wish.
12846
12847Items being declared can also be function calls. The arguments in
12848the call are ignored; the effect is to say that this function returns
12849values of the declared type for any valid arguments. The @kbd{s d}
12850command declares only variables, so if you wish to make a function
12851declaration you will have to edit the @code{Decls} matrix yourself.
12852
12853For example, the declaration matrix
12854
12855@group
12856@smallexample
12857[ [ foo, real ]
12858 [ [j, k, n], int ]
12859 [ f(1,2,3), [0 .. inf) ] ]
12860@end smallexample
12861@end group
12862
12863@noindent
12864declares that @code{foo} represents a real number, @code{j}, @code{k}
12865and @code{n} represent integers, and the function @code{f} always
12866returns a real number in the interval shown.
12867
12868@vindex All
12869If there is a declaration for the variable @code{All}, then that
12870declaration applies to all variables that are not otherwise declared.
12871It does not apply to function names. For example, using the row
12872@samp{[All, real]} says that all your variables are real unless they
12873are explicitly declared without @code{real} in some other row.
12874The @kbd{s d} command declares @code{All} if you give a blank
12875response to the variable-name prompt.
12876
12877@node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
12878@subsection Kinds of Declarations
12879
12880@noindent
12881The type-specifier part of a declaration (that is, the second prompt
12882in the @kbd{s d} command) can be a type symbol, an interval, or a
12883vector consisting of zero or more type symbols followed by zero or
12884more intervals or numbers that represent the set of possible values
12885for the variable.
12886
12887@group
12888@smallexample
12889[ [ a, [1, 2, 3, 4, 5] ]
12890 [ b, [1 .. 5] ]
12891 [ c, [int, 1 .. 5] ] ]
12892@end smallexample
12893@end group
12894
12895Here @code{a} is declared to contain one of the five integers shown;
12896@code{b} is any number in the interval from 1 to 5 (any real number
12897since we haven't specified), and @code{c} is any integer in that
12898interval. Thus the declarations for @code{a} and @code{c} are
12899nearly equivalent (see below).
12900
12901The type-specifier can be the empty vector @samp{[]} to say that
12902nothing is known about a given variable's value. This is the same
12903as not declaring the variable at all except that it overrides any
12904@code{All} declaration which would otherwise apply.
12905
12906The initial value of @code{Decls} is the empty vector @samp{[]}.
12907If @code{Decls} has no stored value or if the value stored in it
12908is not valid, it is ignored and there are no declarations as far
12909as Calc is concerned. (The @kbd{s d} command will replace such a
12910malformed value with a fresh empty matrix, @samp{[]}, before recording
12911the new declaration.) Unrecognized type symbols are ignored.
12912
12913The following type symbols describe what sorts of numbers will be
12914stored in a variable:
12915
12916@table @code
12917@item int
12918Integers.
12919@item numint
12920Numerical integers. (Integers or integer-valued floats.)
12921@item frac
12922Fractions. (Rational numbers which are not integers.)
12923@item rat
12924Rational numbers. (Either integers or fractions.)
12925@item float
12926Floating-point numbers.
12927@item real
12928Real numbers. (Integers, fractions, or floats. Actually,
12929intervals and error forms with real components also count as
12930reals here.)
12931@item pos
12932Positive real numbers. (Strictly greater than zero.)
12933@item nonneg
12934Nonnegative real numbers. (Greater than or equal to zero.)
12935@item number
12936Numbers. (Real or complex.)
12937@end table
12938
12939Calc uses this information to determine when certain simplifications
12940of formulas are safe. For example, @samp{(x^y)^z} cannot be
12941simplified to @samp{x^(y z)} in general; for example,
12942@samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @i{-3}.
12943However, this simplification @emph{is} safe if @code{z} is known
12944to be an integer, or if @code{x} is known to be a nonnegative
12945real number. If you have given declarations that allow Calc to
12946deduce either of these facts, Calc will perform this simplification
12947of the formula.
12948
12949Calc can apply a certain amount of logic when using declarations.
12950For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
12951has been declared @code{int}; Calc knows that an integer times an
12952integer, plus an integer, must always be an integer. (In fact,
12953Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
12954it is able to determine that @samp{2n+1} must be an odd integer.)
12955
12956Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
12957because Calc knows that the @code{abs} function always returns a
12958nonnegative real. If you had a @code{myabs} function that also had
12959this property, you could get Calc to recognize it by adding the row
12960@samp{[myabs(), nonneg]} to the @code{Decls} matrix.
12961
12962One instance of this simplification is @samp{sqrt(x^2)} (since the
12963@code{sqrt} function is effectively a one-half power). Normally
12964Calc leaves this formula alone. After the command
12965@kbd{s d x RET real RET}, however, it can simplify the formula to
12966@samp{abs(x)}. And after @kbd{s d x RET nonneg RET}, Calc can
12967simplify this formula all the way to @samp{x}.
12968
12969If there are any intervals or real numbers in the type specifier,
12970they comprise the set of possible values that the variable or
12971function being declared can have. In particular, the type symbol
12972@code{real} is effectively the same as the range @samp{[-inf .. inf]}
12973(note that infinity is included in the range of possible values);
12974@code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
12975the same as @samp{[0 .. inf]}. Saying @samp{[real, [-5 .. 5]]} is
12976redundant because the fact that the variable is real can be
12977deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
12978@samp{[rat, [-5 .. 5]]} are useful combinations.
12979
12980Note that the vector of intervals or numbers is in the same format
12981used by Calc's set-manipulation commands. @xref{Set Operations}.
12982
12983The type specifier @samp{[1, 2, 3]} is equivalent to
12984@samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
12985In other words, the range of possible values means only that
12986the variable's value must be numerically equal to a number in
12987that range, but not that it must be equal in type as well.
12988Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
12989and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
12990
12991If you use a conflicting combination of type specifiers, the
12992results are unpredictable. An example is @samp{[pos, [0 .. 5]]},
12993where the interval does not lie in the range described by the
12994type symbol.
12995
12996``Real'' declarations mostly affect simplifications involving powers
12997like the one described above. Another case where they are used
12998is in the @kbd{a P} command which returns a list of all roots of a
12999polynomial; if the variable has been declared real, only the real
13000roots (if any) will be included in the list.
13001
13002``Integer'' declarations are used for simplifications which are valid
13003only when certain values are integers (such as @samp{(x^y)^z}
13004shown above).
13005
13006Another command that makes use of declarations is @kbd{a s}, when
13007simplifying equations and inequalities. It will cancel @code{x}
13008from both sides of @samp{a x = b x} only if it is sure @code{x}
13009is non-zero, say, because it has a @code{pos} declaration.
13010To declare specifically that @code{x} is real and non-zero,
13011use @samp{[[-inf .. 0), (0 .. inf]]}. (There is no way in the
13012current notation to say that @code{x} is nonzero but not necessarily
13013real.) The @kbd{a e} command does ``unsafe'' simplifications,
13014including cancelling @samp{x} from the equation when @samp{x} is
13015not known to be nonzero.
13016
13017Another set of type symbols distinguish between scalars and vectors.
13018
13019@table @code
13020@item scalar
13021The value is not a vector.
13022@item vector
13023The value is a vector.
13024@item matrix
13025The value is a matrix (a rectangular vector of vectors).
13026@end table
13027
13028These type symbols can be combined with the other type symbols
13029described above; @samp{[int, matrix]} describes an object which
13030is a matrix of integers.
13031
13032Scalar/vector declarations are used to determine whether certain
13033algebraic operations are safe. For example, @samp{[a, b, c] + x}
13034is normally not simplified to @samp{[a + x, b + x, c + x]}, but
13035it will be if @code{x} has been declared @code{scalar}. On the
13036other hand, multiplication is usually assumed to be commutative,
13037but the terms in @samp{x y} will never be exchanged if both @code{x}
13038and @code{y} are known to be vectors or matrices. (Calc currently
13039never distinguishes between @code{vector} and @code{matrix}
13040declarations.)
13041
13042@xref{Matrix Mode}, for a discussion of ``matrix mode'' and
13043``scalar mode,'' which are similar to declaring @samp{[All, matrix]}
13044or @samp{[All, scalar]} but much more convenient.
13045
13046One more type symbol that is recognized is used with the @kbd{H a d}
13047command for taking total derivatives of a formula. @xref{Calculus}.
13048
13049@table @code
13050@item const
13051The value is a constant with respect to other variables.
13052@end table
13053
13054Calc does not check the declarations for a variable when you store
13055a value in it. However, storing @i{-3.5} in a variable that has
13056been declared @code{pos}, @code{int}, or @code{matrix} may have
13057unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @cite{3.5}
13058if it substitutes the value first, or to @cite{-3.5} if @code{x}
13059was declared @code{pos} and the formula @samp{sqrt(x^2)} is
13060simplified to @samp{x} before the value is substituted. Before
13061using a variable for a new purpose, it is best to use @kbd{s d}
13062or @kbd{s D} to check to make sure you don't still have an old
13063declaration for the variable that will conflict with its new meaning.
13064
13065@node Functions for Declarations, , Kinds of Declarations, Declarations
13066@subsection Functions for Declarations
13067
13068@noindent
13069Calc has a set of functions for accessing the current declarations
13070in a convenient manner. These functions return 1 if the argument
13071can be shown to have the specified property, or 0 if the argument
13072can be shown @emph{not} to have that property; otherwise they are
13073left unevaluated. These functions are suitable for use with rewrite
13074rules (@pxref{Conditional Rewrite Rules}) or programming constructs
13075(@pxref{Conditionals in Macros}). They can be entered only using
13076algebraic notation. @xref{Logical Operations}, for functions
13077that perform other tests not related to declarations.
13078
13079For example, @samp{dint(17)} returns 1 because 17 is an integer, as
13080do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
13081@code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
13082Calc consults knowledge of its own built-in functions as well as your
13083own declarations: @samp{dint(floor(x))} returns 1.
13084
13085@c @starindex
13086@tindex dint
13087@c @starindex
13088@tindex dnumint
13089@c @starindex
13090@tindex dnatnum
13091The @code{dint} function checks if its argument is an integer.
13092The @code{dnatnum} function checks if its argument is a natural
13093number, i.e., a nonnegative integer. The @code{dnumint} function
13094checks if its argument is numerically an integer, i.e., either an
13095integer or an integer-valued float. Note that these and the other
13096data type functions also accept vectors or matrices composed of
13097suitable elements, and that real infinities @samp{inf} and @samp{-inf}
13098are considered to be integers for the purposes of these functions.
13099
13100@c @starindex
13101@tindex drat
13102The @code{drat} function checks if its argument is rational, i.e.,
13103an integer or fraction. Infinities count as rational, but intervals
13104and error forms do not.
13105
13106@c @starindex
13107@tindex dreal
13108The @code{dreal} function checks if its argument is real. This
13109includes integers, fractions, floats, real error forms, and intervals.
13110
13111@c @starindex
13112@tindex dimag
13113The @code{dimag} function checks if its argument is imaginary,
13114i.e., is mathematically equal to a real number times @cite{i}.
13115
13116@c @starindex
13117@tindex dpos
13118@c @starindex
13119@tindex dneg
13120@c @starindex
13121@tindex dnonneg
13122The @code{dpos} function checks for positive (but nonzero) reals.
13123The @code{dneg} function checks for negative reals. The @code{dnonneg}
13124function checks for nonnegative reals, i.e., reals greater than or
13125equal to zero. Note that the @kbd{a s} command can simplify an
13126expression like @cite{x > 0} to 1 or 0 using @code{dpos}, and that
13127@kbd{a s} is effectively applied to all conditions in rewrite rules,
13128so the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
13129are rarely necessary.
13130
13131@c @starindex
13132@tindex dnonzero
13133The @code{dnonzero} function checks that its argument is nonzero.
13134This includes all nonzero real or complex numbers, all intervals that
13135do not include zero, all nonzero modulo forms, vectors all of whose
13136elements are nonzero, and variables or formulas whose values can be
13137deduced to be nonzero. It does not include error forms, since they
13138represent values which could be anything including zero. (This is
13139also the set of objects considered ``true'' in conditional contexts.)
13140
13141@c @starindex
13142@tindex deven
13143@c @starindex
13144@tindex dodd
13145The @code{deven} function returns 1 if its argument is known to be
13146an even integer (or integer-valued float); it returns 0 if its argument
13147is known not to be even (because it is known to be odd or a non-integer).
13148The @kbd{a s} command uses this to simplify a test of the form
13149@samp{x % 2 = 0}. There is also an analogous @code{dodd} function.
13150
13151@c @starindex
13152@tindex drange
13153The @code{drange} function returns a set (an interval or a vector
13154of intervals and/or numbers; @pxref{Set Operations}) that describes
13155the set of possible values of its argument. If the argument is
13156a variable or a function with a declaration, the range is copied
13157from the declaration. Otherwise, the possible signs of the
13158expression are determined using a method similar to @code{dpos},
13159etc., and a suitable set like @samp{[0 .. inf]} is returned. If
13160the expression is not provably real, the @code{drange} function
13161remains unevaluated.
13162
13163@c @starindex
13164@tindex dscalar
13165The @code{dscalar} function returns 1 if its argument is provably
13166scalar, or 0 if its argument is provably non-scalar. It is left
13167unevaluated if this cannot be determined. (If matrix mode or scalar
13168mode are in effect, this function returns 1 or 0, respectively,
13169if it has no other information.) When Calc interprets a condition
13170(say, in a rewrite rule) it considers an unevaluated formula to be
13171``false.'' Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
13172provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
13173is provably non-scalar; both are ``false'' if there is insufficient
13174information to tell.
13175
13176@node Display Modes, Language Modes, Declarations, Mode Settings
13177@section Display Modes
13178
13179@noindent
13180The commands in this section are two-key sequences beginning with the
13181@kbd{d} prefix. The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
13182(@code{calc-line-breaking}) commands are described elsewhere;
13183@pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
13184Display formats for vectors and matrices are also covered elsewhere;
13185@pxref{Vector and Matrix Formats}.@refill
13186
13187One thing all display modes have in common is their treatment of the
13188@kbd{H} prefix. This prefix causes any mode command that would normally
13189refresh the stack to leave the stack display alone. The word ``Dirty''
13190will appear in the mode line when Calc thinks the stack display may not
13191reflect the latest mode settings.
13192
13193@kindex d RET
13194@pindex calc-refresh-top
13195The @kbd{d RET} (@code{calc-refresh-top}) command reformats the
13196top stack entry according to all the current modes. Positive prefix
13197arguments reformat the top @var{n} entries; negative prefix arguments
13198reformat the specified entry, and a prefix of zero is equivalent to
13199@kbd{d SPC} (@code{calc-refresh}), which reformats the entire stack.
13200For example, @kbd{H d s M-2 d RET} changes to scientific notation
13201but reformats only the top two stack entries in the new mode.
13202
13203The @kbd{I} prefix has another effect on the display modes. The mode
13204is set only temporarily; the top stack entry is reformatted according
13205to that mode, then the original mode setting is restored. In other
13206words, @kbd{I d s} is equivalent to @kbd{H d s d RET H d @var{(old mode)}}.
13207
13208@menu
13209* Radix Modes::
13210* Grouping Digits::
13211* Float Formats::
13212* Complex Formats::
13213* Fraction Formats::
13214* HMS Formats::
13215* Date Formats::
13216* Truncating the Stack::
13217* Justification::
13218* Labels::
13219@end menu
13220
13221@node Radix Modes, Grouping Digits, Display Modes, Display Modes
13222@subsection Radix Modes
13223
13224@noindent
13225@cindex Radix display
13226@cindex Non-decimal numbers
13227@cindex Decimal and non-decimal numbers
13228Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
13229notation. Calc can actually display in any radix from two (binary) to 36.
13230When the radix is above 10, the letters @code{A} to @code{Z} are used as
13231digits. When entering such a number, letter keys are interpreted as
13232potential digits rather than terminating numeric entry mode.
13233
13234@kindex d 2
13235@kindex d 8
13236@kindex d 6
13237@kindex d 0
13238@cindex Hexadecimal integers
13239@cindex Octal integers
13240The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
13241binary, octal, hexadecimal, and decimal as the current display radix,
13242respectively. Numbers can always be entered in any radix, though the
13243current radix is used as a default if you press @kbd{#} without any initial
13244digits. A number entered without a @kbd{#} is @emph{always} interpreted
13245as decimal.@refill
13246
13247@kindex d r
13248@pindex calc-radix
13249To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
13250an integer from 2 to 36. You can specify the radix as a numeric prefix
13251argument; otherwise you will be prompted for it.
13252
13253@kindex d z
13254@pindex calc-leading-zeros
13255@cindex Leading zeros
13256Integers normally are displayed with however many digits are necessary to
13257represent the integer and no more. The @kbd{d z} (@code{calc-leading-zeros})
13258command causes integers to be padded out with leading zeros according to the
13259current binary word size. (@xref{Binary Functions}, for a discussion of
13260word size.) If the absolute value of the word size is @cite{w}, all integers
13261are displayed with at least enough digits to represent @c{$2^w-1$}
13262@cite{(2^w)-1} in the
13263current radix. (Larger integers will still be displayed in their entirety.)
13264
13265@node Grouping Digits, Float Formats, Radix Modes, Display Modes
13266@subsection Grouping Digits
13267
13268@noindent
13269@kindex d g
13270@pindex calc-group-digits
13271@cindex Grouping digits
13272@cindex Digit grouping
13273Long numbers can be hard to read if they have too many digits. For
13274example, the factorial of 30 is 33 digits long! Press @kbd{d g}
13275(@code{calc-group-digits}) to enable @dfn{grouping} mode, in which digits
13276are displayed in clumps of 3 or 4 (depending on the current radix)
13277separated by commas.
13278
13279The @kbd{d g} command toggles grouping on and off.
13280With a numerix prefix of 0, this command displays the current state of
13281the grouping flag; with an argument of minus one it disables grouping;
13282with a positive argument @cite{N} it enables grouping on every @cite{N}
13283digits. For floating-point numbers, grouping normally occurs only
13284before the decimal point. A negative prefix argument @cite{-N} enables
13285grouping every @cite{N} digits both before and after the decimal point.@refill
13286
13287@kindex d ,
13288@pindex calc-group-char
13289The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
13290character as the grouping separator. The default is the comma character.
13291If you find it difficult to read vectors of large integers grouped with
13292commas, you may wish to use spaces or some other character instead.
13293This command takes the next character you type, whatever it is, and
13294uses it as the digit separator. As a special case, @kbd{d , \} selects
13295@samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
13296
13297Please note that grouped numbers will not generally be parsed correctly
13298if re-read in textual form, say by the use of @kbd{M-# y} and @kbd{M-# g}.
13299(@xref{Kill and Yank}, for details on these commands.) One exception is
13300the @samp{\,} separator, which doesn't interfere with parsing because it
13301is ignored by @TeX{} language mode.
13302
13303@node Float Formats, Complex Formats, Grouping Digits, Display Modes
13304@subsection Float Formats
13305
13306@noindent
13307Floating-point quantities are normally displayed in standard decimal
13308form, with scientific notation used if the exponent is especially high
13309or low. All significant digits are normally displayed. The commands
13310in this section allow you to choose among several alternative display
13311formats for floats.
13312
13313@kindex d n
13314@pindex calc-normal-notation
13315The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
13316display format. All significant figures in a number are displayed.
13317With a positive numeric prefix, numbers are rounded if necessary to
13318that number of significant digits. With a negative numerix prefix,
13319the specified number of significant digits less than the current
13320precision is used. (Thus @kbd{C-u -2 d n} displays 10 digits if the
13321current precision is 12.)
13322
13323@kindex d f
13324@pindex calc-fix-notation
13325The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
13326notation. The numeric argument is the number of digits after the
13327decimal point, zero or more. This format will relax into scientific
13328notation if a nonzero number would otherwise have been rounded all the
13329way to zero. Specifying a negative number of digits is the same as
13330for a positive number, except that small nonzero numbers will be rounded
13331to zero rather than switching to scientific notation.
13332
13333@kindex d s
13334@pindex calc-sci-notation
13335@cindex Scientific notation, display of
13336The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
13337notation. A positive argument sets the number of significant figures
13338displayed, of which one will be before and the rest after the decimal
13339point. A negative argument works the same as for @kbd{d n} format.
13340The default is to display all significant digits.
13341
13342@kindex d e
13343@pindex calc-eng-notation
13344@cindex Engineering notation, display of
13345The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
13346notation. This is similar to scientific notation except that the
13347exponent is rounded down to a multiple of three, with from one to three
13348digits before the decimal point. An optional numeric prefix sets the
13349number of significant digits to display, as for @kbd{d s}.
13350
13351It is important to distinguish between the current @emph{precision} and
13352the current @emph{display format}. After the commands @kbd{C-u 10 p}
13353and @kbd{C-u 6 d n} the Calculator computes all results to ten
13354significant figures but displays only six. (In fact, intermediate
13355calculations are often carried to one or two more significant figures,
13356but values placed on the stack will be rounded down to ten figures.)
13357Numbers are never actually rounded to the display precision for storage,
13358except by commands like @kbd{C-k} and @kbd{M-# y} which operate on the
13359actual displayed text in the Calculator buffer.
13360
13361@kindex d .
13362@pindex calc-point-char
13363The @kbd{d .} (@code{calc-point-char}) command selects the character used
13364as a decimal point. Normally this is a period; users in some countries
13365may wish to change this to a comma. Note that this is only a display
13366style; on entry, periods must always be used to denote floating-point
13367numbers, and commas to separate elements in a list.
13368
13369@node Complex Formats, Fraction Formats, Float Formats, Display Modes
13370@subsection Complex Formats
13371
13372@noindent
13373@kindex d c
13374@pindex calc-complex-notation
13375There are three supported notations for complex numbers in rectangular
13376form. The default is as a pair of real numbers enclosed in parentheses
13377and separated by a comma: @samp{(a,b)}. The @kbd{d c}
13378(@code{calc-complex-notation}) command selects this style.@refill
13379
13380@kindex d i
13381@pindex calc-i-notation
13382@kindex d j
13383@pindex calc-j-notation
13384The other notations are @kbd{d i} (@code{calc-i-notation}), in which
13385numbers are displayed in @samp{a+bi} form, and @kbd{d j}
13386(@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
13387in some disciplines.@refill
13388
13389@cindex @code{i} variable
13390@vindex i
13391Complex numbers are normally entered in @samp{(a,b)} format.
13392If you enter @samp{2+3i} as an algebraic formula, it will be stored as
13393the formula @samp{2 + 3 * i}. However, if you use @kbd{=} to evaluate
13394this formula and you have not changed the variable @samp{i}, the @samp{i}
13395will be interpreted as @samp{(0,1)} and the formula will be simplified
13396to @samp{(2,3)}. Other commands (like @code{calc-sin}) will @emph{not}
13397interpret the formula @samp{2 + 3 * i} as a complex number.
13398@xref{Variables}, under ``special constants.''@refill
13399
13400@node Fraction Formats, HMS Formats, Complex Formats, Display Modes
13401@subsection Fraction Formats
13402
13403@noindent
13404@kindex d o
13405@pindex calc-over-notation
13406Display of fractional numbers is controlled by the @kbd{d o}
13407(@code{calc-over-notation}) command. By default, a number like
13408eight thirds is displayed in the form @samp{8:3}. The @kbd{d o} command
13409prompts for a one- or two-character format. If you give one character,
13410that character is used as the fraction separator. Common separators are
13411@samp{:} and @samp{/}. (During input of numbers, the @kbd{:} key must be
13412used regardless of the display format; in particular, the @kbd{/} is used
13413for RPN-style division, @emph{not} for entering fractions.)
13414
13415If you give two characters, fractions use ``integer-plus-fractional-part''
13416notation. For example, the format @samp{+/} would display eight thirds
13417as @samp{2+2/3}. If two colons are present in a number being entered,
13418the number is interpreted in this form (so that the entries @kbd{2:2:3}
13419and @kbd{8:3} are equivalent).
13420
13421It is also possible to follow the one- or two-character format with
13422a number. For example: @samp{:10} or @samp{+/3}. In this case,
13423Calc adjusts all fractions that are displayed to have the specified
13424denominator, if possible. Otherwise it adjusts the denominator to
13425be a multiple of the specified value. For example, in @samp{:6} mode
13426the fraction @cite{1:6} will be unaffected, but @cite{2:3} will be
13427displayed as @cite{4:6}, @cite{1:2} will be displayed as @cite{3:6},
13428and @cite{1:8} will be displayed as @cite{3:24}. Integers are also
13429affected by this mode: 3 is displayed as @cite{18:6}. Note that the
13430format @samp{:1} writes fractions the same as @samp{:}, but it writes
13431integers as @cite{n:1}.
13432
13433The fraction format does not affect the way fractions or integers are
13434stored, only the way they appear on the screen. The fraction format
13435never affects floats.
13436
13437@node HMS Formats, Date Formats, Fraction Formats, Display Modes
13438@subsection HMS Formats
13439
13440@noindent
13441@kindex d h
13442@pindex calc-hms-notation
13443The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
13444HMS (hours-minutes-seconds) forms. It prompts for a string which
13445consists basically of an ``hours'' marker, optional punctuation, a
13446``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
13447Punctuation is zero or more spaces, commas, or semicolons. The hours
13448marker is one or more non-punctuation characters. The minutes and
13449seconds markers must be single non-punctuation characters.
13450
13451The default HMS format is @samp{@@ ' "}, producing HMS values of the form
13452@samp{23@@ 30' 15.75"}. The format @samp{deg, ms} would display this same
13453value as @samp{23deg, 30m15.75s}. During numeric entry, the @kbd{h} or @kbd{o}
13454keys are recognized as synonyms for @kbd{@@} regardless of display format.
13455The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
13456@kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
13457already been typed; otherwise, they have their usual meanings
13458(@kbd{m-} prefix and @kbd{s-} prefix). Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
13459@kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
13460The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
13461@kbd{o}) has already been pressed; otherwise it means to switch to algebraic
13462entry.
13463
13464@node Date Formats, Truncating the Stack, HMS Formats, Display Modes
13465@subsection Date Formats
13466
13467@noindent
13468@kindex d d
13469@pindex calc-date-notation
13470The @kbd{d d} (@code{calc-date-notation}) command controls the display
13471of date forms (@pxref{Date Forms}). It prompts for a string which
13472contains letters that represent the various parts of a date and time.
13473To show which parts should be omitted when the form represents a pure
13474date with no time, parts of the string can be enclosed in @samp{< >}
13475marks. If you don't include @samp{< >} markers in the format, Calc
13476guesses at which parts, if any, should be omitted when formatting
13477pure dates.
13478
13479The default format is: @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
13480An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
13481If you enter a blank format string, this default format is
13482reestablished.
13483
13484Calc uses @samp{< >} notation for nameless functions as well as for
13485dates. @xref{Specifying Operators}. To avoid confusion with nameless
13486functions, your date formats should avoid using the @samp{#} character.
13487
13488@menu
13489* Date Formatting Codes::
13490* Free-Form Dates::
13491* Standard Date Formats::
13492@end menu
13493
13494@node Date Formatting Codes, Free-Form Dates, Date Formats, Date Formats
13495@subsubsection Date Formatting Codes
13496
13497@noindent
13498When displaying a date, the current date format is used. All
13499characters except for letters and @samp{<} and @samp{>} are
13500copied literally when dates are formatted. The portion between
13501@samp{< >} markers is omitted for pure dates, or included for
13502date/time forms. Letters are interpreted according to the table
13503below.
13504
13505When dates are read in during algebraic entry, Calc first tries to
13506match the input string to the current format either with or without
13507the time part. The punctuation characters (including spaces) must
13508match exactly; letter fields must correspond to suitable text in
13509the input. If this doesn't work, Calc checks if the input is a
13510simple number; if so, the number is interpreted as a number of days
13511since Jan 1, 1 AD. Otherwise, Calc tries a much more relaxed and
13512flexible algorithm which is described in the next section.
13513
13514Weekday names are ignored during reading.
13515
13516Two-digit year numbers are interpreted as lying in the range
13517from 1941 to 2039. Years outside that range are always
13518entered and displayed in full. Year numbers with a leading
13519@samp{+} sign are always interpreted exactly, allowing the
13520entry and display of the years 1 through 99 AD.
13521
13522Here is a complete list of the formatting codes for dates:
13523
13524@table @asis
13525@item Y
13526Year: ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
13527@item YY
13528Year: ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
13529@item BY
13530Year: ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
13531@item YYY
13532Year: ``1991'' for 1991, ``23'' for 23 AD.
13533@item YYYY
13534Year: ``1991'' for 1991, ``+23'' for 23 AD.
13535@item aa
13536Year: ``ad'' or blank.
13537@item AA
13538Year: ``AD'' or blank.
13539@item aaa
13540Year: ``ad '' or blank. (Note trailing space.)
13541@item AAA
13542Year: ``AD '' or blank.
13543@item aaaa
13544Year: ``a.d.'' or blank.
13545@item AAAA
13546Year: ``A.D.'' or blank.
13547@item bb
13548Year: ``bc'' or blank.
13549@item BB
13550Year: ``BC'' or blank.
13551@item bbb
13552Year: `` bc'' or blank. (Note leading space.)
13553@item BBB
13554Year: `` BC'' or blank.
13555@item bbbb
13556Year: ``b.c.'' or blank.
13557@item BBBB
13558Year: ``B.C.'' or blank.
13559@item M
13560Month: ``8'' for August.
13561@item MM
13562Month: ``08'' for August.
13563@item BM
13564Month: `` 8'' for August.
13565@item MMM
13566Month: ``AUG'' for August.
13567@item Mmm
13568Month: ``Aug'' for August.
13569@item mmm
13570Month: ``aug'' for August.
13571@item MMMM
13572Month: ``AUGUST'' for August.
13573@item Mmmm
13574Month: ``August'' for August.
13575@item D
13576Day: ``7'' for 7th day of month.
13577@item DD
13578Day: ``07'' for 7th day of month.
13579@item BD
13580Day: `` 7'' for 7th day of month.
13581@item W
13582Weekday: ``0'' for Sunday, ``6'' for Saturday.
13583@item WWW
13584Weekday: ``SUN'' for Sunday.
13585@item Www
13586Weekday: ``Sun'' for Sunday.
13587@item www
13588Weekday: ``sun'' for Sunday.
13589@item WWWW
13590Weekday: ``SUNDAY'' for Sunday.
13591@item Wwww
13592Weekday: ``Sunday'' for Sunday.
13593@item d
13594Day of year: ``34'' for Feb. 3.
13595@item ddd
13596Day of year: ``034'' for Feb. 3.
13597@item bdd
13598Day of year: `` 34'' for Feb. 3.
13599@item h
13600Hour: ``5'' for 5 AM; ``17'' for 5 PM.
13601@item hh
13602Hour: ``05'' for 5 AM; ``17'' for 5 PM.
13603@item bh
13604Hour: `` 5'' for 5 AM; ``17'' for 5 PM.
13605@item H
13606Hour: ``5'' for 5 AM and 5 PM.
13607@item HH
13608Hour: ``05'' for 5 AM and 5 PM.
13609@item BH
13610Hour: `` 5'' for 5 AM and 5 PM.
13611@item p
13612AM/PM: ``a'' or ``p''.
13613@item P
13614AM/PM: ``A'' or ``P''.
13615@item pp
13616AM/PM: ``am'' or ``pm''.
13617@item PP
13618AM/PM: ``AM'' or ``PM''.
13619@item pppp
13620AM/PM: ``a.m.'' or ``p.m.''.
13621@item PPPP
13622AM/PM: ``A.M.'' or ``P.M.''.
13623@item m
13624Minutes: ``7'' for 7.
13625@item mm
13626Minutes: ``07'' for 7.
13627@item bm
13628Minutes: `` 7'' for 7.
13629@item s
13630Seconds: ``7'' for 7; ``7.23'' for 7.23.
13631@item ss
13632Seconds: ``07'' for 7; ``07.23'' for 7.23.
13633@item bs
13634Seconds: `` 7'' for 7; `` 7.23'' for 7.23.
13635@item SS
13636Optional seconds: ``07'' for 7; blank for 0.
13637@item BS
13638Optional seconds: `` 7'' for 7; blank for 0.
13639@item N
13640Numeric date/time: ``726842.25'' for 6:00am Wed Jan 9, 1991.
13641@item n
13642Numeric date: ``726842'' for any time on Wed Jan 9, 1991.
13643@item J
13644Julian date/time: ``2448265.75'' for 6:00am Wed Jan 9, 1991.
13645@item j
13646Julian date: ``2448266'' for any time on Wed Jan 9, 1991.
13647@item U
13648Unix time: ``663400800'' for 6:00am Wed Jan 9, 1991.
13649@item X
13650Brackets suppression. An ``X'' at the front of the format
13651causes the surrounding @w{@samp{< >}} delimiters to be omitted
13652when formatting dates. Note that the brackets are still
13653required for algebraic entry.
13654@end table
13655
13656If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
13657colon is also omitted if the seconds part is zero.
13658
13659If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
13660appear in the format, then negative year numbers are displayed
13661without a minus sign. Note that ``aa'' and ``bb'' are mutually
13662exclusive. Some typical usages would be @samp{YYYY AABB};
13663@samp{AAAYYYYBBB}; @samp{YYYYBBB}.
13664
13665The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
13666``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
13667reading unless several of these codes are strung together with no
13668punctuation in between, in which case the input must have exactly as
13669many digits as there are letters in the format.
13670
13671The ``j,'' ``J,'' and ``U'' formats do not make any time zone
13672adjustment. They effectively use @samp{julian(x,0)} and
13673@samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
13674
13675@node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
13676@subsubsection Free-Form Dates
13677
13678@noindent
13679When reading a date form during algebraic entry, Calc falls back
13680on the algorithm described here if the input does not exactly
13681match the current date format. This algorithm generally
13682``does the right thing'' and you don't have to worry about it,
13683but it is described here in full detail for the curious.
13684
13685Calc does not distinguish between upper- and lower-case letters
13686while interpreting dates.
13687
13688First, the time portion, if present, is located somewhere in the
13689text and then removed. The remaining text is then interpreted as
13690the date.
13691
13692A time is of the form @samp{hh:mm:ss}, possibly with the seconds
13693part omitted and possibly with an AM/PM indicator added to indicate
1369412-hour time. If the AM/PM is present, the minutes may also be
13695omitted. The AM/PM part may be any of the words @samp{am},
13696@samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
13697abbreviated to one letter, and the alternate forms @samp{a.m.},
13698@samp{p.m.}, and @samp{mid} are also understood. Obviously
13699@samp{noon} and @samp{midnight} are allowed only on 12:00:00.
13700The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
13701recognized with no number attached.
13702
13703If there is no AM/PM indicator, the time is interpreted in 24-hour
13704format.
13705
13706To read the date portion, all words and numbers are isolated
13707from the string; other characters are ignored. All words must
13708be either month names or day-of-week names (the latter of which
13709are ignored). Names can be written in full or as three-letter
13710abbreviations.
13711
13712Large numbers, or numbers with @samp{+} or @samp{-} signs,
13713are interpreted as years. If one of the other numbers is
13714greater than 12, then that must be the day and the remaining
13715number in the input is therefore the month. Otherwise, Calc
13716assumes the month, day and year are in the same order that they
13717appear in the current date format. If the year is omitted, the
13718current year is taken from the system clock.
13719
13720If there are too many or too few numbers, or any unrecognizable
13721words, then the input is rejected.
13722
13723If there are any large numbers (of five digits or more) other than
13724the year, they are ignored on the assumption that they are something
13725like Julian dates that were included along with the traditional
13726date components when the date was formatted.
13727
13728One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
13729may optionally be used; the latter two are equivalent to a
13730minus sign on the year value.
13731
13732If you always enter a four-digit year, and use a name instead
13733of a number for the month, there is no danger of ambiguity.
13734
13735@node Standard Date Formats, , Free-Form Dates, Date Formats
13736@subsubsection Standard Date Formats
13737
13738@noindent
13739There are actually ten standard date formats, numbered 0 through 9.
13740Entering a blank line at the @kbd{d d} command's prompt gives
13741you format number 1, Calc's usual format. You can enter any digit
13742to select the other formats.
13743
13744To create your own standard date formats, give a numeric prefix
13745argument from 0 to 9 to the @w{@kbd{d d}} command. The format you
13746enter will be recorded as the new standard format of that
13747number, as well as becoming the new current date format.
13748You can save your formats permanently with the @w{@kbd{m m}}
13749command (@pxref{Mode Settings}).
13750
13751@table @asis
13752@item 0
13753@samp{N} (Numerical format)
13754@item 1
13755@samp{<H:mm:SSpp >Www Mmm D, YYYY} (American format)
13756@item 2
13757@samp{D Mmm YYYY<, h:mm:SS>} (European format)
13758@item 3
13759@samp{Www Mmm BD< hh:mm:ss> YYYY} (Unix written date format)
13760@item 4
13761@samp{M/D/Y< H:mm:SSpp>} (American slashed format)
13762@item 5
13763@samp{D.M.Y< h:mm:SS>} (European dotted format)
13764@item 6
13765@samp{M-D-Y< H:mm:SSpp>} (American dashed format)
13766@item 7
13767@samp{D-M-Y< h:mm:SS>} (European dashed format)
13768@item 8
13769@samp{j<, h:mm:ss>} (Julian day plus time)
13770@item 9
13771@samp{YYddd< hh:mm:ss>} (Year-day format)
13772@end table
13773
13774@node Truncating the Stack, Justification, Date Formats, Display Modes
13775@subsection Truncating the Stack
13776
13777@noindent
13778@kindex d t
13779@pindex calc-truncate-stack
13780@cindex Truncating the stack
13781@cindex Narrowing the stack
13782The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
13783line that marks the top-of-stack up or down in the Calculator buffer.
13784The number right above that line is considered to the be at the top of
13785the stack. Any numbers below that line are ``hidden'' from all stack
13786operations. This is similar to the Emacs ``narrowing'' feature, except
13787that the values below the @samp{.} are @emph{visible}, just temporarily
13788frozen. This feature allows you to keep several independent calculations
13789running at once in different parts of the stack, or to apply a certain
13790command to an element buried deep in the stack.@refill
13791
13792Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
13793is on. Thus, this line and all those below it become hidden. To un-hide
13794these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
13795With a positive numeric prefix argument @cite{n}, @kbd{d t} hides the
13796bottom @cite{n} values in the buffer. With a negative argument, it hides
13797all but the top @cite{n} values. With an argument of zero, it hides zero
13798values, i.e., moves the @samp{.} all the way down to the bottom.@refill
13799
13800@kindex d [
13801@pindex calc-truncate-up
13802@kindex d ]
13803@pindex calc-truncate-down
13804The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
13805(@code{calc-truncate-down}) commands move the @samp{.} up or down one
13806line at a time (or several lines with a prefix argument).@refill
13807
13808@node Justification, Labels, Truncating the Stack, Display Modes
13809@subsection Justification
13810
13811@noindent
13812@kindex d <
13813@pindex calc-left-justify
13814@kindex d =
13815@pindex calc-center-justify
13816@kindex d >
13817@pindex calc-right-justify
13818Values on the stack are normally left-justified in the window. You can
13819control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
13820@kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
13821(@code{calc-center-justify}). For example, in right-justification mode,
13822stack entries are displayed flush-right against the right edge of the
13823window.@refill
13824
13825If you change the width of the Calculator window you may have to type
13826@kbd{d SPC} (@code{calc-refresh}) to re-align right-justified or centered
13827text.
13828
13829Right-justification is especially useful together with fixed-point
13830notation (see @code{d f}; @code{calc-fix-notation}). With these modes
13831together, the decimal points on numbers will always line up.
13832
13833With a numeric prefix argument, the justification commands give you
13834a little extra control over the display. The argument specifies the
13835horizontal ``origin'' of a display line. It is also possible to
13836specify a maximum line width using the @kbd{d b} command (@pxref{Normal
13837Language Modes}). For reference, the precise rules for formatting and
13838breaking lines are given below. Notice that the interaction between
13839origin and line width is slightly different in each justification
13840mode.
13841
13842In left-justified mode, the line is indented by a number of spaces
13843given by the origin (default zero). If the result is longer than the
13844maximum line width, if given, or too wide to fit in the Calc window
13845otherwise, then it is broken into lines which will fit; each broken
13846line is indented to the origin.
13847
13848In right-justified mode, lines are shifted right so that the rightmost
13849character is just before the origin, or just before the current
13850window width if no origin was specified. If the line is too long
13851for this, then it is broken; the current line width is used, if
13852specified, or else the origin is used as a width if that is
13853specified, or else the line is broken to fit in the window.
13854
13855In centering mode, the origin is the column number of the center of
13856each stack entry. If a line width is specified, lines will not be
13857allowed to go past that width; Calc will either indent less or
13858break the lines if necessary. If no origin is specified, half the
13859line width or Calc window width is used.
13860
13861Note that, in each case, if line numbering is enabled the display
13862is indented an additional four spaces to make room for the line
13863number. The width of the line number is taken into account when
13864positioning according to the current Calc window width, but not
13865when positioning by explicit origins and widths. In the latter
13866case, the display is formatted as specified, and then uniformly
13867shifted over four spaces to fit the line numbers.
13868
13869@node Labels, , Justification, Display Modes
13870@subsection Labels
13871
13872@noindent
13873@kindex d @{
13874@pindex calc-left-label
13875The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
13876then displays that string to the left of every stack entry. If the
13877entries are left-justified (@pxref{Justification}), then they will
13878appear immediately after the label (unless you specified an origin
13879greater than the length of the label). If the entries are centered
13880or right-justified, the label appears on the far left and does not
13881affect the horizontal position of the stack entry.
13882
13883Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
13884
13885@kindex d @}
13886@pindex calc-right-label
13887The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
13888label on the righthand side. It does not affect positioning of
13889the stack entries unless they are right-justified. Also, if both
13890a line width and an origin are given in right-justified mode, the
13891stack entry is justified to the origin and the righthand label is
13892justified to the line width.
13893
13894One application of labels would be to add equation numbers to
13895formulas you are manipulating in Calc and then copying into a
13896document (possibly using Embedded Mode). The equations would
13897typically be centered, and the equation numbers would be on the
13898left or right as you prefer.
13899
13900@node Language Modes, Modes Variable, Display Modes, Mode Settings
13901@section Language Modes
13902
13903@noindent
13904The commands in this section change Calc to use a different notation for
13905entry and display of formulas, corresponding to the conventions of some
13906other common language such as Pascal or @TeX{}. Objects displayed on the
13907stack or yanked from the Calculator to an editing buffer will be formatted
13908in the current language; objects entered in algebraic entry or yanked from
13909another buffer will be interpreted according to the current language.
13910
13911The current language has no effect on things written to or read from the
13912trail buffer, nor does it affect numeric entry. Only algebraic entry is
13913affected. You can make even algebraic entry ignore the current language
13914and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
13915
13916For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
13917program; elsewhere in the program you need the derivatives of this formula
13918with respect to @samp{a[1]} and @samp{a[2]}. First, type @kbd{d C}
13919to switch to C notation. Now use @code{C-u M-# g} to grab the formula
13920into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
13921to the first variable, and @kbd{M-# y} to yank the formula for the derivative
13922back into your C program. Press @kbd{U} to undo the differentiation and
13923repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
13924
13925Without being switched into C mode first, Calc would have misinterpreted
13926the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
13927@code{atan} was equivalent to Calc's built-in @code{arctan} function,
13928and would have written the formula back with notations (like implicit
13929multiplication) which would not have been legal for a C program.
13930
13931As another example, suppose you are maintaining a C program and a @TeX{}
13932document, each of which needs a copy of the same formula. You can grab the
13933formula from the program in C mode, switch to @TeX{} mode, and yank the
13934formula into the document in @TeX{} math-mode format.
13935
13936Language modes are selected by typing the letter @kbd{d} followed by a
13937shifted letter key.
13938
13939@menu
13940* Normal Language Modes::
13941* C FORTRAN Pascal::
13942* TeX Language Mode::
13943* Eqn Language Mode::
13944* Mathematica Language Mode::
13945* Maple Language Mode::
13946* Compositions::
13947* Syntax Tables::
13948@end menu
13949
13950@node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
13951@subsection Normal Language Modes
13952
13953@noindent
13954@kindex d N
13955@pindex calc-normal-language
13956The @kbd{d N} (@code{calc-normal-language}) command selects the usual
13957notation for Calc formulas, as described in the rest of this manual.
13958Matrices are displayed in a multi-line tabular format, but all other
13959objects are written in linear form, as they would be typed from the
13960keyboard.
13961
13962@kindex d O
13963@pindex calc-flat-language
13964@cindex Matrix display
13965The @kbd{d O} (@code{calc-flat-language}) command selects a language
13966identical with the normal one, except that matrices are written in
13967one-line form along with everything else. In some applications this
13968form may be more suitable for yanking data into other buffers.
13969
13970@kindex d b
13971@pindex calc-line-breaking
13972@cindex Line breaking
13973@cindex Breaking up long lines
13974Even in one-line mode, long formulas or vectors will still be split
13975across multiple lines if they exceed the width of the Calculator window.
13976The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
13977feature on and off. (It works independently of the current language.)
13978If you give a numeric prefix argument of five or greater to the @kbd{d b}
13979command, that argument will specify the line width used when breaking
13980long lines.
13981
13982@kindex d B
13983@pindex calc-big-language
13984The @kbd{d B} (@code{calc-big-language}) command selects a language
13985which uses textual approximations to various mathematical notations,
13986such as powers, quotients, and square roots:
13987
13988@example
13989 ____________
13990 | a + 1 2
13991 | ----- + c
13992\| b
13993@end example
13994
13995@noindent
13996in place of @samp{sqrt((a+1)/b + c^2)}.
13997
13998Subscripts like @samp{a_i} are displayed as actual subscripts in ``big''
13999mode. Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
14000are displayed as @samp{a} with subscripts separated by commas:
14001@samp{i, j}. They must still be entered in the usual underscore
14002notation.
14003
14004One slight ambiguity of Big notation is that
14005
14006@example
14007 3
14008- -
14009 4
14010@end example
14011
14012@noindent
14013can represent either the negative rational number @cite{-3:4}, or the
14014actual expression @samp{-(3/4)}; but the latter formula would normally
14015never be displayed because it would immediately be evaluated to
14016@cite{-3:4} or @cite{-0.75}, so this ambiguity is not a problem in
14017typical use.
14018
14019Non-decimal numbers are displayed with subscripts. Thus there is no
14020way to tell the difference between @samp{16#C2} and @samp{C2_16},
14021though generally you will know which interpretation is correct.
14022Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
14023in Big mode.
14024
14025In Big mode, stack entries often take up several lines. To aid
14026readability, stack entries are separated by a blank line in this mode.
14027You may find it useful to expand the Calc window's height using
14028@kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
14029one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
14030
14031Long lines are currently not rearranged to fit the window width in
14032Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
14033to scroll across a wide formula. For really big formulas, you may
14034even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
14035
14036@kindex d U
14037@pindex calc-unformatted-language
14038The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
14039the use of operator notation in formulas. In this mode, the formula
14040shown above would be displayed:
14041
14042@example
14043sqrt(add(div(add(a, 1), b), pow(c, 2)))
14044@end example
14045
14046These four modes differ only in display format, not in the format
14047expected for algebraic entry. The standard Calc operators work in
14048all four modes, and unformatted notation works in any language mode
14049(except that Mathematica mode expects square brackets instead of
14050parentheses).
14051
14052@node C FORTRAN Pascal, TeX Language Mode, Normal Language Modes, Language Modes
14053@subsection C, FORTRAN, and Pascal Modes
14054
14055@noindent
14056@kindex d C
14057@pindex calc-c-language
14058@cindex C language
14059The @kbd{d C} (@code{calc-c-language}) command selects the conventions
14060of the C language for display and entry of formulas. This differs from
14061the normal language mode in a variety of (mostly minor) ways. In
14062particular, C language operators and operator precedences are used in
14063place of Calc's usual ones. For example, @samp{a^b} means @samp{xor(a,b)}
14064in C mode; a value raised to a power is written as a function call,
14065@samp{pow(a,b)}.
14066
14067In C mode, vectors and matrices use curly braces instead of brackets.
14068Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
14069rather than using the @samp{#} symbol. Array subscripting is
14070translated into @code{subscr} calls, so that @samp{a[i]} in C
14071mode is the same as @samp{a_i} in normal mode. Assignments
14072turn into the @code{assign} function, which Calc normally displays
14073using the @samp{:=} symbol.
14074
14075The variables @code{var-pi} and @code{var-e} would be displayed @samp{pi}
14076and @samp{e} in normal mode, but in C mode they are displayed as
14077@samp{M_PI} and @samp{M_E}, corresponding to the names of constants
14078typically provided in the @file{<math.h>} header. Functions whose
14079names are different in C are translated automatically for entry and
14080display purposes. For example, entering @samp{asin(x)} will push the
14081formula @samp{arcsin(x)} onto the stack; this formula will be displayed
14082as @samp{asin(x)} as long as C mode is in effect.
14083
14084@kindex d P
14085@pindex calc-pascal-language
14086@cindex Pascal language
14087The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
14088conventions. Like C mode, Pascal mode interprets array brackets and uses
14089a different table of operators. Hexadecimal numbers are entered and
14090displayed with a preceding dollar sign. (Thus the regular meaning of
14091@kbd{$2} during algebraic entry does not work in Pascal mode, though
14092@kbd{$} (and @kbd{$$}, etc.) not followed by digits works the same as
14093always.) No special provisions are made for other non-decimal numbers,
14094vectors, and so on, since there is no universally accepted standard way
14095of handling these in Pascal.
14096
14097@kindex d F
14098@pindex calc-fortran-language
14099@cindex FORTRAN language
14100The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
14101conventions. Various function names are transformed into FORTRAN
14102equivalents. Vectors are written as @samp{/1, 2, 3/}, and may be
14103entered this way or using square brackets. Since FORTRAN uses round
14104parentheses for both function calls and array subscripts, Calc displays
14105both in the same way; @samp{a(i)} is interpreted as a function call
14106upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
14107Also, if the variable @code{a} has been declared to have type
14108@code{vector} or @code{matrix} then @samp{a(i)} will be parsed as a
14109subscript. (@xref{Declarations}.) Usually it doesn't matter, though;
14110if you enter the subscript expression @samp{a(i)} and Calc interprets
14111it as a function call, you'll never know the difference unless you
14112switch to another language mode or replace @code{a} with an actual
14113vector (or unless @code{a} happens to be the name of a built-in
14114function!).
14115
14116Underscores are allowed in variable and function names in all of these
14117language modes. The underscore here is equivalent to the @samp{#} in
14118normal mode, or to hyphens in the underlying Emacs Lisp variable names.
14119
14120FORTRAN and Pascal modes normally do not adjust the case of letters in
14121formulas. Most built-in Calc names use lower-case letters. If you use a
14122positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
14123modes will use upper-case letters exclusively for display, and will
14124convert to lower-case on input. With a negative prefix, these modes
14125convert to lower-case for display and input.
14126
14127@node TeX Language Mode, Eqn Language Mode, C FORTRAN Pascal, Language Modes
14128@subsection @TeX{} Language Mode
14129
14130@noindent
14131@kindex d T
14132@pindex calc-tex-language
14133@cindex TeX language
14134The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
14135of ``math mode'' in the @TeX{} typesetting language, by Donald Knuth.
14136Formulas are entered
14137and displayed in @TeX{} notation, as in @samp{\sin\left( a \over b \right)}.
14138Math formulas are usually enclosed by @samp{$ $} signs in @TeX{}; these
14139should be omitted when interfacing with Calc. To Calc, the @samp{$} sign
14140has the same meaning it always does in algebraic formulas (a reference to
14141an existing entry on the stack).@refill
14142
14143Complex numbers are displayed as in @samp{3 + 4i}. Fractions and
14144quotients are written using @code{\over};
14145binomial coefficients are written with @code{\choose}.
14146Interval forms are written with @code{\ldots}, and
14147error forms are written with @code{\pm}.
14148Absolute values are written as in @samp{|x + 1|}, and the floor and
14149ceiling functions are written with @code{\lfloor}, @code{\rfloor}, etc.
14150The words @code{\left} and @code{\right} are ignored when reading
14151formulas in @TeX{} mode. Both @code{inf} and @code{uinf} are written
14152as @code{\infty}; when read, @code{\infty} always translates to
14153@code{inf}.@refill
14154
14155Function calls are written the usual way, with the function name followed
14156by the arguments in parentheses. However, functions for which @TeX{} has
14157special names (like @code{\sin}) will use curly braces instead of
14158parentheses for very simple arguments. During input, curly braces and
14159parentheses work equally well for grouping, but when the document is
14160formatted the curly braces will be invisible. Thus the printed result is
14161@c{$\sin{2 x}$}
14162@cite{sin 2x} but @c{$\sin(2 + x)$}
14163@cite{sin(2 + x)}.
14164
14165Function and variable names not treated specially by @TeX{} are simply
14166written out as-is, which will cause them to come out in italic letters
14167in the printed document. If you invoke @kbd{d T} with a positive numeric
14168prefix argument, names of more than one character will instead be written
14169@samp{\hbox@{@var{name}@}}. The @samp{\hbox@{ @}} notation is ignored
14170during reading. If you use a negative prefix argument, such function
14171names are written @samp{\@var{name}}, and function names that begin
14172with @code{\} during reading have the @code{\} removed. (Note that
14173in this mode, long variable names are still written with @code{\hbox}.
14174However, you can always make an actual variable name like @code{\bar}
14175in any @TeX{} mode.)
14176
14177During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
14178by @samp{[ ...@: ]}. The same also applies to @code{\pmatrix} and
14179@code{\bmatrix}. The symbol @samp{&} is interpreted as a comma,
14180and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
14181During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
14182format; you may need to edit this afterwards to change @code{\matrix}
14183to @code{\pmatrix} or @code{\\} to @code{\cr}.
14184
14185Accents like @code{\tilde} and @code{\bar} translate into function
14186calls internally (@samp{tilde(x)}, @samp{bar(x)}). The @code{\underline}
14187sequence is treated as an accent. The @code{\vec} accent corresponds
14188to the function name @code{Vec}, because @code{vec} is the name of
14189a built-in Calc function. The following table shows the accents
14190in Calc, @TeX{}, and @dfn{eqn} (described in the next section):
14191
14192@iftex
14193@begingroup
14194@let@calcindexershow=@calcindexernoshow @c Suppress marginal notes
14195@let@calcindexersh=@calcindexernoshow
14196@end iftex
14197@c @starindex
14198@tindex acute
14199@c @starindex
14200@tindex bar
14201@c @starindex
14202@tindex breve
14203@c @starindex
14204@tindex check
14205@c @starindex
14206@tindex dot
14207@c @starindex
14208@tindex dotdot
14209@c @starindex
14210@tindex dyad
14211@c @starindex
14212@tindex grave
14213@c @starindex
14214@tindex hat
14215@c @starindex
14216@tindex Prime
14217@c @starindex
14218@tindex tilde
14219@c @starindex
14220@tindex under
14221@c @starindex
14222@tindex Vec
14223@iftex
14224@endgroup
14225@end iftex
14226@example
14227Calc TeX eqn
14228---- --- ---
14229acute \acute
14230bar \bar bar
14231breve \breve
14232check \check
14233dot \dot dot
14234dotdot \ddot dotdot
14235dyad dyad
14236grave \grave
14237hat \hat hat
14238Prime prime
14239tilde \tilde tilde
14240under \underline under
14241Vec \vec vec
14242@end example
14243
14244The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
14245@samp{@{@var{a} \to @var{b}@}}. @TeX{} defines @code{\to} as an
14246alias for @code{\rightarrow}. However, if the @samp{=>} is the
14247top-level expression being formatted, a slightly different notation
14248is used: @samp{\evalto @var{a} \to @var{b}}. The @code{\evalto}
14249word is ignored by Calc's input routines, and is undefined in @TeX{}.
14250You will typically want to include one of the following definitions
14251at the top of a @TeX{} file that uses @code{\evalto}:
14252
14253@example
14254\def\evalto@{@}
14255\def\evalto#1\to@{@}
14256@end example
14257
14258The first definition formats evaluates-to operators in the usual
14259way. The second causes only the @var{b} part to appear in the
14260printed document; the @var{a} part and the arrow are hidden.
14261Another definition you may wish to use is @samp{\let\to=\Rightarrow}
14262which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
14263@xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
14264
14265The complete set of @TeX{} control sequences that are ignored during
14266reading is:
14267
14268@example
14269\hbox \mbox \text \left \right
14270\, \> \: \; \! \quad \qquad \hfil \hfill
14271\displaystyle \textstyle \dsize \tsize
14272\scriptstyle \scriptscriptstyle \ssize \ssize
14273\rm \bf \it \sl \roman \bold \italic \slanted
14274\cal \mit \Cal \Bbb \frak \goth
14275\evalto
14276@end example
14277
14278Note that, because these symbols are ignored, reading a @TeX{} formula
14279into Calc and writing it back out may lose spacing and font information.
14280
14281Also, the ``discretionary multiplication sign'' @samp{\*} is read
14282the same as @samp{*}.
14283
14284@ifinfo
14285The @TeX{} version of this manual includes some printed examples at the
14286end of this section.
14287@end ifinfo
14288@iftex
14289Here are some examples of how various Calc formulas are formatted in @TeX{}:
14290
14291@group
14292@example
14293sin(a^2 / b_i)
14294\sin\left( {a^2 \over b_i} \right)
14295@end example
14296@tex
14297\let\rm\goodrm
14298$$ \sin\left( a^2 \over b_i \right) $$
14299@end tex
14300@sp 1
14301@end group
14302
14303@group
14304@example
14305[(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
14306[3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
14307@end example
14308@tex
14309\turnoffactive
14310$$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
14311@end tex
14312@sp 1
14313@end group
14314
14315@group
14316@example
14317[abs(a), abs(a / b), floor(a), ceil(a / b)]
14318[|a|, \left| a \over b \right|,
14319 \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
14320@end example
14321@tex
14322$$ [|a|, \left| a \over b \right|,
14323 \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
14324@end tex
14325@sp 1
14326@end group
14327
14328@group
14329@example
14330[sin(a), sin(2 a), sin(2 + a), sin(a / b)]
14331[\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
14332 \sin\left( @{a \over b@} \right)]
14333@end example
14334@tex
14335\turnoffactive\let\rm\goodrm
14336$$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
14337@end tex
14338@sp 2
14339@end group
14340
14341@group
14342First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
14343@kbd{C-u - d T} (using the example definition
14344@samp{\def\foo#1@{\tilde F(#1)@}}:
14345
14346@example
14347
14348[f(a), foo(bar), sin(pi)]
14349[f(a), foo(bar), \sin{\pi}]
14350[f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
14351[f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
14352@end example
14353@tex
14354\let\rm\goodrm
14355$$ [f(a), foo(bar), \sin{\pi}] $$
14356$$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
14357$$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
14358@end tex
14359@sp 2
14360@end group
14361
14362@group
14363First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
14364
14365@example
14366
143672 + 3 => 5
14368\evalto 2 + 3 \to 5
14369@end example
14370@tex
14371\turnoffactive
14372$$ 2 + 3 \to 5 $$
14373$$ 5 $$
14374@end tex
14375@sp 2
14376@end group
14377
14378@group
14379First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
14380
14381@example
14382
14383[2 + 3 => 5, a / 2 => (b + c) / 2]
14384[@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
14385@end example
14386@tex
14387\turnoffactive
14388$$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
14389{\let\to\Rightarrow
14390$$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
14391@end tex
14392@sp 2
14393@end group
14394
14395@group
14396Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
14397
14398@example
14399
14400[ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
14401\matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14402\pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14403@end example
14404@tex
14405\turnoffactive
14406$$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14407$$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14408@end tex
14409@sp 2
14410@end group
14411@end iftex
14412
14413@node Eqn Language Mode, Mathematica Language Mode, TeX Language Mode, Language Modes
14414@subsection Eqn Language Mode
14415
14416@noindent
14417@kindex d E
14418@pindex calc-eqn-language
14419@dfn{Eqn} is another popular formatter for math formulas. It is
14420designed for use with the TROFF text formatter, and comes standard
14421with many versions of Unix. The @kbd{d E} (@code{calc-eqn-language})
14422command selects @dfn{eqn} notation.
14423
14424The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
14425a significant part in the parsing of the language. For example,
14426@samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
14427@code{sqrt} operator. @dfn{Eqn} also understands more conventional
14428grouping using curly braces: @samp{sqrt@{x+1@} + y}. Braces are
14429required only when the argument contains spaces.
14430
14431In Calc's @dfn{eqn} mode, however, curly braces are required to
14432delimit arguments of operators like @code{sqrt}. The first of the
14433above examples would treat only the @samp{x} as the argument of
14434@code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
14435@samp{sin * x + 1}, because @code{sin} is not a special operator
14436in the @dfn{eqn} language. If you always surround the argument
14437with curly braces, Calc will never misunderstand.
14438
14439Calc also understands parentheses as grouping characters. Another
14440peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
14441words with spaces from any surrounding characters that aren't curly
14442braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
14443(The spaces around @code{sin} are important to make @dfn{eqn}
14444recognize that @code{sin} should be typeset in a roman font, and
14445the spaces around @code{x} and @code{y} are a good idea just in
14446case the @dfn{eqn} document has defined special meanings for these
14447names, too.)
14448
14449Powers and subscripts are written with the @code{sub} and @code{sup}
14450operators, respectively. Note that the caret symbol @samp{^} is
14451treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
14452symbol (these are used to introduce spaces of various widths into
14453the typeset output of @dfn{eqn}).
14454
14455As in @TeX{} mode, Calc's formatter omits parentheses around the
14456arguments of functions like @code{ln} and @code{sin} if they are
14457``simple-looking''; in this case Calc surrounds the argument with
14458braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
14459
14460Font change codes (like @samp{roman @var{x}}) and positioning codes
14461(like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
14462@dfn{eqn} reader. Also ignored are the words @code{left}, @code{right},
14463@code{mark}, and @code{lineup}. Quotation marks in @dfn{eqn} mode input
14464are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
14465@samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
14466of quotes in @dfn{eqn}, but it is good enough for most uses.
14467
14468Accent codes (@samp{@var{x} dot}) are handled by treating them as
14469function calls (@samp{dot(@var{x})}) internally. @xref{TeX Language
14470Mode} for a table of these accent functions. The @code{prime} accent
14471is treated specially if it occurs on a variable or function name:
14472@samp{f prime prime @w{( x prime )}} is stored internally as
14473@samp{f'@w{'}(x')}. For example, taking the derivative of @samp{f(2 x)}
14474with @kbd{a d x} will produce @samp{2 f'(2 x)}, which @dfn{eqn} mode
14475will display as @samp{2 f prime ( 2 x )}.
14476
14477Assignments are written with the @samp{<-} (left-arrow) symbol,
14478and @code{evalto} operators are written with @samp{->} or
14479@samp{evalto ... ->} (@pxref{TeX Language Mode}, for a discussion
14480of this). The regular Calc symbols @samp{:=} and @samp{=>} are also
14481recognized for these operators during reading.
14482
14483Vectors in @dfn{eqn} mode use regular Calc square brackets, but
14484matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
14485The words @code{lcol} and @code{rcol} are recognized as synonyms
14486for @code{ccol} during input, and are generated instead of @code{ccol}
14487if the matrix justification mode so specifies.
14488
14489@node Mathematica Language Mode, Maple Language Mode, Eqn Language Mode, Language Modes
14490@subsection Mathematica Language Mode
14491
14492@noindent
14493@kindex d M
14494@pindex calc-mathematica-language
14495@cindex Mathematica language
14496The @kbd{d M} (@code{calc-mathematica-language}) command selects the
14497conventions of Mathematica, a powerful and popular mathematical tool
14498from Wolfram Research, Inc. Notable differences in Mathematica mode
14499are that the names of built-in functions are capitalized, and function
14500calls use square brackets instead of parentheses. Thus the Calc
14501formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
14502Mathematica mode.
14503
14504Vectors and matrices use curly braces in Mathematica. Complex numbers
14505are written @samp{3 + 4 I}. The standard special constants in Calc are
14506written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
14507@code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
14508Mathematica mode.
14509Non-decimal numbers are written, e.g., @samp{16^^7fff}. Floating-point
14510numbers in scientific notation are written @samp{1.23*10.^3}.
14511Subscripts use double square brackets: @samp{a[[i]]}.@refill
14512
14513@node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
14514@subsection Maple Language Mode
14515
14516@noindent
14517@kindex d W
14518@pindex calc-maple-language
14519@cindex Maple language
14520The @kbd{d W} (@code{calc-maple-language}) command selects the
14521conventions of Maple, another mathematical tool from the University
14522of Waterloo.
14523
14524Maple's language is much like C. Underscores are allowed in symbol
14525names; square brackets are used for subscripts; explicit @samp{*}s for
14526multiplications are required. Use either @samp{^} or @samp{**} to
14527denote powers.
14528
14529Maple uses square brackets for lists and curly braces for sets. Calc
14530interprets both notations as vectors, and displays vectors with square
14531brackets. This means Maple sets will be converted to lists when they
14532pass through Calc. As a special case, matrices are written as calls
14533to the function @code{matrix}, given a list of lists as the argument,
14534and can be read in this form or with all-capitals @code{MATRIX}.
14535
14536The Maple interval notation @samp{2 .. 3} has no surrounding brackets;
14537Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]}, and
14538writes any kind of interval as @samp{2 .. 3}. This means you cannot
14539see the difference between an open and a closed interval while in
14540Maple display mode.
14541
14542Maple writes complex numbers as @samp{3 + 4*I}. Its special constants
14543are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
14544@code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
14545Floating-point numbers are written @samp{1.23*10.^3}.
14546
14547Among things not currently handled by Calc's Maple mode are the
14548various quote symbols, procedures and functional operators, and
14549inert (@samp{&}) operators.
14550
14551@node Compositions, Syntax Tables, Maple Language Mode, Language Modes
14552@subsection Compositions
14553
14554@noindent
14555@cindex Compositions
14556There are several @dfn{composition functions} which allow you to get
14557displays in a variety of formats similar to those in Big language
14558mode. Most of these functions do not evaluate to anything; they are
14559placeholders which are left in symbolic form by Calc's evaluator but
14560are recognized by Calc's display formatting routines.
14561
14562Two of these, @code{string} and @code{bstring}, are described elsewhere.
14563@xref{Strings}. For example, @samp{string("ABC")} is displayed as
14564@samp{ABC}. When viewed on the stack it will be indistinguishable from
14565the variable @code{ABC}, but internally it will be stored as
14566@samp{string([65, 66, 67])} and can still be manipulated this way; for
14567example, the selection and vector commands @kbd{j 1 v v j u} would
14568select the vector portion of this object and reverse the elements, then
14569deselect to reveal a string whose characters had been reversed.
14570
14571The composition functions do the same thing in all language modes
14572(although their components will of course be formatted in the current
14573language mode). The one exception is Unformatted mode (@kbd{d U}),
14574which does not give the composition functions any special treatment.
14575The functions are discussed here because of their relationship to
14576the language modes.
14577
14578@menu
14579* Composition Basics::
14580* Horizontal Compositions::
14581* Vertical Compositions::
14582* Other Compositions::
14583* Information about Compositions::
14584* User-Defined Compositions::
14585@end menu
14586
14587@node Composition Basics, Horizontal Compositions, Compositions, Compositions
14588@subsubsection Composition Basics
14589
14590@noindent
14591Compositions are generally formed by stacking formulas together
14592horizontally or vertically in various ways. Those formulas are
14593themselves compositions. @TeX{} users will find this analogous
14594to @TeX{}'s ``boxes.'' Each multi-line composition has a
14595@dfn{baseline}; horizontal compositions use the baselines to
14596decide how formulas should be positioned relative to one another.
14597For example, in the Big mode formula
14598
14599@group
14600@example
14601 2
14602 a + b
1460317 + ------
14604 c
14605@end example
14606@end group
14607
14608@noindent
14609the second term of the sum is four lines tall and has line three as
14610its baseline. Thus when the term is combined with 17, line three
14611is placed on the same level as the baseline of 17.
14612
14613@tex
14614\bigskip
14615@end tex
14616
14617Another important composition concept is @dfn{precedence}. This is
14618an integer that represents the binding strength of various operators.
14619For example, @samp{*} has higher precedence (195) than @samp{+} (180),
14620which means that @samp{(a * b) + c} will be formatted without the
14621parentheses, but @samp{a * (b + c)} will keep the parentheses.
14622
14623The operator table used by normal and Big language modes has the
14624following precedences:
14625
14626@example
14627_ 1200 @r{(subscripts)}
14628% 1100 @r{(as in n}%@r{)}
14629- 1000 @r{(as in }-@r{n)}
14630! 1000 @r{(as in }!@r{n)}
14631mod 400
14632+/- 300
14633!! 210 @r{(as in n}!!@r{)}
14634! 210 @r{(as in n}!@r{)}
14635^ 200
14636* 195 @r{(or implicit multiplication)}
14637/ % \ 190
14638+ - 180 @r{(as in a}+@r{b)}
14639| 170
14640< = 160 @r{(and other relations)}
14641&& 110
14642|| 100
14643? : 90
14644!!! 85
14645&&& 80
14646||| 75
14647:= 50
14648:: 45
14649=> 40
14650@end example
14651
14652The general rule is that if an operator with precedence @cite{n}
14653occurs as an argument to an operator with precedence @cite{m}, then
14654the argument is enclosed in parentheses if @cite{n < m}. Top-level
14655expressions and expressions which are function arguments, vector
14656components, etc., are formatted with precedence zero (so that they
14657normally never get additional parentheses).
14658
14659For binary left-associative operators like @samp{+}, the righthand
14660argument is actually formatted with one-higher precedence than shown
14661in the table. This makes sure @samp{(a + b) + c} omits the parentheses,
14662but the unnatural form @samp{a + (b + c)} keeps its parentheses.
14663Right-associative operators like @samp{^} format the lefthand argument
14664with one-higher precedence.
14665
14666@c @starindex
14667@tindex cprec
14668The @code{cprec} function formats an expression with an arbitrary
14669precedence. For example, @samp{cprec(abc, 185)} will combine into
14670sums and products as follows: @samp{7 + abc}, @samp{7 (abc)} (because
14671this @code{cprec} form has higher precedence than addition, but lower
14672precedence than multiplication).
14673
14674@tex
14675\bigskip
14676@end tex
14677
14678A final composition issue is @dfn{line breaking}. Calc uses two
14679different strategies for ``flat'' and ``non-flat'' compositions.
14680A non-flat composition is anything that appears on multiple lines
14681(not counting line breaking). Examples would be matrices and Big
14682mode powers and quotients. Non-flat compositions are displayed
14683exactly as specified. If they come out wider than the current
14684window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
14685view them.
14686
14687Flat compositions, on the other hand, will be broken across several
14688lines if they are too wide to fit the window. Certain points in a
14689composition are noted internally as @dfn{break points}. Calc's
14690general strategy is to fill each line as much as possible, then to
14691move down to the next line starting at the first break point that
14692didn't fit. However, the line breaker understands the hierarchical
14693structure of formulas. It will not break an ``inner'' formula if
14694it can use an earlier break point from an ``outer'' formula instead.
14695For example, a vector of sums might be formatted as:
14696
14697@group
14698@example
14699[ a + b + c, d + e + f,
14700 g + h + i, j + k + l, m ]
14701@end example
14702@end group
14703
14704@noindent
14705If the @samp{m} can fit, then so, it seems, could the @samp{g}.
14706But Calc prefers to break at the comma since the comma is part
14707of a ``more outer'' formula. Calc would break at a plus sign
14708only if it had to, say, if the very first sum in the vector had
14709itself been too large to fit.
14710
14711Of the composition functions described below, only @code{choriz}
14712generates break points. The @code{bstring} function (@pxref{Strings})
14713also generates breakable items: A break point is added after every
14714space (or group of spaces) except for spaces at the very beginning or
14715end of the string.
14716
14717Composition functions themselves count as levels in the formula
14718hierarchy, so a @code{choriz} that is a component of a larger
14719@code{choriz} will be less likely to be broken. As a special case,
14720if a @code{bstring} occurs as a component of a @code{choriz} or
14721@code{choriz}-like object (such as a vector or a list of arguments
14722in a function call), then the break points in that @code{bstring}
14723will be on the same level as the break points of the surrounding
14724object.
14725
14726@node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
14727@subsubsection Horizontal Compositions
14728
14729@noindent
14730@c @starindex
14731@tindex choriz
14732The @code{choriz} function takes a vector of objects and composes
14733them horizontally. For example, @samp{choriz([17, a b/c, d])} formats
14734as @w{@samp{17a b / cd}} in normal language mode, or as
14735
14736@group
14737@example
14738 a b
1473917---d
14740 c
14741@end example
14742@end group
14743
14744@noindent
14745in Big language mode. This is actually one case of the general
14746function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
14747either or both of @var{sep} and @var{prec} may be omitted.
14748@var{Prec} gives the @dfn{precedence} to use when formatting
14749each of the components of @var{vec}. The default precedence is
14750the precedence from the surrounding environment.
14751
14752@var{Sep} is a string (i.e., a vector of character codes as might
14753be entered with @code{" "} notation) which should separate components
14754of the composition. Also, if @var{sep} is given, the line breaker
14755will allow lines to be broken after each occurrence of @var{sep}.
14756If @var{sep} is omitted, the composition will not be breakable
14757(unless any of its component compositions are breakable).
14758
14759For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
14760formatted as @samp{2 a + b c + (d = e)}. To get the @code{choriz}
14761to have precedence 180 ``outwards'' as well as ``inwards,''
14762enclose it in a @code{cprec} form: @samp{2 cprec(choriz(...), 180)}
14763formats as @samp{2 (a + b c + (d = e))}.
14764
14765The baseline of a horizontal composition is the same as the
14766baselines of the component compositions, which are all aligned.
14767
14768@node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
14769@subsubsection Vertical Compositions
14770
14771@noindent
14772@c @starindex
14773@tindex cvert
14774The @code{cvert} function makes a vertical composition. Each
14775component of the vector is centered in a column. The baseline of
14776the result is by default the top line of the resulting composition.
14777For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
14778formats in Big mode as
14779
14780@group
14781@example
14782f( a , 2 )
14783 bb a + 1
14784 ccc 2
14785 b
14786@end example
14787@end group
14788
14789@c @starindex
14790@tindex cbase
14791There are several special composition functions that work only as
14792components of a vertical composition. The @code{cbase} function
14793controls the baseline of the vertical composition; the baseline
14794will be the same as the baseline of whatever component is enclosed
14795in @code{cbase}. Thus @samp{f(cvert([a, cbase(bb), ccc]),
14796cvert([a^2 + 1, cbase(b^2)]))} displays as
14797
14798@group
14799@example
14800 2
14801 a + 1
14802 a 2
14803f(bb , b )
14804 ccc
14805@end example
14806@end group
14807
14808@c @starindex
14809@tindex ctbase
14810@c @starindex
14811@tindex cbbase
14812There are also @code{ctbase} and @code{cbbase} functions which
14813make the baseline of the vertical composition equal to the top
14814or bottom line (rather than the baseline) of that component.
14815Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
14816cvert([cbbase(a / b)])} gives
14817
14818@group
14819@example
14820 a
14821a -
14822- + a + b
14823b -
14824 b
14825@end example
14826@end group
14827
14828There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
14829function in a given vertical composition. These functions can also
14830be written with no arguments: @samp{ctbase()} is a zero-height object
14831which means the baseline is the top line of the following item, and
14832@samp{cbbase()} means the baseline is the bottom line of the preceding
14833item.
14834
14835@c @starindex
14836@tindex crule
14837The @code{crule} function builds a ``rule,'' or horizontal line,
14838across a vertical composition. By itself @samp{crule()} uses @samp{-}
14839characters to build the rule. You can specify any other character,
14840e.g., @samp{crule("=")}. The argument must be a character code or
14841vector of exactly one character code. It is repeated to match the
14842width of the widest item in the stack. For example, a quotient
14843with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
14844
14845@group
14846@example
14847a + 1
14848=====
14849 2
14850 b
14851@end example
14852@end group
14853
14854@c @starindex
14855@tindex clvert
14856@c @starindex
14857@tindex crvert
14858Finally, the functions @code{clvert} and @code{crvert} act exactly
14859like @code{cvert} except that the items are left- or right-justified
14860in the stack. Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
14861gives:
14862
14863@group
14864@example
14865a + a
14866bb bb
14867ccc ccc
14868@end example
14869@end group
14870
14871Like @code{choriz}, the vertical compositions accept a second argument
14872which gives the precedence to use when formatting the components.
14873Vertical compositions do not support separator strings.
14874
14875@node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
14876@subsubsection Other Compositions
14877
14878@noindent
14879@c @starindex
14880@tindex csup
14881The @code{csup} function builds a superscripted expression. For
14882example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
14883language mode. This is essentially a horizontal composition of
14884@samp{a} and @samp{b}, where @samp{b} is shifted up so that its
14885bottom line is one above the baseline.
14886
14887@c @starindex
14888@tindex csub
14889Likewise, the @code{csub} function builds a subscripted expression.
14890This shifts @samp{b} down so that its top line is one below the
14891bottom line of @samp{a} (note that this is not quite analogous to
14892@code{csup}). Other arrangements can be obtained by using
14893@code{choriz} and @code{cvert} directly.
14894
14895@c @starindex
14896@tindex cflat
14897The @code{cflat} function formats its argument in ``flat'' mode,
14898as obtained by @samp{d O}, if the current language mode is normal
14899or Big. It has no effect in other language modes. For example,
14900@samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
14901to improve its readability.
14902
14903@c @starindex
14904@tindex cspace
14905The @code{cspace} function creates horizontal space. For example,
14906@samp{cspace(4)} is effectively the same as @samp{string(" ")}.
14907A second string (i.e., vector of characters) argument is repeated
14908instead of the space character. For example, @samp{cspace(4, "ab")}
14909looks like @samp{abababab}. If the second argument is not a string,
14910it is formatted in the normal way and then several copies of that
14911are composed together: @samp{cspace(4, a^2)} yields
14912
14913@group
14914@example
14915 2 2 2 2
14916a a a a
14917@end example
14918@end group
14919
14920@noindent
14921If the number argument is zero, this is a zero-width object.
14922
14923@c @starindex
14924@tindex cvspace
14925The @code{cvspace} function creates vertical space, or a vertical
14926stack of copies of a certain string or formatted object. The
14927baseline is the center line of the resulting stack. A numerical
14928argument of zero will produce an object which contributes zero
14929height if used in a vertical composition.
14930
14931@c @starindex
14932@tindex ctspace
14933@c @starindex
14934@tindex cbspace
14935There are also @code{ctspace} and @code{cbspace} functions which
14936create vertical space with the baseline the same as the baseline
14937of the top or bottom copy, respectively, of the second argument.
14938Thus @samp{cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)}
14939displays as:
14940
14941@group
14942@example
14943 a
14944 -
14945a b
14946- a a
14947b + - + -
14948a b b
14949- a
14950b -
14951 b
14952@end example
14953@end group
14954
14955@node Information about Compositions, User-Defined Compositions, Other Compositions, Compositions
14956@subsubsection Information about Compositions
14957
14958@noindent
14959The functions in this section are actual functions; they compose their
14960arguments according to the current language and other display modes,
14961then return a certain measurement of the composition as an integer.
14962
14963@c @starindex
14964@tindex cwidth
14965The @code{cwidth} function measures the width, in characters, of a
14966composition. For example, @samp{cwidth(a + b)} is 5, and
14967@samp{cwidth(a / b)} is 5 in normal mode, 1 in Big mode, and 11 in
14968@TeX{} mode (for @samp{@{a \over b@}}). The argument may involve
14969the composition functions described in this section.
14970
14971@c @starindex
14972@tindex cheight
14973The @code{cheight} function measures the height of a composition.
14974This is the total number of lines in the argument's printed form.
14975
14976@c @starindex
14977@tindex cascent
14978@c @starindex
14979@tindex cdescent
14980The functions @code{cascent} and @code{cdescent} measure the amount
14981of the height that is above (and including) the baseline, or below
14982the baseline, respectively. Thus @samp{cascent(@var{x}) + cdescent(@var{x})}
14983always equals @samp{cheight(@var{x})}. For a one-line formula like
14984@samp{a + b}, @code{cascent} returns 1 and @code{cdescent} returns 0.
14985For @samp{a / b} in Big mode, @code{cascent} returns 2 and @code{cdescent}
14986returns 1. The only formula for which @code{cascent} will return zero
14987is @samp{cvspace(0)} or equivalents.
14988
14989@node User-Defined Compositions, , Information about Compositions, Compositions
14990@subsubsection User-Defined Compositions
14991
14992@noindent
14993@kindex Z C
14994@pindex calc-user-define-composition
14995The @kbd{Z C} (@code{calc-user-define-composition}) command lets you
14996define the display format for any algebraic function. You provide a
14997formula containing a certain number of argument variables on the stack.
14998Any time Calc formats a call to the specified function in the current
14999language mode and with that number of arguments, Calc effectively
15000replaces the function call with that formula with the arguments
15001replaced.
15002
15003Calc builds the default argument list by sorting all the variable names
15004that appear in the formula into alphabetical order. You can edit this
15005argument list before pressing @key{RET} if you wish. Any variables in
15006the formula that do not appear in the argument list will be displayed
15007literally; any arguments that do not appear in the formula will not
15008affect the display at all.
15009
15010You can define formats for built-in functions, for functions you have
15011defined with @kbd{Z F} (@pxref{Algebraic Definitions}), or for functions
15012which have no definitions but are being used as purely syntactic objects.
15013You can define different formats for each language mode, and for each
15014number of arguments, using a succession of @kbd{Z C} commands. When
15015Calc formats a function call, it first searches for a format defined
15016for the current language mode (and number of arguments); if there is
15017none, it uses the format defined for the Normal language mode. If
15018neither format exists, Calc uses its built-in standard format for that
15019function (usually just @samp{@var{func}(@var{args})}).
15020
15021If you execute @kbd{Z C} with the number 0 on the stack instead of a
15022formula, any defined formats for the function in the current language
15023mode will be removed. The function will revert to its standard format.
15024
15025For example, the default format for the binomial coefficient function
15026@samp{choose(n, m)} in the Big language mode is
15027
15028@group
15029@example
15030 n
15031( )
15032 m
15033@end example
15034@end group
15035
15036@noindent
15037You might prefer the notation,
15038
15039@group
15040@example
15041 C
15042n m
15043@end example
15044@end group
15045
15046@noindent
15047To define this notation, first make sure you are in Big mode,
15048then put the formula
15049
15050@smallexample
15051choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
15052@end smallexample
15053
15054@noindent
15055on the stack and type @kbd{Z C}. Answer the first prompt with
15056@code{choose}. The second prompt will be the default argument list
15057of @samp{(C m n)}. Edit this list to be @samp{(n m)} and press
15058@key{RET}. Now, try it out: For example, turn simplification
15059off with @kbd{m O} and enter @samp{choose(a,b) + choose(7,3)}
15060as an algebraic entry.
15061
15062@group
15063@example
15064 C + C
15065a b 7 3
15066@end example
15067@end group
15068
15069As another example, let's define the usual notation for Stirling
15070numbers of the first kind, @samp{stir1(n, m)}. This is just like
15071the regular format for binomial coefficients but with square brackets
15072instead of parentheses.
15073
15074@smallexample
15075choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
15076@end smallexample
15077
15078Now type @kbd{Z C stir1 @key{RET}}, edit the argument list to
15079@samp{(n m)}, and type @key{RET}.
15080
15081The formula provided to @kbd{Z C} usually will involve composition
15082functions, but it doesn't have to. Putting the formula @samp{a + b + c}
15083onto the stack and typing @kbd{Z C foo @key{RET} @key{RET}} would define
15084the function @samp{foo(x,y,z)} to display like @samp{x + y + z}.
15085This ``sum'' will act exactly like a real sum for all formatting
15086purposes (it will be parenthesized the same, and so on). However
15087it will be computationally unrelated to a sum. For example, the
15088formula @samp{2 * foo(1, 2, 3)} will display as @samp{2 (1 + 2 + 3)}.
15089Operator precedences have caused the ``sum'' to be written in
15090parentheses, but the arguments have not actually been summed.
15091(Generally a display format like this would be undesirable, since
15092it can easily be confused with a real sum.)
15093
15094The special function @code{eval} can be used inside a @kbd{Z C}
15095composition formula to cause all or part of the formula to be
15096evaluated at display time. For example, if the formula is
15097@samp{a + eval(b + c)}, then @samp{foo(1, 2, 3)} will be displayed
15098as @samp{1 + 5}. Evaluation will use the default simplifications,
15099regardless of the current simplification mode. There are also
15100@code{evalsimp} and @code{evalextsimp} which simplify as if by
15101@kbd{a s} and @kbd{a e} (respectively). Note that these ``functions''
15102operate only in the context of composition formulas (and also in
15103rewrite rules, where they serve a similar purpose; @pxref{Rewrite
15104Rules}). On the stack, a call to @code{eval} will be left in
15105symbolic form.
15106
15107It is not a good idea to use @code{eval} except as a last resort.
15108It can cause the display of formulas to be extremely slow. For
15109example, while @samp{eval(a + b)} might seem quite fast and simple,
15110there are several situations where it could be slow. For example,
15111@samp{a} and/or @samp{b} could be polar complex numbers, in which
15112case doing the sum requires trigonometry. Or, @samp{a} could be
15113the factorial @samp{fact(100)} which is unevaluated because you
15114have typed @kbd{m O}; @code{eval} will evaluate it anyway to
15115produce a large, unwieldy integer.
15116
15117You can save your display formats permanently using the @kbd{Z P}
15118command (@pxref{Creating User Keys}).
15119
15120@node Syntax Tables, , Compositions, Language Modes
15121@subsection Syntax Tables
15122
15123@noindent
15124@cindex Syntax tables
15125@cindex Parsing formulas, customized
15126Syntax tables do for input what compositions do for output: They
15127allow you to teach custom notations to Calc's formula parser.
15128Calc keeps a separate syntax table for each language mode.
15129
15130(Note that the Calc ``syntax tables'' discussed here are completely
15131unrelated to the syntax tables described in the Emacs manual.)
15132
15133@kindex Z S
15134@pindex calc-edit-user-syntax
15135The @kbd{Z S} (@code{calc-edit-user-syntax}) command edits the
15136syntax table for the current language mode. If you want your
15137syntax to work in any language, define it in the normal language
15138mode. Type @kbd{M-# M-#} to finish editing the syntax table, or
15139@kbd{M-# x} to cancel the edit. The @kbd{m m} command saves all
15140the syntax tables along with the other mode settings;
15141@pxref{General Mode Commands}.
15142
15143@menu
15144* Syntax Table Basics::
15145* Precedence in Syntax Tables::
15146* Advanced Syntax Patterns::
15147* Conditional Syntax Rules::
15148@end menu
15149
15150@node Syntax Table Basics, Precedence in Syntax Tables, Syntax Tables, Syntax Tables
15151@subsubsection Syntax Table Basics
15152
15153@noindent
15154@dfn{Parsing} is the process of converting a raw string of characters,
15155such as you would type in during algebraic entry, into a Calc formula.
15156Calc's parser works in two stages. First, the input is broken down
15157into @dfn{tokens}, such as words, numbers, and punctuation symbols
15158like @samp{+}, @samp{:=}, and @samp{+/-}. Space between tokens is
15159ignored (except when it serves to separate adjacent words). Next,
15160the parser matches this string of tokens against various built-in
15161syntactic patterns, such as ``an expression followed by @samp{+}
15162followed by another expression'' or ``a name followed by @samp{(},
15163zero or more expressions separated by commas, and @samp{)}.''
15164
15165A @dfn{syntax table} is a list of user-defined @dfn{syntax rules},
15166which allow you to specify new patterns to define your own
15167favorite input notations. Calc's parser always checks the syntax
15168table for the current language mode, then the table for the normal
15169language mode, before it uses its built-in rules to parse an
15170algebraic formula you have entered. Each syntax rule should go on
15171its own line; it consists of a @dfn{pattern}, a @samp{:=} symbol,
15172and a Calc formula with an optional @dfn{condition}. (Syntax rules
15173resemble algebraic rewrite rules, but the notation for patterns is
15174completely different.)
15175
15176A syntax pattern is a list of tokens, separated by spaces.
15177Except for a few special symbols, tokens in syntax patterns are
15178matched literally, from left to right. For example, the rule,
15179
15180@example
15181foo ( ) := 2+3
15182@end example
15183
15184@noindent
15185would cause Calc to parse the formula @samp{4+foo()*5} as if it
15186were @samp{4+(2+3)*5}. Notice that the parentheses were written
15187as two separate tokens in the rule. As a result, the rule works
15188for both @samp{foo()} and @w{@samp{foo ( )}}. If we had written
15189the rule as @samp{foo () := 2+3}, then Calc would treat @samp{()}
15190as a single, indivisible token, so that @w{@samp{foo( )}} would
15191not be recognized by the rule. (It would be parsed as a regular
15192zero-argument function call instead.) In fact, this rule would
15193also make trouble for the rest of Calc's parser: An unrelated
15194formula like @samp{bar()} would now be tokenized into @samp{bar ()}
15195instead of @samp{bar ( )}, so that the standard parser for function
15196calls would no longer recognize it!
15197
15198While it is possible to make a token with a mixture of letters
15199and punctuation symbols, this is not recommended. It is better to
15200break it into several tokens, as we did with @samp{foo()} above.
15201
15202The symbol @samp{#} in a syntax pattern matches any Calc expression.
15203On the righthand side, the things that matched the @samp{#}s can
15204be referred to as @samp{#1}, @samp{#2}, and so on (where @samp{#1}
15205matches the leftmost @samp{#} in the pattern). For example, these
15206rules match a user-defined function, prefix operator, infix operator,
15207and postfix operator, respectively:
15208
15209@example
15210foo ( # ) := myfunc(#1)
15211foo # := myprefix(#1)
15212# foo # := myinfix(#1,#2)
15213# foo := mypostfix(#1)
15214@end example
15215
15216Thus @samp{foo(3)} will parse as @samp{myfunc(3)}, and @samp{2+3 foo}
15217will parse as @samp{mypostfix(2+3)}.
15218
15219It is important to write the first two rules in the order shown,
15220because Calc tries rules in order from first to last. If the
15221pattern @samp{foo #} came first, it would match anything that could
15222match the @samp{foo ( # )} rule, since an expression in parentheses
15223is itself a valid expression. Thus the @w{@samp{foo ( # )}} rule would
15224never get to match anything. Likewise, the last two rules must be
15225written in the order shown or else @samp{3 foo 4} will be parsed as
15226@samp{mypostfix(3) * 4}. (Of course, the best way to avoid these
15227ambiguities is not to use the same symbol in more than one way at
15228the same time! In case you're not convinced, try the following
15229exercise: How will the above rules parse the input @samp{foo(3,4)},
15230if at all? Work it out for yourself, then try it in Calc and see.)
15231
15232Calc is quite flexible about what sorts of patterns are allowed.
15233The only rule is that every pattern must begin with a literal
15234token (like @samp{foo} in the first two patterns above), or with
15235a @samp{#} followed by a literal token (as in the last two
15236patterns). After that, any mixture is allowed, although putting
15237two @samp{#}s in a row will not be very useful since two
15238expressions with nothing between them will be parsed as one
15239expression that uses implicit multiplication.
15240
15241As a more practical example, Maple uses the notation
15242@samp{sum(a(i), i=1..10)} for sums, which Calc's Maple mode doesn't
15243recognize at present. To handle this syntax, we simply add the
15244rule,
15245
15246@example
15247sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
15248@end example
15249
15250@noindent
15251to the Maple mode syntax table. As another example, C mode can't
15252read assignment operators like @samp{++} and @samp{*=}. We can
15253define these operators quite easily:
15254
15255@example
15256# *= # := muleq(#1,#2)
15257# ++ := postinc(#1)
15258++ # := preinc(#1)
15259@end example
15260
15261@noindent
15262To complete the job, we would use corresponding composition functions
15263and @kbd{Z C} to cause these functions to display in their respective
15264Maple and C notations. (Note that the C example ignores issues of
15265operator precedence, which are discussed in the next section.)
15266
15267You can enclose any token in quotes to prevent its usual
15268interpretation in syntax patterns:
15269
15270@example
15271# ":=" # := becomes(#1,#2)
15272@end example
15273
15274Quotes also allow you to include spaces in a token, although once
15275again it is generally better to use two tokens than one token with
15276an embedded space. To include an actual quotation mark in a quoted
15277token, precede it with a backslash. (This also works to include
15278backslashes in tokens.)
15279
15280@example
15281# "bad token" # "/\"\\" # := silly(#1,#2,#3)
15282@end example
15283
15284@noindent
15285This will parse @samp{3 bad token 4 /"\ 5} to @samp{silly(3,4,5)}.
15286
15287The token @kbd{#} has a predefined meaning in Calc's formula parser;
15288it is not legal to use @samp{"#"} in a syntax rule. However, longer
15289tokens that include the @samp{#} character are allowed. Also, while
15290@samp{"$"} and @samp{"\""} are allowed as tokens, their presence in
15291the syntax table will prevent those characters from working in their
15292usual ways (referring to stack entries and quoting strings,
15293respectively).
15294
15295Finally, the notation @samp{%%} anywhere in a syntax table causes
15296the rest of the line to be ignored as a comment.
15297
15298@node Precedence in Syntax Tables, Advanced Syntax Patterns, Syntax Table Basics, Syntax Tables
15299@subsubsection Precedence
15300
15301@noindent
15302Different operators are generally assigned different @dfn{precedences}.
15303By default, an operator defined by a rule like
15304
15305@example
15306# foo # := foo(#1,#2)
15307@end example
15308
15309@noindent
15310will have an extremely low precedence, so that @samp{2*3+4 foo 5 == 6}
15311will be parsed as @samp{(2*3+4) foo (5 == 6)}. To change the
15312precedence of an operator, use the notation @samp{#/@var{p}} in
15313place of @samp{#}, where @var{p} is an integer precedence level.
15314For example, 185 lies between the precedences for @samp{+} and
15315@samp{*}, so if we change this rule to
15316
15317@example
15318#/185 foo #/186 := foo(#1,#2)
15319@end example
15320
15321@noindent
15322then @samp{2+3 foo 4*5} will be parsed as @samp{2+(3 foo (4*5))}.
15323Also, because we've given the righthand expression slightly higher
15324precedence, our new operator will be left-associative:
15325@samp{1 foo 2 foo 3} will be parsed as @samp{(1 foo 2) foo 3}.
15326By raising the precedence of the lefthand expression instead, we
15327can create a right-associative operator.
15328
15329@xref{Composition Basics}, for a table of precedences of the
15330standard Calc operators. For the precedences of operators in other
15331language modes, look in the Calc source file @file{calc-lang.el}.
15332
15333@node Advanced Syntax Patterns, Conditional Syntax Rules, Precedence in Syntax Tables, Syntax Tables
15334@subsubsection Advanced Syntax Patterns
15335
15336@noindent
15337To match a function with a variable number of arguments, you could
15338write
15339
15340@example
15341foo ( # ) := myfunc(#1)
15342foo ( # , # ) := myfunc(#1,#2)
15343foo ( # , # , # ) := myfunc(#1,#2,#3)
15344@end example
15345
15346@noindent
15347but this isn't very elegant. To match variable numbers of items,
15348Calc uses some notations inspired regular expressions and the
15349``extended BNF'' style used by some language designers.
15350
15351@example
15352foo ( @{ # @}*, ) := apply(myfunc,#1)
15353@end example
15354
15355The token @samp{@{} introduces a repeated or optional portion.
15356One of the three tokens @samp{@}*}, @samp{@}+}, or @samp{@}?}
15357ends the portion. These will match zero or more, one or more,
15358or zero or one copies of the enclosed pattern, respectively.
15359In addition, @samp{@}*} and @samp{@}+} can be followed by a
15360separator token (with no space in between, as shown above).
15361Thus @samp{@{ # @}*,} matches nothing, or one expression, or
15362several expressions separated by commas.
15363
15364A complete @samp{@{ ... @}} item matches as a vector of the
15365items that matched inside it. For example, the above rule will
15366match @samp{foo(1,2,3)} to get @samp{apply(myfunc,[1,2,3])}.
15367The Calc @code{apply} function takes a function name and a vector
15368of arguments and builds a call to the function with those
15369arguments, so the net result is the formula @samp{myfunc(1,2,3)}.
15370
15371If the body of a @samp{@{ ... @}} contains several @samp{#}s
15372(or nested @samp{@{ ... @}} constructs), then the items will be
15373strung together into the resulting vector. If the body
15374does not contain anything but literal tokens, the result will
15375always be an empty vector.
15376
15377@example
15378foo ( @{ # , # @}+, ) := bar(#1)
15379foo ( @{ @{ # @}*, @}*; ) := matrix(#1)
15380@end example
15381
15382@noindent
15383will parse @samp{foo(1,2,3,4)} as @samp{bar([1,2,3,4])}, and
15384@samp{foo(1,2;3,4)} as @samp{matrix([[1,2],[3,4]])}. Also, after
15385some thought it's easy to see how this pair of rules will parse
15386@samp{foo(1,2,3)} as @samp{matrix([[1,2,3]])}, since the first
15387rule will only match an even number of arguments. The rule
15388
15389@example
15390foo ( # @{ , # , # @}? ) := bar(#1,#2)
15391@end example
15392
15393@noindent
15394will parse @samp{foo(2,3,4)} as @samp{bar(2,[3,4])}, and
15395@samp{foo(2)} as @samp{bar(2,[])}.
15396
15397The notation @samp{@{ ... @}?.} (note the trailing period) works
15398just the same as regular @samp{@{ ... @}?}, except that it does not
15399count as an argument; the following two rules are equivalent:
15400
15401@example
15402foo ( # , @{ also @}? # ) := bar(#1,#3)
15403foo ( # , @{ also @}?. # ) := bar(#1,#2)
15404@end example
15405
15406@noindent
15407Note that in the first case the optional text counts as @samp{#2},
15408which will always be an empty vector, but in the second case no
15409empty vector is produced.
15410
15411Another variant is @samp{@{ ... @}?$}, which means the body is
15412optional only at the end of the input formula. All built-in syntax
15413rules in Calc use this for closing delimiters, so that during
15414algebraic entry you can type @kbd{[sqrt(2), sqrt(3 RET}, omitting
15415the closing parenthesis and bracket. Calc does this automatically
15416for trailing @samp{)}, @samp{]}, and @samp{>} tokens in syntax
15417rules, but you can use @samp{@{ ... @}?$} explicitly to get
15418this effect with any token (such as @samp{"@}"} or @samp{end}).
15419Like @samp{@{ ... @}?.}, this notation does not count as an
15420argument. Conversely, you can use quotes, as in @samp{")"}, to
15421prevent a closing-delimiter token from being automatically treated
15422as optional.
15423
15424Calc's parser does not have full backtracking, which means some
15425patterns will not work as you might expect:
15426
15427@example
15428foo ( @{ # , @}? # , # ) := bar(#1,#2,#3)
15429@end example
15430
15431@noindent
15432Here we are trying to make the first argument optional, so that
15433@samp{foo(2,3)} parses as @samp{bar([],2,3)}. Unfortunately, Calc
15434first tries to match @samp{2,} against the optional part of the
15435pattern, finds a match, and so goes ahead to match the rest of the
15436pattern. Later on it will fail to match the second comma, but it
15437doesn't know how to go back and try the other alternative at that
15438point. One way to get around this would be to use two rules:
15439
15440@example
15441foo ( # , # , # ) := bar([#1],#2,#3)
15442foo ( # , # ) := bar([],#1,#2)
15443@end example
15444
15445More precisely, when Calc wants to match an optional or repeated
15446part of a pattern, it scans forward attempting to match that part.
15447If it reaches the end of the optional part without failing, it
15448``finalizes'' its choice and proceeds. If it fails, though, it
15449backs up and tries the other alternative. Thus Calc has ``partial''
15450backtracking. A fully backtracking parser would go on to make sure
15451the rest of the pattern matched before finalizing the choice.
15452
15453@node Conditional Syntax Rules, , Advanced Syntax Patterns, Syntax Tables
15454@subsubsection Conditional Syntax Rules
15455
15456@noindent
15457It is possible to attach a @dfn{condition} to a syntax rule. For
15458example, the rules
15459
15460@example
15461foo ( # ) := ifoo(#1) :: integer(#1)
15462foo ( # ) := gfoo(#1)
15463@end example
15464
15465@noindent
15466will parse @samp{foo(3)} as @samp{ifoo(3)}, but will parse
15467@samp{foo(3.5)} and @samp{foo(x)} as calls to @code{gfoo}. Any
15468number of conditions may be attached; all must be true for the
15469rule to succeed. A condition is ``true'' if it evaluates to a
15470nonzero number. @xref{Logical Operations}, for a list of Calc
15471functions like @code{integer} that perform logical tests.
15472
15473The exact sequence of events is as follows: When Calc tries a
15474rule, it first matches the pattern as usual. It then substitutes
15475@samp{#1}, @samp{#2}, etc., in the conditions, if any. Next, the
15476conditions are simplified and evaluated in order from left to right,
15477as if by the @w{@kbd{a s}} algebra command (@pxref{Simplifying Formulas}).
15478Each result is true if it is a nonzero number, or an expression
15479that can be proven to be nonzero (@pxref{Declarations}). If the
15480results of all conditions are true, the expression (such as
15481@samp{ifoo(#1)}) has its @samp{#}s substituted, and that is the
15482result of the parse. If the result of any condition is false, Calc
15483goes on to try the next rule in the syntax table.
15484
15485Syntax rules also support @code{let} conditions, which operate in
15486exactly the same way as they do in algebraic rewrite rules.
15487@xref{Other Features of Rewrite Rules}, for details. A @code{let}
15488condition is always true, but as a side effect it defines a
15489variable which can be used in later conditions, and also in the
15490expression after the @samp{:=} sign:
15491
15492@example
15493foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
15494@end example
15495
15496@noindent
15497The @code{dnumint} function tests if a value is numerically an
15498integer, i.e., either a true integer or an integer-valued float.
15499This rule will parse @code{foo} with a half-integer argument,
15500like @samp{foo(3.5)}, to a call like @samp{hifoo(4.)}.
15501
15502The lefthand side of a syntax rule @code{let} must be a simple
15503variable, not the arbitrary pattern that is allowed in rewrite
15504rules.
15505
15506The @code{matches} function is also treated specially in syntax
15507rule conditions (again, in the same way as in rewrite rules).
15508@xref{Matching Commands}. If the matching pattern contains
15509meta-variables, then those meta-variables may be used in later
15510conditions and in the result expression. The arguments to
15511@code{matches} are not evaluated in this situation.
15512
15513@example
15514sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
15515@end example
15516
15517@noindent
15518This is another way to implement the Maple mode @code{sum} notation.
15519In this approach, we allow @samp{#2} to equal the whole expression
15520@samp{i=1..10}. Then, we use @code{matches} to break it apart into
15521its components. If the expression turns out not to match the pattern,
15522the syntax rule will fail. Note that @kbd{Z S} always uses Calc's
15523normal language mode for editing expressions in syntax rules, so we
15524must use regular Calc notation for the interval @samp{[b..c]} that
15525will correspond to the Maple mode interval @samp{1..10}.
15526
15527@node Modes Variable, Calc Mode Line, Language Modes, Mode Settings
15528@section The @code{Modes} Variable
15529
15530@noindent
15531@kindex m g
15532@pindex calc-get-modes
15533The @kbd{m g} (@code{calc-get-modes}) command pushes onto the stack
15534a vector of numbers that describes the various mode settings that
15535are in effect. With a numeric prefix argument, it pushes only the
15536@var{n}th mode, i.e., the @var{n}th element of this vector. Keyboard
15537macros can use the @kbd{m g} command to modify their behavior based
15538on the current mode settings.
15539
15540@cindex @code{Modes} variable
15541@vindex Modes
15542The modes vector is also available in the special variable
15543@code{Modes}. In other words, @kbd{m g} is like @kbd{s r Modes RET}.
15544It will not work to store into this variable; in fact, if you do,
15545@code{Modes} will cease to track the current modes. (The @kbd{m g}
15546command will continue to work, however.)
15547
15548In general, each number in this vector is suitable as a numeric
15549prefix argument to the associated mode-setting command. (Recall
15550that the @kbd{~} key takes a number from the stack and gives it as
15551a numeric prefix to the next command.)
15552
15553The elements of the modes vector are as follows:
15554
15555@enumerate
15556@item
15557Current precision. Default is 12; associated command is @kbd{p}.
15558
15559@item
15560Binary word size. Default is 32; associated command is @kbd{b w}.
15561
15562@item
15563Stack size (not counting the value about to be pushed by @kbd{m g}).
15564This is zero if @kbd{m g} is executed with an empty stack.
15565
15566@item
15567Number radix. Default is 10; command is @kbd{d r}.
15568
15569@item
15570Floating-point format. This is the number of digits, plus the
15571constant 0 for normal notation, 10000 for scientific notation,
1557220000 for engineering notation, or 30000 for fixed-point notation.
15573These codes are acceptable as prefix arguments to the @kbd{d n}
15574command, but note that this may lose information: For example,
15575@kbd{d s} and @kbd{C-u 12 d s} have similar (but not quite
15576identical) effects if the current precision is 12, but they both
15577produce a code of 10012, which will be treated by @kbd{d n} as
15578@kbd{C-u 12 d s}. If the precision then changes, the float format
15579will still be frozen at 12 significant figures.
15580
15581@item
15582Angular mode. Default is 1 (degrees). Other values are 2 (radians)
15583and 3 (HMS). The @kbd{m d} command accepts these prefixes.
15584
15585@item
15586Symbolic mode. Value is 0 or 1; default is 0. Command is @kbd{m s}.
15587
15588@item
15589Fraction mode. Value is 0 or 1; default is 0. Command is @kbd{m f}.
15590
15591@item
15592Polar mode. Value is 0 (rectangular) or 1 (polar); default is 0.
15593Command is @kbd{m p}.
15594
15595@item
15596Matrix/scalar mode. Default value is @i{-1}. Value is 0 for scalar
15597mode, @i{-2} for matrix mode, or @i{N} for @c{$N\times N$}
15598@i{NxN} matrix mode. Command is @kbd{m v}.
15599
15600@item
15601Simplification mode. Default is 1. Value is @i{-1} for off (@kbd{m O}),
156020 for @kbd{m N}, 2 for @kbd{m B}, 3 for @kbd{m A}, 4 for @kbd{m E},
15603or 5 for @w{@kbd{m U}}. The @kbd{m D} command accepts these prefixes.
15604
15605@item
15606Infinite mode. Default is @i{-1} (off). Value is 1 if the mode is on,
15607or 0 if the mode is on with positive zeros. Command is @kbd{m i}.
15608@end enumerate
15609
15610For example, the sequence @kbd{M-1 m g RET 2 + ~ p} increases the
15611precision by two, leaving a copy of the old precision on the stack.
15612Later, @kbd{~ p} will restore the original precision using that
15613stack value. (This sequence might be especially useful inside a
15614keyboard macro.)
15615
15616As another example, @kbd{M-3 m g 1 - ~ DEL} deletes all but the
15617oldest (bottommost) stack entry.
15618
15619Yet another example: The HP-48 ``round'' command rounds a number
15620to the current displayed precision. You could roughly emulate this
15621in Calc with the sequence @kbd{M-5 m g 10000 % ~ c c}. (This
15622would not work for fixed-point mode, but it wouldn't be hard to
15623do a full emulation with the help of the @kbd{Z [} and @kbd{Z ]}
15624programming commands. @xref{Conditionals in Macros}.)
15625
15626@node Calc Mode Line, , Modes Variable, Mode Settings
15627@section The Calc Mode Line
15628
15629@noindent
15630@cindex Mode line indicators
15631This section is a summary of all symbols that can appear on the
15632Calc mode line, the highlighted bar that appears under the Calc
15633stack window (or under an editing window in Embedded Mode).
15634
15635The basic mode line format is:
15636
15637@example
15638--%%-Calc: 12 Deg @var{other modes} (Calculator)
15639@end example
15640
15641The @samp{%%} is the Emacs symbol for ``read-only''; it shows that
15642regular Emacs commands are not allowed to edit the stack buffer
15643as if it were text.
15644
15645The word @samp{Calc:} changes to @samp{CalcEmbed:} if Embedded Mode
15646is enabled. The words after this describe the various Calc modes
15647that are in effect.
15648
15649The first mode is always the current precision, an integer.
15650The second mode is always the angular mode, either @code{Deg},
15651@code{Rad}, or @code{Hms}.
15652
15653Here is a complete list of the remaining symbols that can appear
15654on the mode line:
15655
15656@table @code
15657@item Alg
15658Algebraic mode (@kbd{m a}; @pxref{Algebraic Entry}).
15659
15660@item Alg[(
15661Incomplete algebraic mode (@kbd{C-u m a}).
15662
15663@item Alg*
15664Total algebraic mode (@kbd{m t}).
15665
15666@item Symb
15667Symbolic mode (@kbd{m s}; @pxref{Symbolic Mode}).
15668
15669@item Matrix
15670Matrix mode (@kbd{m v}; @pxref{Matrix Mode}).
15671
15672@item Matrix@var{n}
15673Dimensioned matrix mode (@kbd{C-u @var{n} m v}).
15674
15675@item Scalar
15676Scalar mode (@kbd{m v}; @pxref{Matrix Mode}).
15677
15678@item Polar
15679Polar complex mode (@kbd{m p}; @pxref{Polar Mode}).
15680
15681@item Frac
15682Fraction mode (@kbd{m f}; @pxref{Fraction Mode}).
15683
15684@item Inf
15685Infinite mode (@kbd{m i}; @pxref{Infinite Mode}).
15686
15687@item +Inf
15688Positive infinite mode (@kbd{C-u 0 m i}).
15689
15690@item NoSimp
15691Default simplifications off (@kbd{m O}; @pxref{Simplification Modes}).
15692
15693@item NumSimp
15694Default simplifications for numeric arguments only (@kbd{m N}).
15695
15696@item BinSimp@var{w}
15697Binary-integer simplification mode; word size @var{w} (@kbd{m B}, @kbd{b w}).
15698
15699@item AlgSimp
15700Algebraic simplification mode (@kbd{m A}).
15701
15702@item ExtSimp
15703Extended algebraic simplification mode (@kbd{m E}).
15704
15705@item UnitSimp
15706Units simplification mode (@kbd{m U}).
15707
15708@item Bin
15709Current radix is 2 (@kbd{d 2}; @pxref{Radix Modes}).
15710
15711@item Oct
15712Current radix is 8 (@kbd{d 8}).
15713
15714@item Hex
15715Current radix is 16 (@kbd{d 6}).
15716
15717@item Radix@var{n}
15718Current radix is @var{n} (@kbd{d r}).
15719
15720@item Zero
15721Leading zeros (@kbd{d z}; @pxref{Radix Modes}).
15722
15723@item Big
15724Big language mode (@kbd{d B}; @pxref{Normal Language Modes}).
15725
15726@item Flat
15727One-line normal language mode (@kbd{d O}).
15728
15729@item Unform
15730Unformatted language mode (@kbd{d U}).
15731
15732@item C
15733C language mode (@kbd{d C}; @pxref{C FORTRAN Pascal}).
15734
15735@item Pascal
15736Pascal language mode (@kbd{d P}).
15737
15738@item Fortran
15739FORTRAN language mode (@kbd{d F}).
15740
15741@item TeX
15742@TeX{} language mode (@kbd{d T}; @pxref{TeX Language Mode}).
15743
15744@item Eqn
15745@dfn{Eqn} language mode (@kbd{d E}; @pxref{Eqn Language Mode}).
15746
15747@item Math
15748Mathematica language mode (@kbd{d M}; @pxref{Mathematica Language Mode}).
15749
15750@item Maple
15751Maple language mode (@kbd{d W}; @pxref{Maple Language Mode}).
15752
15753@item Norm@var{n}
15754Normal float mode with @var{n} digits (@kbd{d n}; @pxref{Float Formats}).
15755
15756@item Fix@var{n}
15757Fixed point mode with @var{n} digits after the point (@kbd{d f}).
15758
15759@item Sci
15760Scientific notation mode (@kbd{d s}).
15761
15762@item Sci@var{n}
15763Scientific notation with @var{n} digits (@kbd{d s}).
15764
15765@item Eng
15766Engineering notation mode (@kbd{d e}).
15767
15768@item Eng@var{n}
15769Engineering notation with @var{n} digits (@kbd{d e}).
15770
15771@item Left@var{n}
15772Left-justified display indented by @var{n} (@kbd{d <}; @pxref{Justification}).
15773
15774@item Right
15775Right-justified display (@kbd{d >}).
15776
15777@item Right@var{n}
15778Right-justified display with width @var{n} (@kbd{d >}).
15779
15780@item Center
15781Centered display (@kbd{d =}).
15782
15783@item Center@var{n}
15784Centered display with center column @var{n} (@kbd{d =}).
15785
15786@item Wid@var{n}
15787Line breaking with width @var{n} (@kbd{d b}; @pxref{Normal Language Modes}).
15788
15789@item Wide
15790No line breaking (@kbd{d b}).
15791
15792@item Break
15793Selections show deep structure (@kbd{j b}; @pxref{Making Selections}).
15794
15795@item Save
15796Record modes in @file{~/.emacs} (@kbd{m R}; @pxref{General Mode Commands}).
15797
15798@item Local
15799Record modes in Embedded buffer (@kbd{m R}).
15800
15801@item LocEdit
15802Record modes as editing-only in Embedded buffer (@kbd{m R}).
15803
15804@item LocPerm
15805Record modes as permanent-only in Embedded buffer (@kbd{m R}).
15806
15807@item Global
15808Record modes as global in Embedded buffer (@kbd{m R}).
15809
15810@item Manual
15811Automatic recomputation turned off (@kbd{m C}; @pxref{Automatic
15812Recomputation}).
15813
15814@item Graph
15815GNUPLOT process is alive in background (@pxref{Graphics}).
15816
15817@item Sel
15818Top-of-stack has a selection (Embedded only; @pxref{Making Selections}).
15819
15820@item Dirty
15821The stack display may not be up-to-date (@pxref{Display Modes}).
15822
15823@item Inv
15824``Inverse'' prefix was pressed (@kbd{I}; @pxref{Inverse and Hyperbolic}).
15825
15826@item Hyp
15827``Hyperbolic'' prefix was pressed (@kbd{H}).
15828
15829@item Keep
15830``Keep-arguments'' prefix was pressed (@kbd{K}).
15831
15832@item Narrow
15833Stack is truncated (@kbd{d t}; @pxref{Truncating the Stack}).
15834@end table
15835
15836In addition, the symbols @code{Active} and @code{~Active} can appear
15837as minor modes on an Embedded buffer's mode line. @xref{Embedded Mode}.
15838
15839@node Arithmetic, Scientific Functions, Mode Settings, Top
15840@chapter Arithmetic Functions
15841
15842@noindent
15843This chapter describes the Calc commands for doing simple calculations
15844on numbers, such as addition, absolute value, and square roots. These
15845commands work by removing the top one or two values from the stack,
15846performing the desired operation, and pushing the result back onto the
15847stack. If the operation cannot be performed, the result pushed is a
15848formula instead of a number, such as @samp{2/0} (because division by zero
15849is illegal) or @samp{sqrt(x)} (because the argument @samp{x} is a formula).
15850
15851Most of the commands described here can be invoked by a single keystroke.
15852Some of the more obscure ones are two-letter sequences beginning with
15853the @kbd{f} (``functions'') prefix key.
15854
15855@xref{Prefix Arguments}, for a discussion of the effect of numeric
15856prefix arguments on commands in this chapter which do not otherwise
15857interpret a prefix argument.
15858
15859@menu
15860* Basic Arithmetic::
15861* Integer Truncation::
15862* Complex Number Functions::
15863* Conversions::
15864* Date Arithmetic::
15865* Financial Functions::
15866* Binary Functions::
15867@end menu
15868
15869@node Basic Arithmetic, Integer Truncation, Arithmetic, Arithmetic
15870@section Basic Arithmetic
15871
15872@noindent
15873@kindex +
15874@pindex calc-plus
15875@c @mindex @null
15876@tindex +
15877The @kbd{+} (@code{calc-plus}) command adds two numbers. The numbers may
15878be any of the standard Calc data types. The resulting sum is pushed back
15879onto the stack.
15880
15881If both arguments of @kbd{+} are vectors or matrices (of matching dimensions),
15882the result is a vector or matrix sum. If one argument is a vector and the
15883other a scalar (i.e., a non-vector), the scalar is added to each of the
15884elements of the vector to form a new vector. If the scalar is not a
15885number, the operation is left in symbolic form: Suppose you added @samp{x}
15886to the vector @samp{[1,2]}. You may want the result @samp{[1+x,2+x]}, or
15887you may plan to substitute a 2-vector for @samp{x} in the future. Since
15888the Calculator can't tell which interpretation you want, it makes the
15889safest assumption. @xref{Reducing and Mapping}, for a way to add @samp{x}
15890to every element of a vector.
15891
15892If either argument of @kbd{+} is a complex number, the result will in general
15893be complex. If one argument is in rectangular form and the other polar,
15894the current Polar Mode determines the form of the result. If Symbolic
15895Mode is enabled, the sum may be left as a formula if the necessary
15896conversions for polar addition are non-trivial.
15897
15898If both arguments of @kbd{+} are HMS forms, the forms are added according to
15899the usual conventions of hours-minutes-seconds notation. If one argument
15900is an HMS form and the other is a number, that number is converted from
15901degrees or radians (depending on the current Angular Mode) to HMS format
15902and then the two HMS forms are added.
15903
15904If one argument of @kbd{+} is a date form, the other can be either a
15905real number, which advances the date by a certain number of days, or
15906an HMS form, which advances the date by a certain amount of time.
15907Subtracting two date forms yields the number of days between them.
15908Adding two date forms is meaningless, but Calc interprets it as the
15909subtraction of one date form and the negative of the other. (The
15910negative of a date form can be understood by remembering that dates
15911are stored as the number of days before or after Jan 1, 1 AD.)
15912
15913If both arguments of @kbd{+} are error forms, the result is an error form
15914with an appropriately computed standard deviation. If one argument is an
15915error form and the other is a number, the number is taken to have zero error.
15916Error forms may have symbolic formulas as their mean and/or error parts;
15917adding these will produce a symbolic error form result. However, adding an
15918error form to a plain symbolic formula (as in @samp{(a +/- b) + c}) will not
15919work, for the same reasons just mentioned for vectors. Instead you must
15920write @samp{(a +/- b) + (c +/- 0)}.
15921
15922If both arguments of @kbd{+} are modulo forms with equal values of @cite{M},
15923or if one argument is a modulo form and the other a plain number, the
15924result is a modulo form which represents the sum, modulo @cite{M}, of
15925the two values.
15926
15927If both arguments of @kbd{+} are intervals, the result is an interval
15928which describes all possible sums of the possible input values. If
15929one argument is a plain number, it is treated as the interval
15930@w{@samp{[x ..@: x]}}.
15931
15932If one argument of @kbd{+} is an infinity and the other is not, the
15933result is that same infinity. If both arguments are infinite and in
15934the same direction, the result is the same infinity, but if they are
15935infinite in different directions the result is @code{nan}.
15936
15937@kindex -
15938@pindex calc-minus
15939@c @mindex @null
15940@tindex -
15941The @kbd{-} (@code{calc-minus}) command subtracts two values. The top
15942number on the stack is subtracted from the one behind it, so that the
15943computation @kbd{5 @key{RET} 2 -} produces 3, not @i{-3}. All options
15944available for @kbd{+} are available for @kbd{-} as well.
15945
15946@kindex *
15947@pindex calc-times
15948@c @mindex @null
15949@tindex *
15950The @kbd{*} (@code{calc-times}) command multiplies two numbers. If one
15951argument is a vector and the other a scalar, the scalar is multiplied by
15952the elements of the vector to produce a new vector. If both arguments
15953are vectors, the interpretation depends on the dimensions of the
15954vectors: If both arguments are matrices, a matrix multiplication is
15955done. If one argument is a matrix and the other a plain vector, the
15956vector is interpreted as a row vector or column vector, whichever is
15957dimensionally correct. If both arguments are plain vectors, the result
15958is a single scalar number which is the dot product of the two vectors.
15959
15960If one argument of @kbd{*} is an HMS form and the other a number, the
15961HMS form is multiplied by that amount. It is an error to multiply two
15962HMS forms together, or to attempt any multiplication involving date
15963forms. Error forms, modulo forms, and intervals can be multiplied;
15964see the comments for addition of those forms. When two error forms
15965or intervals are multiplied they are considered to be statistically
15966independent; thus, @samp{[-2 ..@: 3] * [-2 ..@: 3]} is @samp{[-6 ..@: 9]},
15967whereas @w{@samp{[-2 ..@: 3] ^ 2}} is @samp{[0 ..@: 9]}.
15968
15969@kindex /
15970@pindex calc-divide
15971@c @mindex @null
15972@tindex /
15973The @kbd{/} (@code{calc-divide}) command divides two numbers. When
15974dividing a scalar @cite{B} by a square matrix @cite{A}, the computation
15975performed is @cite{B} times the inverse of @cite{A}. This also occurs
15976if @cite{B} is itself a vector or matrix, in which case the effect is
15977to solve the set of linear equations represented by @cite{B}. If @cite{B}
15978is a matrix with the same number of rows as @cite{A}, or a plain vector
15979(which is interpreted here as a column vector), then the equation
15980@cite{A X = B} is solved for the vector or matrix @cite{X}. Otherwise,
15981if @cite{B} is a non-square matrix with the same number of @emph{columns}
15982as @cite{A}, the equation @cite{X A = B} is solved. If you wish a vector
15983@cite{B} to be interpreted as a row vector to be solved as @cite{X A = B},
15984make it into a one-row matrix with @kbd{C-u 1 v p} first. To force a
15985left-handed solution with a square matrix @cite{B}, transpose @cite{A} and
15986@cite{B} before dividing, then transpose the result.
15987
15988HMS forms can be divided by real numbers or by other HMS forms. Error
15989forms can be divided in any combination of ways. Modulo forms where both
15990values and the modulo are integers can be divided to get an integer modulo
15991form result. Intervals can be divided; dividing by an interval that
15992encompasses zero or has zero as a limit will result in an infinite
15993interval.
15994
15995@kindex ^
15996@pindex calc-power
15997@c @mindex @null
15998@tindex ^
15999The @kbd{^} (@code{calc-power}) command raises a number to a power. If
16000the power is an integer, an exact result is computed using repeated
16001multiplications. For non-integer powers, Calc uses Newton's method or
16002logarithms and exponentials. Square matrices can be raised to integer
16003powers. If either argument is an error (or interval or modulo) form,
16004the result is also an error (or interval or modulo) form.
16005
16006@kindex I ^
16007@tindex nroot
16008If you press the @kbd{I} (inverse) key first, the @kbd{I ^} command
16009computes an Nth root: @kbd{125 RET 3 I ^} computes the number 5.
16010(This is entirely equivalent to @kbd{125 RET 1:3 ^}.)
16011
16012@kindex \
16013@pindex calc-idiv
16014@tindex idiv
16015@c @mindex @null
16016@tindex \
16017The @kbd{\} (@code{calc-idiv}) command divides two numbers on the stack
16018to produce an integer result. It is equivalent to dividing with
16019@key{/}, then rounding down with @kbd{F} (@code{calc-floor}), only a bit
16020more convenient and efficient. Also, since it is an all-integer
16021operation when the arguments are integers, it avoids problems that
16022@kbd{/ F} would have with floating-point roundoff.
16023
16024@kindex %
16025@pindex calc-mod
16026@c @mindex @null
16027@tindex %
16028The @kbd{%} (@code{calc-mod}) command performs a ``modulo'' (or ``remainder'')
16029operation. Mathematically, @samp{a%b = a - (a\b)*b}, and is defined
16030for all real numbers @cite{a} and @cite{b} (except @cite{b=0}). For
16031positive @cite{b}, the result will always be between 0 (inclusive) and
16032@cite{b} (exclusive). Modulo does not work for HMS forms and error forms.
16033If @cite{a} is a modulo form, its modulo is changed to @cite{b}, which
16034must be positive real number.
16035
16036@kindex :
16037@pindex calc-fdiv
16038@tindex fdiv
16039The @kbd{:} (@code{calc-fdiv}) command [@code{fdiv} function in a formula]
16040divides the two integers on the top of the stack to produce a fractional
16041result. This is a convenient shorthand for enabling Fraction Mode (with
16042@kbd{m f}) temporarily and using @samp{/}. Note that during numeric entry
16043the @kbd{:} key is interpreted as a fraction separator, so to divide 8 by 6
16044you would have to type @kbd{8 @key{RET} 6 @key{RET} :}. (Of course, in
16045this case, it would be much easier simply to enter the fraction directly
16046as @kbd{8:6 @key{RET}}!)
16047
16048@kindex n
16049@pindex calc-change-sign
16050The @kbd{n} (@code{calc-change-sign}) command negates the number on the top
16051of the stack. It works on numbers, vectors and matrices, HMS forms, date
16052forms, error forms, intervals, and modulo forms.
16053
16054@kindex A
16055@pindex calc-abs
16056@tindex abs
16057The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the absolute
16058value of a number. The result of @code{abs} is always a nonnegative
16059real number: With a complex argument, it computes the complex magnitude.
16060With a vector or matrix argument, it computes the Frobenius norm, i.e.,
16061the square root of the sum of the squares of the absolute values of the
16062elements. The absolute value of an error form is defined by replacing
16063the mean part with its absolute value and leaving the error part the same.
16064The absolute value of a modulo form is undefined. The absolute value of
16065an interval is defined in the obvious way.
16066
16067@kindex f A
16068@pindex calc-abssqr
16069@tindex abssqr
16070The @kbd{f A} (@code{calc-abssqr}) [@code{abssqr}] command computes the
16071absolute value squared of a number, vector or matrix, or error form.
16072
16073@kindex f s
16074@pindex calc-sign
16075@tindex sign
16076The @kbd{f s} (@code{calc-sign}) [@code{sign}] command returns 1 if its
16077argument is positive, @i{-1} if its argument is negative, or 0 if its
16078argument is zero. In algebraic form, you can also write @samp{sign(a,x)}
16079which evaluates to @samp{x * sign(a)}, i.e., either @samp{x}, @samp{-x}, or
16080zero depending on the sign of @samp{a}.
16081
16082@kindex &
16083@pindex calc-inv
16084@tindex inv
16085@cindex Reciprocal
16086The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
16087reciprocal of a number, i.e., @cite{1 / x}. Operating on a square
16088matrix, it computes the inverse of that matrix.
16089
16090@kindex Q
16091@pindex calc-sqrt
16092@tindex sqrt
16093The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] command computes the square
16094root of a number. For a negative real argument, the result will be a
16095complex number whose form is determined by the current Polar Mode.
16096
16097@kindex f h
16098@pindex calc-hypot
16099@tindex hypot
16100The @kbd{f h} (@code{calc-hypot}) [@code{hypot}] command computes the square
16101root of the sum of the squares of two numbers. That is, @samp{hypot(a,b)}
16102is the length of the hypotenuse of a right triangle with sides @cite{a}
16103and @cite{b}. If the arguments are complex numbers, their squared
16104magnitudes are used.
16105
16106@kindex f Q
16107@pindex calc-isqrt
16108@tindex isqrt
16109The @kbd{f Q} (@code{calc-isqrt}) [@code{isqrt}] command computes the
16110integer square root of an integer. This is the true square root of the
16111number, rounded down to an integer. For example, @samp{isqrt(10)}
16112produces 3. Note that, like @kbd{\} [@code{idiv}], this uses exact
16113integer arithmetic throughout to avoid roundoff problems. If the input
16114is a floating-point number or other non-integer value, this is exactly
16115the same as @samp{floor(sqrt(x))}.
16116
16117@kindex f n
16118@kindex f x
16119@pindex calc-min
16120@tindex min
16121@pindex calc-max
16122@tindex max
16123The @kbd{f n} (@code{calc-min}) [@code{min}] and @kbd{f x} (@code{calc-max})
16124[@code{max}] commands take the minimum or maximum of two real numbers,
16125respectively. These commands also work on HMS forms, date forms,
16126intervals, and infinities. (In algebraic expressions, these functions
16127take any number of arguments and return the maximum or minimum among
16128all the arguments.)@refill
16129
16130@kindex f M
16131@kindex f X
16132@pindex calc-mant-part
16133@tindex mant
16134@pindex calc-xpon-part
16135@tindex xpon
16136The @kbd{f M} (@code{calc-mant-part}) [@code{mant}] function extracts
16137the ``mantissa'' part @cite{m} of its floating-point argument; @kbd{f X}
16138(@code{calc-xpon-part}) [@code{xpon}] extracts the ``exponent'' part
16139@cite{e}. The original number is equal to @c{$m \times 10^e$}
16140@cite{m * 10^e},
16141where @cite{m} is in the interval @samp{[1.0 ..@: 10.0)} except that
16142@cite{m=e=0} if the original number is zero. For integers
16143and fractions, @code{mant} returns the number unchanged and @code{xpon}
16144returns zero. The @kbd{v u} (@code{calc-unpack}) command can also be
16145used to ``unpack'' a floating-point number; this produces an integer
16146mantissa and exponent, with the constraint that the mantissa is not
16147a multiple of ten (again except for the @cite{m=e=0} case).@refill
16148
16149@kindex f S
16150@pindex calc-scale-float
16151@tindex scf
16152The @kbd{f S} (@code{calc-scale-float}) [@code{scf}] function scales a number
16153by a given power of ten. Thus, @samp{scf(mant(x), xpon(x)) = x} for any
16154real @samp{x}. The second argument must be an integer, but the first
16155may actually be any numeric value. For example, @samp{scf(5,-2) = 0.05}
16156or @samp{1:20} depending on the current Fraction Mode.@refill
16157
16158@kindex f [
16159@kindex f ]
16160@pindex calc-decrement
16161@pindex calc-increment
16162@tindex decr
16163@tindex incr
16164The @kbd{f [} (@code{calc-decrement}) [@code{decr}] and @kbd{f ]}
16165(@code{calc-increment}) [@code{incr}] functions decrease or increase
16166a number by one unit. For integers, the effect is obvious. For
16167floating-point numbers, the change is by one unit in the last place.
16168For example, incrementing @samp{12.3456} when the current precision
16169is 6 digits yields @samp{12.3457}. If the current precision had been
161708 digits, the result would have been @samp{12.345601}. Incrementing
16171@samp{0.0} produces @c{$10^{-p}$}
16172@cite{10^-p}, where @cite{p} is the current
16173precision. These operations are defined only on integers and floats.
16174With numeric prefix arguments, they change the number by @cite{n} units.
16175
16176Note that incrementing followed by decrementing, or vice-versa, will
16177almost but not quite always cancel out. Suppose the precision is
161786 digits and the number @samp{9.99999} is on the stack. Incrementing
16179will produce @samp{10.0000}; decrementing will produce @samp{9.9999}.
16180One digit has been dropped. This is an unavoidable consequence of the
16181way floating-point numbers work.
16182
16183Incrementing a date/time form adjusts it by a certain number of seconds.
16184Incrementing a pure date form adjusts it by a certain number of days.
16185
16186@node Integer Truncation, Complex Number Functions, Basic Arithmetic, Arithmetic
16187@section Integer Truncation
16188
16189@noindent
16190There are four commands for truncating a real number to an integer,
16191differing mainly in their treatment of negative numbers. All of these
16192commands have the property that if the argument is an integer, the result
16193is the same integer. An integer-valued floating-point argument is converted
16194to integer form.
16195
16196If you press @kbd{H} (@code{calc-hyperbolic}) first, the result will be
16197expressed as an integer-valued floating-point number.
16198
16199@cindex Integer part of a number
16200@kindex F
16201@pindex calc-floor
16202@tindex floor
16203@tindex ffloor
16204@c @mindex @null
16205@kindex H F
16206The @kbd{F} (@code{calc-floor}) [@code{floor} or @code{ffloor}] command
16207truncates a real number to the next lower integer, i.e., toward minus
16208infinity. Thus @kbd{3.6 F} produces 3, but @kbd{_3.6 F} produces
16209@i{-4}.@refill
16210
16211@kindex I F
16212@pindex calc-ceiling
16213@tindex ceil
16214@tindex fceil
16215@c @mindex @null
16216@kindex H I F
16217The @kbd{I F} (@code{calc-ceiling}) [@code{ceil} or @code{fceil}]
16218command truncates toward positive infinity. Thus @kbd{3.6 I F} produces
162194, and @kbd{_3.6 I F} produces @i{-3}.@refill
16220
16221@kindex R
16222@pindex calc-round
16223@tindex round
16224@tindex fround
16225@c @mindex @null
16226@kindex H R
16227The @kbd{R} (@code{calc-round}) [@code{round} or @code{fround}] command
16228rounds to the nearest integer. When the fractional part is .5 exactly,
16229this command rounds away from zero. (All other rounding in the
16230Calculator uses this convention as well.) Thus @kbd{3.5 R} produces 4
16231but @kbd{3.4 R} produces 3; @kbd{_3.5 R} produces @i{-4}.@refill
16232
16233@kindex I R
16234@pindex calc-trunc
16235@tindex trunc
16236@tindex ftrunc
16237@c @mindex @null
16238@kindex H I R
16239The @kbd{I R} (@code{calc-trunc}) [@code{trunc} or @code{ftrunc}]
16240command truncates toward zero. In other words, it ``chops off''
16241everything after the decimal point. Thus @kbd{3.6 I R} produces 3 and
16242@kbd{_3.6 I R} produces @i{-3}.@refill
16243
16244These functions may not be applied meaningfully to error forms, but they
16245do work for intervals. As a convenience, applying @code{floor} to a
16246modulo form floors the value part of the form. Applied to a vector,
16247these functions operate on all elements of the vector one by one.
16248Applied to a date form, they operate on the internal numerical
16249representation of dates, converting a date/time form into a pure date.
16250
16251@c @starindex
16252@tindex rounde
16253@c @starindex
16254@tindex roundu
16255@c @starindex
16256@tindex frounde
16257@c @starindex
16258@tindex froundu
16259There are two more rounding functions which can only be entered in
16260algebraic notation. The @code{roundu} function is like @code{round}
16261except that it rounds up, toward plus infinity, when the fractional
16262part is .5. This distinction matters only for negative arguments.
16263Also, @code{rounde} rounds to an even number in the case of a tie,
16264rounding up or down as necessary. For example, @samp{rounde(3.5)} and
16265@samp{rounde(4.5)} both return 4, but @samp{rounde(5.5)} returns 6.
16266The advantage of round-to-even is that the net error due to rounding
16267after a long calculation tends to cancel out to zero. An important
16268subtle point here is that the number being fed to @code{rounde} will
16269already have been rounded to the current precision before @code{rounde}
16270begins. For example, @samp{rounde(2.500001)} with a current precision
16271of 6 will incorrectly, or at least surprisingly, yield 2 because the
16272argument will first have been rounded down to @cite{2.5} (which
16273@code{rounde} sees as an exact tie between 2 and 3).
16274
16275Each of these functions, when written in algebraic formulas, allows
16276a second argument which specifies the number of digits after the
16277decimal point to keep. For example, @samp{round(123.4567, 2)} will
16278produce the answer 123.46, and @samp{round(123.4567, -1)} will
16279produce 120 (i.e., the cutoff is one digit to the @emph{left} of
16280the decimal point). A second argument of zero is equivalent to
16281no second argument at all.
16282
16283@cindex Fractional part of a number
16284To compute the fractional part of a number (i.e., the amount which, when
16285added to `@t{floor(}@i{N}@t{)}', will produce @cite{N}) just take @cite{N}
16286modulo 1 using the @code{%} command.@refill
16287
16288Note also the @kbd{\} (integer quotient), @kbd{f I} (integer logarithm),
16289and @kbd{f Q} (integer square root) commands, which are analogous to
16290@kbd{/}, @kbd{B}, and @kbd{Q}, respectively, except that they take integer
16291arguments and return the result rounded down to an integer.
16292
16293@node Complex Number Functions, Conversions, Integer Truncation, Arithmetic
16294@section Complex Number Functions
16295
16296@noindent
16297@kindex J
16298@pindex calc-conj
16299@tindex conj
16300The @kbd{J} (@code{calc-conj}) [@code{conj}] command computes the
16301complex conjugate of a number. For complex number @cite{a+bi}, the
16302complex conjugate is @cite{a-bi}. If the argument is a real number,
16303this command leaves it the same. If the argument is a vector or matrix,
16304this command replaces each element by its complex conjugate.
16305
16306@kindex G
16307@pindex calc-argument
16308@tindex arg
16309The @kbd{G} (@code{calc-argument}) [@code{arg}] command computes the
16310``argument'' or polar angle of a complex number. For a number in polar
16311notation, this is simply the second component of the pair
16312`@t{(}@i{r}@t{;}@c{$\theta$}
16313@i{theta}@t{)}'.
16314The result is expressed according to the current angular mode and will
16315be in the range @i{-180} degrees (exclusive) to @i{+180} degrees
16316(inclusive), or the equivalent range in radians.@refill
16317
16318@pindex calc-imaginary
16319The @code{calc-imaginary} command multiplies the number on the
16320top of the stack by the imaginary number @cite{i = (0,1)}. This
16321command is not normally bound to a key in Calc, but it is available
16322on the @key{IMAG} button in Keypad Mode.
16323
16324@kindex f r
16325@pindex calc-re
16326@tindex re
16327The @kbd{f r} (@code{calc-re}) [@code{re}] command replaces a complex number
16328by its real part. This command has no effect on real numbers. (As an
16329added convenience, @code{re} applied to a modulo form extracts
16330the value part.)@refill
16331
16332@kindex f i
16333@pindex calc-im
16334@tindex im
16335The @kbd{f i} (@code{calc-im}) [@code{im}] command replaces a complex number
16336by its imaginary part; real numbers are converted to zero. With a vector
16337or matrix argument, these functions operate element-wise.@refill
16338
16339@c @mindex v p
16340@kindex v p (complex)
16341@pindex calc-pack
16342The @kbd{v p} (@code{calc-pack}) command can pack the top two numbers on
16343the the stack into a composite object such as a complex number. With
16344a prefix argument of @i{-1}, it produces a rectangular complex number;
16345with an argument of @i{-2}, it produces a polar complex number.
16346(Also, @pxref{Building Vectors}.)
16347
16348@c @mindex v u
16349@kindex v u (complex)
16350@pindex calc-unpack
16351The @kbd{v u} (@code{calc-unpack}) command takes the complex number
16352(or other composite object) on the top of the stack and unpacks it
16353into its separate components.
16354
16355@node Conversions, Date Arithmetic, Complex Number Functions, Arithmetic
16356@section Conversions
16357
16358@noindent
16359The commands described in this section convert numbers from one form
16360to another; they are two-key sequences beginning with the letter @kbd{c}.
16361
16362@kindex c f
16363@pindex calc-float
16364@tindex pfloat
16365The @kbd{c f} (@code{calc-float}) [@code{pfloat}] command converts the
16366number on the top of the stack to floating-point form. For example,
16367@cite{23} is converted to @cite{23.0}, @cite{3:2} is converted to
16368@cite{1.5}, and @cite{2.3} is left the same. If the value is a composite
16369object such as a complex number or vector, each of the components is
16370converted to floating-point. If the value is a formula, all numbers
16371in the formula are converted to floating-point. Note that depending
16372on the current floating-point precision, conversion to floating-point
16373format may lose information.@refill
16374
16375As a special exception, integers which appear as powers or subscripts
16376are not floated by @kbd{c f}. If you really want to float a power,
16377you can use a @kbd{j s} command to select the power followed by @kbd{c f}.
16378Because @kbd{c f} cannot examine the formula outside of the selection,
16379it does not notice that the thing being floated is a power.
16380@xref{Selecting Subformulas}.
16381
16382The normal @kbd{c f} command is ``pervasive'' in the sense that it
16383applies to all numbers throughout the formula. The @code{pfloat}
16384algebraic function never stays around in a formula; @samp{pfloat(a + 1)}
16385changes to @samp{a + 1.0} as soon as it is evaluated.
16386
16387@kindex H c f
16388@tindex float
16389With the Hyperbolic flag, @kbd{H c f} [@code{float}] operates
16390only on the number or vector of numbers at the top level of its
16391argument. Thus, @samp{float(1)} is 1.0, but @samp{float(a + 1)}
16392is left unevaluated because its argument is not a number.
16393
16394You should use @kbd{H c f} if you wish to guarantee that the final
16395value, once all the variables have been assigned, is a float; you
16396would use @kbd{c f} if you wish to do the conversion on the numbers
16397that appear right now.
16398
16399@kindex c F
16400@pindex calc-fraction
16401@tindex pfrac
16402The @kbd{c F} (@code{calc-fraction}) [@code{pfrac}] command converts a
16403floating-point number into a fractional approximation. By default, it
16404produces a fraction whose decimal representation is the same as the
16405input number, to within the current precision. You can also give a
16406numeric prefix argument to specify a tolerance, either directly, or,
16407if the prefix argument is zero, by using the number on top of the stack
16408as the tolerance. If the tolerance is a positive integer, the fraction
16409is correct to within that many significant figures. If the tolerance is
16410a non-positive integer, it specifies how many digits fewer than the current
16411precision to use. If the tolerance is a floating-point number, the
16412fraction is correct to within that absolute amount.
16413
16414@kindex H c F
16415@tindex frac
16416The @code{pfrac} function is pervasive, like @code{pfloat}.
16417There is also a non-pervasive version, @kbd{H c F} [@code{frac}],
16418which is analogous to @kbd{H c f} discussed above.
16419
16420@kindex c d
16421@pindex calc-to-degrees
16422@tindex deg
16423The @kbd{c d} (@code{calc-to-degrees}) [@code{deg}] command converts a
16424number into degrees form. The value on the top of the stack may be an
16425HMS form (interpreted as degrees-minutes-seconds), or a real number which
16426will be interpreted in radians regardless of the current angular mode.@refill
16427
16428@kindex c r
16429@pindex calc-to-radians
16430@tindex rad
16431The @kbd{c r} (@code{calc-to-radians}) [@code{rad}] command converts an
16432HMS form or angle in degrees into an angle in radians.
16433
16434@kindex c h
16435@pindex calc-to-hms
16436@tindex hms
16437The @kbd{c h} (@code{calc-to-hms}) [@code{hms}] command converts a real
16438number, interpreted according to the current angular mode, to an HMS
16439form describing the same angle. In algebraic notation, the @code{hms}
16440function also accepts three arguments: @samp{hms(@var{h}, @var{m}, @var{s})}.
16441(The three-argument version is independent of the current angular mode.)
16442
16443@pindex calc-from-hms
16444The @code{calc-from-hms} command converts the HMS form on the top of the
16445stack into a real number according to the current angular mode.
16446
16447@kindex c p
16448@kindex I c p
16449@pindex calc-polar
16450@tindex polar
16451@tindex rect
16452The @kbd{c p} (@code{calc-polar}) command converts the complex number on
16453the top of the stack from polar to rectangular form, or from rectangular
16454to polar form, whichever is appropriate. Real numbers are left the same.
16455This command is equivalent to the @code{rect} or @code{polar}
16456functions in algebraic formulas, depending on the direction of
16457conversion. (It uses @code{polar}, except that if the argument is
16458already a polar complex number, it uses @code{rect} instead. The
16459@kbd{I c p} command always uses @code{rect}.)@refill
16460
16461@kindex c c
16462@pindex calc-clean
16463@tindex pclean
16464The @kbd{c c} (@code{calc-clean}) [@code{pclean}] command ``cleans'' the
16465number on the top of the stack. Floating point numbers are re-rounded
16466according to the current precision. Polar numbers whose angular
16467components have strayed from the @i{-180} to @i{+180} degree range
16468are normalized. (Note that results will be undesirable if the current
16469angular mode is different from the one under which the number was
16470produced!) Integers and fractions are generally unaffected by this
16471operation. Vectors and formulas are cleaned by cleaning each component
16472number (i.e., pervasively).@refill
16473
16474If the simplification mode is set below the default level, it is raised
16475to the default level for the purposes of this command. Thus, @kbd{c c}
16476applies the default simplifications even if their automatic application
16477is disabled. @xref{Simplification Modes}.
16478
16479@cindex Roundoff errors, correcting
16480A numeric prefix argument to @kbd{c c} sets the floating-point precision
16481to that value for the duration of the command. A positive prefix (of at
16482least 3) sets the precision to the specified value; a negative or zero
16483prefix decreases the precision by the specified amount.
16484
16485@kindex c 0-9
16486@pindex calc-clean-num
16487The keystroke sequences @kbd{c 0} through @kbd{c 9} are equivalent
16488to @kbd{c c} with the corresponding negative prefix argument. If roundoff
16489errors have changed 2.0 into 1.999999, typing @kbd{c 1} to clip off one
16490decimal place often conveniently does the trick.
16491
16492The @kbd{c c} command with a numeric prefix argument, and the @kbd{c 0}
16493through @kbd{c 9} commands, also ``clip'' very small floating-point
16494numbers to zero. If the exponent is less than or equal to the negative
16495of the specified precision, the number is changed to 0.0. For example,
16496if the current precision is 12, then @kbd{c 2} changes the vector
16497@samp{[1e-8, 1e-9, 1e-10, 1e-11]} to @samp{[1e-8, 1e-9, 0, 0]}.
16498Numbers this small generally arise from roundoff noise.
16499
16500If the numbers you are using really are legitimately this small,
16501you should avoid using the @kbd{c 0} through @kbd{c 9} commands.
16502(The plain @kbd{c c} command rounds to the current precision but
16503does not clip small numbers.)
16504
16505One more property of @kbd{c 0} through @kbd{c 9}, and of @kbd{c c} with
16506a prefix argument, is that integer-valued floats are converted to
16507plain integers, so that @kbd{c 1} on @samp{[1., 1.5, 2., 2.5, 3.]}
16508produces @samp{[1, 1.5, 2, 2.5, 3]}. This is not done for huge
16509numbers (@samp{1e100} is technically an integer-valued float, but
16510you wouldn't want it automatically converted to a 100-digit integer).
16511
16512@kindex H c 0-9
16513@kindex H c c
16514@tindex clean
16515With the Hyperbolic flag, @kbd{H c c} and @kbd{H c 0} through @kbd{H c 9}
16516operate non-pervasively [@code{clean}].
16517
16518@node Date Arithmetic, Financial Functions, Conversions, Arithmetic
16519@section Date Arithmetic
16520
16521@noindent
16522@cindex Date arithmetic, additional functions
16523The commands described in this section perform various conversions
16524and calculations involving date forms (@pxref{Date Forms}). They
16525use the @kbd{t} (for time/date) prefix key followed by shifted
16526letters.
16527
16528The simplest date arithmetic is done using the regular @kbd{+} and @kbd{-}
16529commands. In particular, adding a number to a date form advances the
16530date form by a certain number of days; adding an HMS form to a date
16531form advances the date by a certain amount of time; and subtracting two
16532date forms produces a difference measured in days. The commands
16533described here provide additional, more specialized operations on dates.
16534
16535Many of these commands accept a numeric prefix argument; if you give
16536plain @kbd{C-u} as the prefix, these commands will instead take the
16537additional argument from the top of the stack.
16538
16539@menu
16540* Date Conversions::
16541* Date Functions::
16542* Time Zones::
16543* Business Days::
16544@end menu
16545
16546@node Date Conversions, Date Functions, Date Arithmetic, Date Arithmetic
16547@subsection Date Conversions
16548
16549@noindent
16550@kindex t D
16551@pindex calc-date
16552@tindex date
16553The @kbd{t D} (@code{calc-date}) [@code{date}] command converts a
16554date form into a number, measured in days since Jan 1, 1 AD. The
16555result will be an integer if @var{date} is a pure date form, or a
16556fraction or float if @var{date} is a date/time form. Or, if its
16557argument is a number, it converts this number into a date form.
16558
16559With a numeric prefix argument, @kbd{t D} takes that many objects
16560(up to six) from the top of the stack and interprets them in one
16561of the following ways:
16562
16563The @samp{date(@var{year}, @var{month}, @var{day})} function
16564builds a pure date form out of the specified year, month, and
16565day, which must all be integers. @var{Year} is a year number,
16566such as 1991 (@emph{not} the same as 91!). @var{Month} must be
16567an integer in the range 1 to 12; @var{day} must be in the range
165681 to 31. If the specified month has fewer than 31 days and
16569@var{day} is too large, the equivalent day in the following
16570month will be used.
16571
16572The @samp{date(@var{month}, @var{day})} function builds a
16573pure date form using the current year, as determined by the
16574real-time clock.
16575
16576The @samp{date(@var{year}, @var{month}, @var{day}, @var{hms})}
16577function builds a date/time form using an @var{hms} form.
16578
16579The @samp{date(@var{year}, @var{month}, @var{day}, @var{hour},
16580@var{minute}, @var{second})} function builds a date/time form.
16581@var{hour} should be an integer in the range 0 to 23;
16582@var{minute} should be an integer in the range 0 to 59;
16583@var{second} should be any real number in the range @samp{[0 .. 60)}.
16584The last two arguments default to zero if omitted.
16585
16586@kindex t J
16587@pindex calc-julian
16588@tindex julian
16589@cindex Julian day counts, conversions
16590The @kbd{t J} (@code{calc-julian}) [@code{julian}] command converts
16591a date form into a Julian day count, which is the number of days
16592since noon on Jan 1, 4713 BC. A pure date is converted to an integer
16593Julian count representing noon of that day. A date/time form is
16594converted to an exact floating-point Julian count, adjusted to
16595interpret the date form in the current time zone but the Julian
16596day count in Greenwich Mean Time. A numeric prefix argument allows
16597you to specify the time zone; @pxref{Time Zones}. Use a prefix of
16598zero to suppress the time zone adjustment. Note that pure date forms
16599are never time-zone adjusted.
16600
16601This command can also do the opposite conversion, from a Julian day
16602count (either an integer day, or a floating-point day and time in
16603the GMT zone), into a pure date form or a date/time form in the
16604current or specified time zone.
16605
16606@kindex t U
16607@pindex calc-unix-time
16608@tindex unixtime
16609@cindex Unix time format, conversions
16610The @kbd{t U} (@code{calc-unix-time}) [@code{unixtime}] command
16611converts a date form into a Unix time value, which is the number of
16612seconds since midnight on Jan 1, 1970, or vice-versa. The numeric result
16613will be an integer if the current precision is 12 or less; for higher
16614precisions, the result may be a float with (@var{precision}@i{-}12)
16615digits after the decimal. Just as for @kbd{t J}, the numeric time
16616is interpreted in the GMT time zone and the date form is interpreted
16617in the current or specified zone. Some systems use Unix-like
16618numbering but with the local time zone; give a prefix of zero to
16619suppress the adjustment if so.
16620
16621@kindex t C
16622@pindex calc-convert-time-zones
16623@tindex tzconv
16624@cindex Time Zones, converting between
16625The @kbd{t C} (@code{calc-convert-time-zones}) [@code{tzconv}]
16626command converts a date form from one time zone to another. You
16627are prompted for each time zone name in turn; you can answer with
16628any suitable Calc time zone expression (@pxref{Time Zones}).
16629If you answer either prompt with a blank line, the local time
16630zone is used for that prompt. You can also answer the first
16631prompt with @kbd{$} to take the two time zone names from the
16632stack (and the date to be converted from the third stack level).
16633
16634@node Date Functions, Business Days, Date Conversions, Date Arithmetic
16635@subsection Date Functions
16636
16637@noindent
16638@kindex t N
16639@pindex calc-now
16640@tindex now
16641The @kbd{t N} (@code{calc-now}) [@code{now}] command pushes the
16642current date and time on the stack as a date form. The time is
16643reported in terms of the specified time zone; with no numeric prefix
16644argument, @kbd{t N} reports for the current time zone.
16645
16646@kindex t P
16647@pindex calc-date-part
16648The @kbd{t P} (@code{calc-date-part}) command extracts one part
16649of a date form. The prefix argument specifies the part; with no
16650argument, this command prompts for a part code from 1 to 9.
16651The various part codes are described in the following paragraphs.
16652
16653@tindex year
16654The @kbd{M-1 t P} [@code{year}] function extracts the year number
16655from a date form as an integer, e.g., 1991. This and the
16656following functions will also accept a real number for an
16657argument, which is interpreted as a standard Calc day number.
16658Note that this function will never return zero, since the year
166591 BC immediately precedes the year 1 AD.
16660
16661@tindex month
16662The @kbd{M-2 t P} [@code{month}] function extracts the month number
16663from a date form as an integer in the range 1 to 12.
16664
16665@tindex day
16666The @kbd{M-3 t P} [@code{day}] function extracts the day number
16667from a date form as an integer in the range 1 to 31.
16668
16669@tindex hour
16670The @kbd{M-4 t P} [@code{hour}] function extracts the hour from
16671a date form as an integer in the range 0 (midnight) to 23. Note
16672that 24-hour time is always used. This returns zero for a pure
16673date form. This function (and the following two) also accept
16674HMS forms as input.
16675
16676@tindex minute
16677The @kbd{M-5 t P} [@code{minute}] function extracts the minute
16678from a date form as an integer in the range 0 to 59.
16679
16680@tindex second
16681The @kbd{M-6 t P} [@code{second}] function extracts the second
16682from a date form. If the current precision is 12 or less,
16683the result is an integer in the range 0 to 59. For higher
16684precisions, the result may instead be a floating-point number.
16685
16686@tindex weekday
16687The @kbd{M-7 t P} [@code{weekday}] function extracts the weekday
16688number from a date form as an integer in the range 0 (Sunday)
16689to 6 (Saturday).
16690
16691@tindex yearday
16692The @kbd{M-8 t P} [@code{yearday}] function extracts the day-of-year
16693number from a date form as an integer in the range 1 (January 1)
16694to 366 (December 31 of a leap year).
16695
16696@tindex time
16697The @kbd{M-9 t P} [@code{time}] function extracts the time portion
16698of a date form as an HMS form. This returns @samp{0@@ 0' 0"}
16699for a pure date form.
16700
16701@kindex t M
16702@pindex calc-new-month
16703@tindex newmonth
16704The @kbd{t M} (@code{calc-new-month}) [@code{newmonth}] command
16705computes a new date form that represents the first day of the month
16706specified by the input date. The result is always a pure date
16707form; only the year and month numbers of the input are retained.
16708With a numeric prefix argument @var{n} in the range from 1 to 31,
16709@kbd{t M} computes the @var{n}th day of the month. (If @var{n}
16710is greater than the actual number of days in the month, or if
16711@var{n} is zero, the last day of the month is used.)
16712
16713@kindex t Y
16714@pindex calc-new-year
16715@tindex newyear
16716The @kbd{t Y} (@code{calc-new-year}) [@code{newyear}] command
16717computes a new pure date form that represents the first day of
16718the year specified by the input. The month, day, and time
16719of the input date form are lost. With a numeric prefix argument
16720@var{n} in the range from 1 to 366, @kbd{t Y} computes the
16721@var{n}th day of the year (366 is treated as 365 in non-leap
16722years). A prefix argument of 0 computes the last day of the
16723year (December 31). A negative prefix argument from @i{-1} to
16724@i{-12} computes the first day of the @var{n}th month of the year.
16725
16726@kindex t W
16727@pindex calc-new-week
16728@tindex newweek
16729The @kbd{t W} (@code{calc-new-week}) [@code{newweek}] command
16730computes a new pure date form that represents the Sunday on or before
16731the input date. With a numeric prefix argument, it can be made to
16732use any day of the week as the starting day; the argument must be in
16733the range from 0 (Sunday) to 6 (Saturday). This function always
16734subtracts between 0 and 6 days from the input date.
16735
16736Here's an example use of @code{newweek}: Find the date of the next
16737Wednesday after a given date. Using @kbd{M-3 t W} or @samp{newweek(d, 3)}
16738will give you the @emph{preceding} Wednesday, so @samp{newweek(d+7, 3)}
16739will give you the following Wednesday. A further look at the definition
16740of @code{newweek} shows that if the input date is itself a Wednesday,
16741this formula will return the Wednesday one week in the future. An
16742exercise for the reader is to modify this formula to yield the same day
16743if the input is already a Wednesday. Another interesting exercise is
16744to preserve the time-of-day portion of the input (@code{newweek} resets
16745the time to midnight; hint:@: how can @code{newweek} be defined in terms
16746of the @code{weekday} function?).
16747
16748@c @starindex
16749@tindex pwday
16750The @samp{pwday(@var{date})} function (not on any key) computes the
16751day-of-month number of the Sunday on or before @var{date}. With
16752two arguments, @samp{pwday(@var{date}, @var{day})} computes the day
16753number of the Sunday on or before day number @var{day} of the month
16754specified by @var{date}. The @var{day} must be in the range from
167557 to 31; if the day number is greater than the actual number of days
16756in the month, the true number of days is used instead. Thus
16757@samp{pwday(@var{date}, 7)} finds the first Sunday of the month, and
16758@samp{pwday(@var{date}, 31)} finds the last Sunday of the month.
16759With a third @var{weekday} argument, @code{pwday} can be made to look
16760for any day of the week instead of Sunday.
16761
16762@kindex t I
16763@pindex calc-inc-month
16764@tindex incmonth
16765The @kbd{t I} (@code{calc-inc-month}) [@code{incmonth}] command
16766increases a date form by one month, or by an arbitrary number of
16767months specified by a numeric prefix argument. The time portion,
16768if any, of the date form stays the same. The day also stays the
16769same, except that if the new month has fewer days the day
16770number may be reduced to lie in the valid range. For example,
16771@samp{incmonth(<Jan 31, 1991>)} produces @samp{<Feb 28, 1991>}.
16772Because of this, @kbd{t I t I} and @kbd{M-2 t I} do not always give
16773the same results (@samp{<Mar 28, 1991>} versus @samp{<Mar 31, 1991>}
16774in this case).
16775
16776@c @starindex
16777@tindex incyear
16778The @samp{incyear(@var{date}, @var{step})} function increases
16779a date form by the specified number of years, which may be
16780any positive or negative integer. Note that @samp{incyear(d, n)}
16781is equivalent to @w{@samp{incmonth(d, 12*n)}}, but these do not have
16782simple equivalents in terms of day arithmetic because
16783months and years have varying lengths. If the @var{step}
16784argument is omitted, 1 year is assumed. There is no keyboard
16785command for this function; use @kbd{C-u 12 t I} instead.
16786
16787There is no @code{newday} function at all because @kbd{F} [@code{floor}]
16788serves this purpose. Similarly, instead of @code{incday} and
16789@code{incweek} simply use @cite{d + n} or @cite{d + 7 n}.
16790
16791@xref{Basic Arithmetic}, for the @kbd{f ]} [@code{incr}] command
16792which can adjust a date/time form by a certain number of seconds.
16793
16794@node Business Days, Time Zones, Date Functions, Date Arithmetic
16795@subsection Business Days
16796
16797@noindent
16798Often time is measured in ``business days'' or ``working days,''
16799where weekends and holidays are skipped. Calc's normal date
16800arithmetic functions use calendar days, so that subtracting two
16801consecutive Mondays will yield a difference of 7 days. By contrast,
16802subtracting two consecutive Mondays would yield 5 business days
16803(assuming two-day weekends and the absence of holidays).
16804
16805@kindex t +
16806@kindex t -
16807@tindex badd
16808@tindex bsub
16809@pindex calc-business-days-plus
16810@pindex calc-business-days-minus
16811The @kbd{t +} (@code{calc-business-days-plus}) [@code{badd}]
16812and @kbd{t -} (@code{calc-business-days-minus}) [@code{bsub}]
16813commands perform arithmetic using business days. For @kbd{t +},
16814one argument must be a date form and the other must be a real
16815number (positive or negative). If the number is not an integer,
16816then a certain amount of time is added as well as a number of
16817days; for example, adding 0.5 business days to a time in Friday
16818evening will produce a time in Monday morning. It is also
16819possible to add an HMS form; adding @samp{12@@ 0' 0"} also adds
16820half a business day. For @kbd{t -}, the arguments are either a
16821date form and a number or HMS form, or two date forms, in which
16822case the result is the number of business days between the two
16823dates.
16824
16825@cindex @code{Holidays} variable
16826@vindex Holidays
16827By default, Calc considers any day that is not a Saturday or
16828Sunday to be a business day. You can define any number of
16829additional holidays by editing the variable @code{Holidays}.
16830(There is an @w{@kbd{s H}} convenience command for editing this
16831variable.) Initially, @code{Holidays} contains the vector
16832@samp{[sat, sun]}. Entries in the @code{Holidays} vector may
16833be any of the following kinds of objects:
16834
16835@itemize @bullet
16836@item
16837Date forms (pure dates, not date/time forms). These specify
16838particular days which are to be treated as holidays.
16839
16840@item
16841Intervals of date forms. These specify a range of days, all of
16842which are holidays (e.g., Christmas week). @xref{Interval Forms}.
16843
16844@item
16845Nested vectors of date forms. Each date form in the vector is
16846considered to be a holiday.
16847
16848@item
16849Any Calc formula which evaluates to one of the above three things.
16850If the formula involves the variable @cite{y}, it stands for a
16851yearly repeating holiday; @cite{y} will take on various year
16852numbers like 1992. For example, @samp{date(y, 12, 25)} specifies
16853Christmas day, and @samp{newweek(date(y, 11, 7), 4) + 21} specifies
16854Thanksgiving (which is held on the fourth Thursday of November).
16855If the formula involves the variable @cite{m}, that variable
16856takes on month numbers from 1 to 12: @samp{date(y, m, 15)} is
16857a holiday that takes place on the 15th of every month.
16858
16859@item
16860A weekday name, such as @code{sat} or @code{sun}. This is really
16861a variable whose name is a three-letter, lower-case day name.
16862
16863@item
16864An interval of year numbers (integers). This specifies the span of
16865years over which this holiday list is to be considered valid. Any
16866business-day arithmetic that goes outside this range will result
16867in an error message. Use this if you are including an explicit
16868list of holidays, rather than a formula to generate them, and you
16869want to make sure you don't accidentally go beyond the last point
16870where the holidays you entered are complete. If there is no
16871limiting interval in the @code{Holidays} vector, the default
16872@samp{[1 .. 2737]} is used. (This is the absolute range of years
16873for which Calc's business-day algorithms will operate.)
16874
16875@item
16876An interval of HMS forms. This specifies the span of hours that
16877are to be considered one business day. For example, if this
16878range is @samp{[9@@ 0' 0" .. 17@@ 0' 0"]} (i.e., 9am to 5pm), then
16879the business day is only eight hours long, so that @kbd{1.5 t +}
16880on @samp{<4:00pm Fri Dec 13, 1991>} will add one business day and
16881four business hours to produce @samp{<12:00pm Tue Dec 17, 1991>}.
16882Likewise, @kbd{t -} will now express differences in time as
16883fractions of an eight-hour day. Times before 9am will be treated
16884as 9am by business date arithmetic, and times at or after 5pm will
16885be treated as 4:59:59pm. If there is no HMS interval in @code{Holidays},
16886the full 24-hour day @samp{[0@ 0' 0" .. 24@ 0' 0"]} is assumed.
16887(Regardless of the type of bounds you specify, the interval is
16888treated as inclusive on the low end and exclusive on the high end,
16889so that the work day goes from 9am up to, but not including, 5pm.)
16890@end itemize
16891
16892If the @code{Holidays} vector is empty, then @kbd{t +} and
16893@kbd{t -} will act just like @kbd{+} and @kbd{-} because there will
16894then be no difference between business days and calendar days.
16895
16896Calc expands the intervals and formulas you give into a complete
16897list of holidays for internal use. This is done mainly to make
16898sure it can detect multiple holidays. (For example,
16899@samp{<Jan 1, 1989>} is both New Year's Day and a Sunday, but
16900Calc's algorithms take care to count it only once when figuring
16901the number of holidays between two dates.)
16902
16903Since the complete list of holidays for all the years from 1 to
169042737 would be huge, Calc actually computes only the part of the
16905list between the smallest and largest years that have been involved
16906in business-day calculations so far. Normally, you won't have to
16907worry about this. Keep in mind, however, that if you do one
16908calculation for 1992, and another for 1792, even if both involve
16909only a small range of years, Calc will still work out all the
16910holidays that fall in that 200-year span.
16911
16912If you add a (positive) number of days to a date form that falls on a
16913weekend or holiday, the date form is treated as if it were the most
16914recent business day. (Thus adding one business day to a Friday,
16915Saturday, or Sunday will all yield the following Monday.) If you
16916subtract a number of days from a weekend or holiday, the date is
16917effectively on the following business day. (So subtracting one business
16918day from Saturday, Sunday, or Monday yields the preceding Friday.) The
16919difference between two dates one or both of which fall on holidays
16920equals the number of actual business days between them. These
16921conventions are consistent in the sense that, if you add @var{n}
16922business days to any date, the difference between the result and the
16923original date will come out to @var{n} business days. (It can't be
16924completely consistent though; a subtraction followed by an addition
16925might come out a bit differently, since @kbd{t +} is incapable of
16926producing a date that falls on a weekend or holiday.)
16927
16928@c @starindex
16929@tindex holiday
16930There is a @code{holiday} function, not on any keys, that takes
16931any date form and returns 1 if that date falls on a weekend or
16932holiday, as defined in @code{Holidays}, or 0 if the date is a
16933business day.
16934
16935@node Time Zones, , Business Days, Date Arithmetic
16936@subsection Time Zones
16937
16938@noindent
16939@cindex Time zones
16940@cindex Daylight savings time
16941Time zones and daylight savings time are a complicated business.
16942The conversions to and from Julian and Unix-style dates automatically
16943compute the correct time zone and daylight savings adjustment to use,
16944provided they can figure out this information. This section describes
16945Calc's time zone adjustment algorithm in detail, in case you want to
16946do conversions in different time zones or in case Calc's algorithms
16947can't determine the right correction to use.
16948
16949Adjustments for time zones and daylight savings time are done by
16950@kbd{t U}, @kbd{t J}, @kbd{t N}, and @kbd{t C}, but not by any other
16951commands. In particular, @samp{<may 1 1991> - <apr 1 1991>} evaluates
16952to exactly 30 days even though there is a daylight-savings
16953transition in between. This is also true for Julian pure dates:
16954@samp{julian(<may 1 1991>) - julian(<apr 1 1991>)}. But Julian
16955and Unix date/times will adjust for daylight savings time:
16956@samp{julian(<12am may 1 1991>) - julian(<12am apr 1 1991>)}
16957evaluates to @samp{29.95834} (that's 29 days and 23 hours)
16958because one hour was lost when daylight savings commenced on
16959April 7, 1991.
16960
16961In brief, the idiom @samp{julian(@var{date1}) - julian(@var{date2})}
16962computes the actual number of 24-hour periods between two dates, whereas
16963@samp{@var{date1} - @var{date2}} computes the number of calendar
16964days between two dates without taking daylight savings into account.
16965
16966@pindex calc-time-zone
16967@c @starindex
16968@tindex tzone
16969The @code{calc-time-zone} [@code{tzone}] command converts the time
16970zone specified by its numeric prefix argument into a number of
16971seconds difference from Greenwich mean time (GMT). If the argument
16972is a number, the result is simply that value multiplied by 3600.
16973Typical arguments for North America are 5 (Eastern) or 8 (Pacific). If
16974Daylight Savings time is in effect, one hour should be subtracted from
16975the normal difference.
16976
16977If you give a prefix of plain @kbd{C-u}, @code{calc-time-zone} (like other
16978date arithmetic commands that include a time zone argument) takes the
16979zone argument from the top of the stack. (In the case of @kbd{t J}
16980and @kbd{t U}, the normal argument is then taken from the second-to-top
16981stack position.) This allows you to give a non-integer time zone
16982adjustment. The time-zone argument can also be an HMS form, or
16983it can be a variable which is a time zone name in upper- or lower-case.
16984For example @samp{tzone(PST) = tzone(8)} and @samp{tzone(pdt) = tzone(7)}
16985(for Pacific standard and daylight savings times, respectively).
16986
16987North American and European time zone names are defined as follows;
16988note that for each time zone there is one name for standard time,
16989another for daylight savings time, and a third for ``generalized'' time
16990in which the daylight savings adjustment is computed from context.
16991
16992@group
16993@smallexample
16994YST PST MST CST EST AST NST GMT WET MET MEZ
16995 9 8 7 6 5 4 3.5 0 -1 -2 -2
16996
16997YDT PDT MDT CDT EDT ADT NDT BST WETDST METDST MESZ
16998 8 7 6 5 4 3 2.5 -1 -2 -3 -3
16999
17000YGT PGT MGT CGT EGT AGT NGT BGT WEGT MEGT MEGZ
170019/8 8/7 7/6 6/5 5/4 4/3 3.5/2.5 0/-1 -1/-2 -2/-3 -2/-3
17002@end smallexample
17003@end group
17004
17005@vindex math-tzone-names
17006To define time zone names that do not appear in the above table,
17007you must modify the Lisp variable @code{math-tzone-names}. This
17008is a list of lists describing the different time zone names; its
17009structure is best explained by an example. The three entries for
17010Pacific Time look like this:
17011
17012@group
17013@smallexample
17014( ( "PST" 8 0 ) ; Name as an upper-case string, then standard
17015 ( "PDT" 8 -1 ) ; adjustment, then daylight savings adjustment.
17016 ( "PGT" 8 "PST" "PDT" ) ) ; Generalized time zone.
17017@end smallexample
17018@end group
17019
17020@cindex @code{TimeZone} variable
17021@vindex TimeZone
17022With no arguments, @code{calc-time-zone} or @samp{tzone()} obtains an
17023argument from the Calc variable @code{TimeZone} if a value has been
17024stored for that variable. If not, Calc runs the Unix @samp{date}
17025command and looks for one of the above time zone names in the output;
17026if this does not succeed, @samp{tzone()} leaves itself unevaluated.
17027The time zone name in the @samp{date} output may be followed by a signed
17028adjustment, e.g., @samp{GMT+5} or @samp{GMT+0500} which specifies a
17029number of hours and minutes to be added to the base time zone.
17030Calc stores the time zone it finds into @code{TimeZone} to speed
17031later calls to @samp{tzone()}.
17032
17033The special time zone name @code{local} is equivalent to no argument,
17034i.e., it uses the local time zone as obtained from the @code{date}
17035command.
17036
17037If the time zone name found is one of the standard or daylight
17038savings zone names from the above table, and Calc's internal
17039daylight savings algorithm says that time and zone are consistent
17040(e.g., @code{PDT} accompanies a date that Calc's algorithm would also
17041consider to be daylight savings, or @code{PST} accompanies a date
17042that Calc would consider to be standard time), then Calc substitutes
17043the corresponding generalized time zone (like @code{PGT}).
17044
17045If your system does not have a suitable @samp{date} command, you
17046may wish to put a @samp{(setq var-TimeZone ...)} in your Emacs
17047initialization file to set the time zone. The easiest way to do
17048this is to edit the @code{TimeZone} variable using Calc's @kbd{s T}
17049command, then use the @kbd{s p} (@code{calc-permanent-variable})
17050command to save the value of @code{TimeZone} permanently.
17051
17052The @kbd{t J} and @code{t U} commands with no numeric prefix
17053arguments do the same thing as @samp{tzone()}. If the current
17054time zone is a generalized time zone, e.g., @code{EGT}, Calc
17055examines the date being converted to tell whether to use standard
17056or daylight savings time. But if the current time zone is explicit,
17057e.g., @code{EST} or @code{EDT}, then that adjustment is used exactly
17058and Calc's daylight savings algorithm is not consulted.
17059
17060Some places don't follow the usual rules for daylight savings time.
17061The state of Arizona, for example, does not observe daylight savings
17062time. If you run Calc during the winter season in Arizona, the
17063Unix @code{date} command will report @code{MST} time zone, which
17064Calc will change to @code{MGT}. If you then convert a time that
17065lies in the summer months, Calc will apply an incorrect daylight
17066savings time adjustment. To avoid this, set your @code{TimeZone}
17067variable explicitly to @code{MST} to force the use of standard,
17068non-daylight-savings time.
17069
17070@vindex math-daylight-savings-hook
17071@findex math-std-daylight-savings
17072By default Calc always considers daylight savings time to begin at
170732 a.m.@: on the first Sunday of April, and to end at 2 a.m.@: on the
17074last Sunday of October. This is the rule that has been in effect
17075in North America since 1987. If you are in a country that uses
17076different rules for computing daylight savings time, you have two
17077choices: Write your own daylight savings hook, or control time
17078zones explicitly by setting the @code{TimeZone} variable and/or
17079always giving a time-zone argument for the conversion functions.
17080
17081The Lisp variable @code{math-daylight-savings-hook} holds the
17082name of a function that is used to compute the daylight savings
17083adjustment for a given date. The default is
17084@code{math-std-daylight-savings}, which computes an adjustment
17085(either 0 or @i{-1}) using the North American rules given above.
17086
17087The daylight savings hook function is called with four arguments:
17088The date, as a floating-point number in standard Calc format;
17089a six-element list of the date decomposed into year, month, day,
17090hour, minute, and second, respectively; a string which contains
17091the generalized time zone name in upper-case, e.g., @code{"WEGT"};
17092and a special adjustment to be applied to the hour value when
17093converting into a generalized time zone (see below).
17094
17095@findex math-prev-weekday-in-month
17096The Lisp function @code{math-prev-weekday-in-month} is useful for
17097daylight savings computations. This is an internal version of
17098the user-level @code{pwday} function described in the previous
17099section. It takes four arguments: The floating-point date value,
17100the corresponding six-element date list, the day-of-month number,
17101and the weekday number (0-6).
17102
17103The default daylight savings hook ignores the time zone name, but a
17104more sophisticated hook could use different algorithms for different
17105time zones. It would also be possible to use different algorithms
17106depending on the year number, but the default hook always uses the
17107algorithm for 1987 and later. Here is a listing of the default
17108daylight savings hook:
17109
17110@smallexample
17111(defun math-std-daylight-savings (date dt zone bump)
17112 (cond ((< (nth 1 dt) 4) 0)
17113 ((= (nth 1 dt) 4)
17114 (let ((sunday (math-prev-weekday-in-month date dt 7 0)))
17115 (cond ((< (nth 2 dt) sunday) 0)
17116 ((= (nth 2 dt) sunday)
17117 (if (>= (nth 3 dt) (+ 3 bump)) -1 0))
17118 (t -1))))
17119 ((< (nth 1 dt) 10) -1)
17120 ((= (nth 1 dt) 10)
17121 (let ((sunday (math-prev-weekday-in-month date dt 31 0)))
17122 (cond ((< (nth 2 dt) sunday) -1)
17123 ((= (nth 2 dt) sunday)
17124 (if (>= (nth 3 dt) (+ 2 bump)) 0 -1))
17125 (t 0))))
17126 (t 0))
17127)
17128@end smallexample
17129
17130@noindent
17131The @code{bump} parameter is equal to zero when Calc is converting
17132from a date form in a generalized time zone into a GMT date value.
17133It is @i{-1} when Calc is converting in the other direction. The
17134adjustments shown above ensure that the conversion behaves correctly
17135and reasonably around the 2 a.m.@: transition in each direction.
17136
17137There is a ``missing'' hour between 2 a.m.@: and 3 a.m.@: at the
17138beginning of daylight savings time; converting a date/time form that
17139falls in this hour results in a time value for the following hour,
17140from 3 a.m.@: to 4 a.m. At the end of daylight savings time, the
17141hour from 1 a.m.@: to 2 a.m.@: repeats itself; converting a date/time
17142form that falls in in this hour results in a time value for the first
17143manifestion of that time (@emph{not} the one that occurs one hour later).
17144
17145If @code{math-daylight-savings-hook} is @code{nil}, then the
17146daylight savings adjustment is always taken to be zero.
17147
17148In algebraic formulas, @samp{tzone(@var{zone}, @var{date})}
17149computes the time zone adjustment for a given zone name at a
17150given date. The @var{date} is ignored unless @var{zone} is a
17151generalized time zone. If @var{date} is a date form, the
17152daylight savings computation is applied to it as it appears.
17153If @var{date} is a numeric date value, it is adjusted for the
17154daylight-savings version of @var{zone} before being given to
17155the daylight savings hook. This odd-sounding rule ensures
17156that the daylight-savings computation is always done in
17157local time, not in the GMT time that a numeric @var{date}
17158is typically represented in.
17159
17160@c @starindex
17161@tindex dsadj
17162The @samp{dsadj(@var{date}, @var{zone})} function computes the
17163daylight savings adjustment that is appropriate for @var{date} in
17164time zone @var{zone}. If @var{zone} is explicitly in or not in
17165daylight savings time (e.g., @code{PDT} or @code{PST}) the
17166@var{date} is ignored. If @var{zone} is a generalized time zone,
17167the algorithms described above are used. If @var{zone} is omitted,
17168the computation is done for the current time zone.
17169
17170@xref{Reporting Bugs}, for the address of Calc's author, if you
17171should wish to contribute your improved versions of
17172@code{math-tzone-names} and @code{math-daylight-savings-hook}
17173to the Calc distribution.
17174
17175@node Financial Functions, Binary Functions, Date Arithmetic, Arithmetic
17176@section Financial Functions
17177
17178@noindent
17179Calc's financial or business functions use the @kbd{b} prefix
17180key followed by a shifted letter. (The @kbd{b} prefix followed by
17181a lower-case letter is used for operations on binary numbers.)
17182
17183Note that the rate and the number of intervals given to these
17184functions must be on the same time scale, e.g., both months or
17185both years. Mixing an annual interest rate with a time expressed
17186in months will give you very wrong answers!
17187
17188It is wise to compute these functions to a higher precision than
17189you really need, just to make sure your answer is correct to the
17190last penny; also, you may wish to check the definitions at the end
17191of this section to make sure the functions have the meaning you expect.
17192
17193@menu
17194* Percentages::
17195* Future Value::
17196* Present Value::
17197* Related Financial Functions::
17198* Depreciation Functions::
17199* Definitions of Financial Functions::
17200@end menu
17201
17202@node Percentages, Future Value, Financial Functions, Financial Functions
17203@subsection Percentages
17204
17205@kindex M-%
17206@pindex calc-percent
17207@tindex %
17208@tindex percent
17209The @kbd{M-%} (@code{calc-percent}) command takes a percentage value,
17210say 5.4, and converts it to an equivalent actual number. For example,
17211@kbd{5.4 M-%} enters 0.054 on the stack. (That's the @key{META} or
17212@key{ESC} key combined with @kbd{%}.)
17213
17214Actually, @kbd{M-%} creates a formula of the form @samp{5.4%}.
17215You can enter @samp{5.4%} yourself during algebraic entry. The
17216@samp{%} operator simply means, ``the preceding value divided by
17217100.'' The @samp{%} operator has very high precedence, so that
17218@samp{1+8%} is interpreted as @samp{1+(8%)}, not as @samp{(1+8)%}.
17219(The @samp{%} operator is just a postfix notation for the
17220@code{percent} function, just like @samp{20!} is the notation for
17221@samp{fact(20)}, or twenty-factorial.)
17222
17223The formula @samp{5.4%} would normally evaluate immediately to
172240.054, but the @kbd{M-%} command suppresses evaluation as it puts
17225the formula onto the stack. However, the next Calc command that
17226uses the formula @samp{5.4%} will evaluate it as its first step.
17227The net effect is that you get to look at @samp{5.4%} on the stack,
17228but Calc commands see it as @samp{0.054}, which is what they expect.
17229
17230In particular, @samp{5.4%} and @samp{0.054} are suitable values
17231for the @var{rate} arguments of the various financial functions,
17232but the number @samp{5.4} is probably @emph{not} suitable---it
17233represents a rate of 540 percent!
17234
17235The key sequence @kbd{M-% *} effectively means ``percent-of.''
17236For example, @kbd{68 RET 25 M-% *} computes 17, which is 25% of
1723768 (and also 68% of 25, which comes out to the same thing).
17238
17239@kindex c %
17240@pindex calc-convert-percent
17241The @kbd{c %} (@code{calc-convert-percent}) command converts the
17242value on the top of the stack from numeric to percentage form.
17243For example, if 0.08 is on the stack, @kbd{c %} converts it to
17244@samp{8%}. The quantity is the same, it's just represented
17245differently. (Contrast this with @kbd{M-%}, which would convert
17246this number to @samp{0.08%}.) The @kbd{=} key is a convenient way
17247to convert a formula like @samp{8%} back to numeric form, 0.08.
17248
17249To compute what percentage one quantity is of another quantity,
17250use @kbd{/ c %}. For example, @w{@kbd{17 RET 68 / c %}} displays
17251@samp{25%}.
17252
17253@kindex b %
17254@pindex calc-percent-change
17255@tindex relch
17256The @kbd{b %} (@code{calc-percent-change}) [@code{relch}] command
17257calculates the percentage change from one number to another.
17258For example, @kbd{40 RET 50 b %} produces the answer @samp{25%},
17259since 50 is 25% larger than 40. A negative result represents a
17260decrease: @kbd{50 RET 40 b %} produces @samp{-20%}, since 40 is
1726120% smaller than 50. (The answers are different in magnitude
17262because, in the first case, we're increasing by 25% of 40, but
17263in the second case, we're decreasing by 20% of 50.) The effect
17264of @kbd{40 RET 50 b %} is to compute @cite{(50-40)/40}, converting
17265the answer to percentage form as if by @kbd{c %}.
17266
17267@node Future Value, Present Value, Percentages, Financial Functions
17268@subsection Future Value
17269
17270@noindent
17271@kindex b F
17272@pindex calc-fin-fv
17273@tindex fv
17274The @kbd{b F} (@code{calc-fin-fv}) [@code{fv}] command computes
17275the future value of an investment. It takes three arguments
17276from the stack: @samp{fv(@var{rate}, @var{n}, @var{payment})}.
17277If you give payments of @var{payment} every year for @var{n}
17278years, and the money you have paid earns interest at @var{rate} per
17279year, then this function tells you what your investment would be
17280worth at the end of the period. (The actual interval doesn't
17281have to be years, as long as @var{n} and @var{rate} are expressed
17282in terms of the same intervals.) This function assumes payments
17283occur at the @emph{end} of each interval.
17284
17285@kindex I b F
17286@tindex fvb
17287The @kbd{I b F} [@code{fvb}] command does the same computation,
17288but assuming your payments are at the beginning of each interval.
17289Suppose you plan to deposit $1000 per year in a savings account
17290earning 5.4% interest, starting right now. How much will be
17291in the account after five years? @code{fvb(5.4%, 5, 1000) = 5870.73}.
17292Thus you will have earned $870 worth of interest over the years.
17293Using the stack, this calculation would have been
17294@kbd{5.4 M-% 5 RET 1000 I b F}. Note that the rate is expressed
17295as a number between 0 and 1, @emph{not} as a percentage.
17296
17297@kindex H b F
17298@tindex fvl
17299The @kbd{H b F} [@code{fvl}] command computes the future value
17300of an initial lump sum investment. Suppose you could deposit
17301those five thousand dollars in the bank right now; how much would
17302they be worth in five years? @code{fvl(5.4%, 5, 5000) = 6503.89}.
17303
17304The algebraic functions @code{fv} and @code{fvb} accept an optional
17305fourth argument, which is used as an initial lump sum in the sense
17306of @code{fvl}. In other words, @code{fv(@var{rate}, @var{n},
17307@var{payment}, @var{initial}) = fv(@var{rate}, @var{n}, @var{payment})
17308+ fvl(@var{rate}, @var{n}, @var{initial})}.@refill
17309
17310To illustrate the relationships between these functions, we could
17311do the @code{fvb} calculation ``by hand'' using @code{fvl}. The
17312final balance will be the sum of the contributions of our five
17313deposits at various times. The first deposit earns interest for
17314five years: @code{fvl(5.4%, 5, 1000) = 1300.78}. The second
17315deposit only earns interest for four years: @code{fvl(5.4%, 4, 1000) =
173161234.13}. And so on down to the last deposit, which earns one
17317year's interest: @code{fvl(5.4%, 1, 1000) = 1054.00}. The sum of
17318these five values is, sure enough, $5870.73, just as was computed
17319by @code{fvb} directly.
17320
17321What does @code{fv(5.4%, 5, 1000) = 5569.96} mean? The payments
17322are now at the ends of the periods. The end of one year is the same
17323as the beginning of the next, so what this really means is that we've
17324lost the payment at year zero (which contributed $1300.78), but we're
17325now counting the payment at year five (which, since it didn't have
17326a chance to earn interest, counts as $1000). Indeed, @cite{5569.96 =
173275870.73 - 1300.78 + 1000} (give or take a bit of roundoff error).
17328
17329@node Present Value, Related Financial Functions, Future Value, Financial Functions
17330@subsection Present Value
17331
17332@noindent
17333@kindex b P
17334@pindex calc-fin-pv
17335@tindex pv
17336The @kbd{b P} (@code{calc-fin-pv}) [@code{pv}] command computes
17337the present value of an investment. Like @code{fv}, it takes
17338three arguments: @code{pv(@var{rate}, @var{n}, @var{payment})}.
17339It computes the present value of a series of regular payments.
17340Suppose you have the chance to make an investment that will
17341pay $2000 per year over the next four years; as you receive
17342these payments you can put them in the bank at 9% interest.
17343You want to know whether it is better to make the investment, or
17344to keep the money in the bank where it earns 9% interest right
17345from the start. The calculation @code{pv(9%, 4, 2000)} gives the
17346result 6479.44. If your initial investment must be less than this,
17347say, $6000, then the investment is worthwhile. But if you had to
17348put up $7000, then it would be better just to leave it in the bank.
17349
17350Here is the interpretation of the result of @code{pv}: You are
17351trying to compare the return from the investment you are
17352considering, which is @code{fv(9%, 4, 2000) = 9146.26}, with
17353the return from leaving the money in the bank, which is
17354@code{fvl(9%, 4, @var{x})} where @var{x} is the amount of money
17355you would have to put up in advance. The @code{pv} function
17356finds the break-even point, @cite{x = 6479.44}, at which
17357@code{fvl(9%, 4, 6479.44)} is also equal to 9146.26. This is
17358the largest amount you should be willing to invest.
17359
17360@kindex I b P
17361@tindex pvb
17362The @kbd{I b P} [@code{pvb}] command solves the same problem,
17363but with payments occurring at the beginning of each interval.
17364It has the same relationship to @code{fvb} as @code{pv} has
17365to @code{fv}. For example @code{pvb(9%, 4, 2000) = 7062.59},
17366a larger number than @code{pv} produced because we get to start
17367earning interest on the return from our investment sooner.
17368
17369@kindex H b P
17370@tindex pvl
17371The @kbd{H b P} [@code{pvl}] command computes the present value of
17372an investment that will pay off in one lump sum at the end of the
17373period. For example, if we get our $8000 all at the end of the
17374four years, @code{pvl(9%, 4, 8000) = 5667.40}. This is much
17375less than @code{pv} reported, because we don't earn any interest
17376on the return from this investment. Note that @code{pvl} and
17377@code{fvl} are simple inverses: @code{fvl(9%, 4, 5667.40) = 8000}.
17378
17379You can give an optional fourth lump-sum argument to @code{pv}
17380and @code{pvb}; this is handled in exactly the same way as the
17381fourth argument for @code{fv} and @code{fvb}.
17382
17383@kindex b N
17384@pindex calc-fin-npv
17385@tindex npv
17386The @kbd{b N} (@code{calc-fin-npv}) [@code{npv}] command computes
17387the net present value of a series of irregular investments.
17388The first argument is the interest rate. The second argument is
17389a vector which represents the expected return from the investment
17390at the end of each interval. For example, if the rate represents
17391a yearly interest rate, then the vector elements are the return
17392from the first year, second year, and so on.
17393
17394Thus, @code{npv(9%, [2000,2000,2000,2000]) = pv(9%, 4, 2000) = 6479.44}.
17395Obviously this function is more interesting when the payments are
17396not all the same!
17397
17398The @code{npv} function can actually have two or more arguments.
17399Multiple arguments are interpreted in the same way as for the
17400vector statistical functions like @code{vsum}.
17401@xref{Single-Variable Statistics}. Basically, if there are several
17402payment arguments, each either a vector or a plain number, all these
17403values are collected left-to-right into the complete list of payments.
17404A numeric prefix argument on the @kbd{b N} command says how many
17405payment values or vectors to take from the stack.@refill
17406
17407@kindex I b N
17408@tindex npvb
17409The @kbd{I b N} [@code{npvb}] command computes the net present
17410value where payments occur at the beginning of each interval
17411rather than at the end.
17412
17413@node Related Financial Functions, Depreciation Functions, Present Value, Financial Functions
17414@subsection Related Financial Functions
17415
17416@noindent
17417The functions in this section are basically inverses of the
17418present value functions with respect to the various arguments.
17419
17420@kindex b M
17421@pindex calc-fin-pmt
17422@tindex pmt
17423The @kbd{b M} (@code{calc-fin-pmt}) [@code{pmt}] command computes
17424the amount of periodic payment necessary to amortize a loan.
17425Thus @code{pmt(@var{rate}, @var{n}, @var{amount})} equals the
17426value of @var{payment} such that @code{pv(@var{rate}, @var{n},
17427@var{payment}) = @var{amount}}.@refill
17428
17429@kindex I b M
17430@tindex pmtb
17431The @kbd{I b M} [@code{pmtb}] command does the same computation
17432but using @code{pvb} instead of @code{pv}. Like @code{pv} and
17433@code{pvb}, these functions can also take a fourth argument which
17434represents an initial lump-sum investment.
17435
17436@kindex H b M
17437The @kbd{H b M} key just invokes the @code{fvl} function, which is
17438the inverse of @code{pvl}. There is no explicit @code{pmtl} function.
17439
17440@kindex b #
17441@pindex calc-fin-nper
17442@tindex nper
17443The @kbd{b #} (@code{calc-fin-nper}) [@code{nper}] command computes
17444the number of regular payments necessary to amortize a loan.
17445Thus @code{nper(@var{rate}, @var{payment}, @var{amount})} equals
17446the value of @var{n} such that @code{pv(@var{rate}, @var{n},
17447@var{payment}) = @var{amount}}. If @var{payment} is too small
17448ever to amortize a loan for @var{amount} at interest rate @var{rate},
17449the @code{nper} function is left in symbolic form.@refill
17450
17451@kindex I b #
17452@tindex nperb
17453The @kbd{I b #} [@code{nperb}] command does the same computation
17454but using @code{pvb} instead of @code{pv}. You can give a fourth
17455lump-sum argument to these functions, but the computation will be
17456rather slow in the four-argument case.@refill
17457
17458@kindex H b #
17459@tindex nperl
17460The @kbd{H b #} [@code{nperl}] command does the same computation
17461using @code{pvl}. By exchanging @var{payment} and @var{amount} you
17462can also get the solution for @code{fvl}. For example,
17463@code{nperl(8%, 2000, 1000) = 9.006}, so if you place $1000 in a
17464bank account earning 8%, it will take nine years to grow to $2000.@refill
17465
17466@kindex b T
17467@pindex calc-fin-rate
17468@tindex rate
17469The @kbd{b T} (@code{calc-fin-rate}) [@code{rate}] command computes
17470the rate of return on an investment. This is also an inverse of @code{pv}:
17471@code{rate(@var{n}, @var{payment}, @var{amount})} computes the value of
17472@var{rate} such that @code{pv(@var{rate}, @var{n}, @var{payment}) =
17473@var{amount}}. The result is expressed as a formula like @samp{6.3%}.@refill
17474
17475@kindex I b T
17476@kindex H b T
17477@tindex rateb
17478@tindex ratel
17479The @kbd{I b T} [@code{rateb}] and @kbd{H b T} [@code{ratel}]
17480commands solve the analogous equations with @code{pvb} or @code{pvl}
17481in place of @code{pv}. Also, @code{rate} and @code{rateb} can
17482accept an optional fourth argument just like @code{pv} and @code{pvb}.
17483To redo the above example from a different perspective,
17484@code{ratel(9, 2000, 1000) = 8.00597%}, which says you will need an
17485interest rate of 8% in order to double your account in nine years.@refill
17486
17487@kindex b I
17488@pindex calc-fin-irr
17489@tindex irr
17490The @kbd{b I} (@code{calc-fin-irr}) [@code{irr}] command is the
17491analogous function to @code{rate} but for net present value.
17492Its argument is a vector of payments. Thus @code{irr(@var{payments})}
17493computes the @var{rate} such that @code{npv(@var{rate}, @var{payments}) = 0};
17494this rate is known as the @dfn{internal rate of return}.
17495
17496@kindex I b I
17497@tindex irrb
17498The @kbd{I b I} [@code{irrb}] command computes the internal rate of
17499return assuming payments occur at the beginning of each period.
17500
17501@node Depreciation Functions, Definitions of Financial Functions, Related Financial Functions, Financial Functions
17502@subsection Depreciation Functions
17503
17504@noindent
17505The functions in this section calculate @dfn{depreciation}, which is
17506the amount of value that a possession loses over time. These functions
17507are characterized by three parameters: @var{cost}, the original cost
17508of the asset; @var{salvage}, the value the asset will have at the end
17509of its expected ``useful life''; and @var{life}, the number of years
17510(or other periods) of the expected useful life.
17511
17512There are several methods for calculating depreciation that differ in
17513the way they spread the depreciation over the lifetime of the asset.
17514
17515@kindex b S
17516@pindex calc-fin-sln
17517@tindex sln
17518The @kbd{b S} (@code{calc-fin-sln}) [@code{sln}] command computes the
17519``straight-line'' depreciation. In this method, the asset depreciates
17520by the same amount every year (or period). For example,
17521@samp{sln(12000, 2000, 5)} returns 2000. The asset costs $12000
17522initially and will be worth $2000 after five years; it loses $2000
17523per year.
17524
17525@kindex b Y
17526@pindex calc-fin-syd
17527@tindex syd
17528The @kbd{b Y} (@code{calc-fin-syd}) [@code{syd}] command computes the
17529accelerated ``sum-of-years'-digits'' depreciation. Here the depreciation
17530is higher during the early years of the asset's life. Since the
17531depreciation is different each year, @kbd{b Y} takes a fourth @var{period}
17532parameter which specifies which year is requested, from 1 to @var{life}.
17533If @var{period} is outside this range, the @code{syd} function will
17534return zero.
17535
17536@kindex b D
17537@pindex calc-fin-ddb
17538@tindex ddb
17539The @kbd{b D} (@code{calc-fin-ddb}) [@code{ddb}] command computes an
17540accelerated depreciation using the double-declining balance method.
17541It also takes a fourth @var{period} parameter.
17542
17543For symmetry, the @code{sln} function will accept a @var{period}
17544parameter as well, although it will ignore its value except that the
17545return value will as usual be zero if @var{period} is out of range.
17546
17547For example, pushing the vector @cite{[1,2,3,4,5]} (perhaps with @kbd{v x 5})
17548and then mapping @kbd{V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
17549ddb(12000,2000,5,$)] RET} produces a matrix that allows us to compare
17550the three depreciation methods:
17551
17552@group
17553@example
17554[ [ 2000, 3333, 4800 ]
17555 [ 2000, 2667, 2880 ]
17556 [ 2000, 2000, 1728 ]
17557 [ 2000, 1333, 592 ]
17558 [ 2000, 667, 0 ] ]
17559@end example
17560@end group
17561
17562@noindent
17563(Values have been rounded to nearest integers in this figure.)
17564We see that @code{sln} depreciates by the same amount each year,
17565@kbd{syd} depreciates more at the beginning and less at the end,
17566and @kbd{ddb} weights the depreciation even more toward the beginning.
17567
17568Summing columns with @kbd{V R : +} yields @cite{[10000, 10000, 10000]};
17569the total depreciation in any method is (by definition) the
17570difference between the cost and the salvage value.
17571
17572@node Definitions of Financial Functions, , Depreciation Functions, Financial Functions
17573@subsection Definitions
17574
17575@noindent
17576For your reference, here are the actual formulas used to compute
17577Calc's financial functions.
17578
17579Calc will not evaluate a financial function unless the @var{rate} or
17580@var{n} argument is known. However, @var{payment} or @var{amount} can
17581be a variable. Calc expands these functions according to the
17582formulas below for symbolic arguments only when you use the @kbd{a "}
17583(@code{calc-expand-formula}) command, or when taking derivatives or
17584integrals or solving equations involving the functions.
17585
17586@ifinfo
17587These formulas are shown using the conventions of ``Big'' display
17588mode (@kbd{d B}); for example, the formula for @code{fv} written
17589linearly is @samp{pmt * ((1 + rate)^n) - 1) / rate}.
17590
17591@example
17592 n
17593 (1 + rate) - 1
17594fv(rate, n, pmt) = pmt * ---------------
17595 rate
17596
17597 n
17598 ((1 + rate) - 1) (1 + rate)
17599fvb(rate, n, pmt) = pmt * ----------------------------
17600 rate
17601
17602 n
17603fvl(rate, n, pmt) = pmt * (1 + rate)
17604
17605 -n
17606 1 - (1 + rate)
17607pv(rate, n, pmt) = pmt * ----------------
17608 rate
17609
17610 -n
17611 (1 - (1 + rate) ) (1 + rate)
17612pvb(rate, n, pmt) = pmt * -----------------------------
17613 rate
17614
17615 -n
17616pvl(rate, n, pmt) = pmt * (1 + rate)
17617
17618 -1 -2 -3
17619npv(rate, [a, b, c]) = a*(1 + rate) + b*(1 + rate) + c*(1 + rate)
17620
17621 -1 -2
17622npvb(rate, [a, b, c]) = a + b*(1 + rate) + c*(1 + rate)
17623
17624 -n
17625 (amt - x * (1 + rate) ) * rate
17626pmt(rate, n, amt, x) = -------------------------------
17627 -n
17628 1 - (1 + rate)
17629
17630 -n
17631 (amt - x * (1 + rate) ) * rate
17632pmtb(rate, n, amt, x) = -------------------------------
17633 -n
17634 (1 - (1 + rate) ) (1 + rate)
17635
17636 amt * rate
17637nper(rate, pmt, amt) = - log(1 - ------------, 1 + rate)
17638 pmt
17639
17640 amt * rate
17641nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
17642 pmt * (1 + rate)
17643
17644 amt
17645nperl(rate, pmt, amt) = - log(---, 1 + rate)
17646 pmt
17647
17648 1/n
17649 pmt
17650ratel(n, pmt, amt) = ------ - 1
17651 1/n
17652 amt
17653
17654 cost - salv
17655sln(cost, salv, life) = -----------
17656 life
17657
17658 (cost - salv) * (life - per + 1)
17659syd(cost, salv, life, per) = --------------------------------
17660 life * (life + 1) / 2
17661
17662 book * 2
17663ddb(cost, salv, life, per) = --------, book = cost - depreciation so far
17664 life
17665@end example
17666@end ifinfo
17667@tex
17668\turnoffactive
17669$$ \code{fv}(r, n, p) = p { (1 + r)^n - 1 \over r } $$
17670$$ \code{fvb}(r, n, p) = p { ((1 + r)^n - 1) (1 + r) \over r } $$
17671$$ \code{fvl}(r, n, p) = p (1 + r)^n $$
17672$$ \code{pv}(r, n, p) = p { 1 - (1 + r)^{-n} \over r } $$
17673$$ \code{pvb}(r, n, p) = p { (1 - (1 + r)^{-n}) (1 + r) \over r } $$
17674$$ \code{pvl}(r, n, p) = p (1 + r)^{-n} $$
17675$$ \code{npv}(r, [a,b,c]) = a (1 + r)^{-1} + b (1 + r)^{-2} + c (1 + r)^{-3} $$
17676$$ \code{npvb}(r, [a,b,c]) = a + b (1 + r)^{-1} + c (1 + r)^{-2} $$
17677$$ \code{pmt}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over 1 - (1 + r)^{-n} }$$
17678$$ \code{pmtb}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over
17679 (1 - (1 + r)^{-n}) (1 + r) } $$
17680$$ \code{nper}(r, p, a) = -\code{log}(1 - { a r \over p }, 1 + r) $$
17681$$ \code{nperb}(r, p, a) = -\code{log}(1 - { a r \over p (1 + r) }, 1 + r) $$
17682$$ \code{nperl}(r, p, a) = -\code{log}({a \over p}, 1 + r) $$
17683$$ \code{ratel}(n, p, a) = { p^{1/n} \over a^{1/n} } - 1 $$
17684$$ \code{sln}(c, s, l) = { c - s \over l } $$
17685$$ \code{syd}(c, s, l, p) = { (c - s) (l - p + 1) \over l (l+1) / 2 } $$
17686$$ \code{ddb}(c, s, l, p) = { 2 (c - \hbox{depreciation so far}) \over l } $$
17687@end tex
17688
17689@noindent
17690In @code{pmt} and @code{pmtb}, @cite{x=0} if omitted.
17691
17692These functions accept any numeric objects, including error forms,
17693intervals, and even (though not very usefully) complex numbers. The
17694above formulas specify exactly the behavior of these functions with
17695all sorts of inputs.
17696
17697Note that if the first argument to the @code{log} in @code{nper} is
17698negative, @code{nper} leaves itself in symbolic form rather than
17699returning a (financially meaningless) complex number.
17700
17701@samp{rate(num, pmt, amt)} solves the equation
17702@samp{pv(rate, num, pmt) = amt} for @samp{rate} using @kbd{H a R}
17703(@code{calc-find-root}), with the interval @samp{[.01% .. 100%]}
17704for an initial guess. The @code{rateb} function is the same except
17705that it uses @code{pvb}. Note that @code{ratel} can be solved
17706directly; its formula is shown in the above list.
17707
17708Similarly, @samp{irr(pmts)} solves the equation @samp{npv(rate, pmts) = 0}
17709for @samp{rate}.
17710
17711If you give a fourth argument to @code{nper} or @code{nperb}, Calc
17712will also use @kbd{H a R} to solve the equation using an initial
17713guess interval of @samp{[0 .. 100]}.
17714
17715A fourth argument to @code{fv} simply sums the two components
17716calculated from the above formulas for @code{fv} and @code{fvl}.
17717The same is true of @code{fvb}, @code{pv}, and @code{pvb}.
17718
17719The @kbd{ddb} function is computed iteratively; the ``book'' value
17720starts out equal to @var{cost}, and decreases according to the above
17721formula for the specified number of periods. If the book value
17722would decrease below @var{salvage}, it only decreases to @var{salvage}
17723and the depreciation is zero for all subsequent periods. The @code{ddb}
17724function returns the amount the book value decreased in the specified
17725period.
17726
17727The Calc financial function names were borrowed mostly from Microsoft
17728Excel and Borland's Quattro. The @code{ratel} function corresponds to
17729@samp{@@CGR} in Borland's Reflex. The @code{nper} and @code{nperl}
17730functions correspond to @samp{@@TERM} and @samp{@@CTERM} in Quattro,
17731respectively. Beware that the Calc functions may take their arguments
17732in a different order than the corresponding functions in your favorite
17733spreadsheet.
17734
17735@node Binary Functions, , Financial Functions, Arithmetic
17736@section Binary Number Functions
17737
17738@noindent
17739The commands in this chapter all use two-letter sequences beginning with
17740the @kbd{b} prefix.
17741
17742@cindex Binary numbers
17743The ``binary'' operations actually work regardless of the currently
17744displayed radix, although their results make the most sense in a radix
17745like 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @w{@kbd{d 6}}
17746commands, respectively). You may also wish to enable display of leading
17747zeros with @kbd{d z}. @xref{Radix Modes}.
17748
17749@cindex Word size for binary operations
17750The Calculator maintains a current @dfn{word size} @cite{w}, an
17751arbitrary positive or negative integer. For a positive word size, all
17752of the binary operations described here operate modulo @cite{2^w}. In
17753particular, negative arguments are converted to positive integers modulo
17754@cite{2^w} by all binary functions.@refill
17755
17756If the word size is negative, binary operations produce 2's complement
17757integers from @c{$-2^{-w-1}$}
17758@cite{-(2^(-w-1))} to @c{$2^{-w-1}-1$}
17759@cite{2^(-w-1)-1} inclusive. Either
17760mode accepts inputs in any range; the sign of @cite{w} affects only
17761the results produced.
17762
17763@kindex b c
17764@pindex calc-clip
17765@tindex clip
17766The @kbd{b c} (@code{calc-clip})
17767[@code{clip}] command can be used to clip a number by reducing it modulo
17768@cite{2^w}. The commands described in this chapter automatically clip
17769their results to the current word size. Note that other operations like
17770addition do not use the current word size, since integer addition
17771generally is not ``binary.'' (However, @pxref{Simplification Modes},
17772@code{calc-bin-simplify-mode}.) For example, with a word size of 8
17773bits @kbd{b c} converts a number to the range 0 to 255; with a word
17774size of @i{-8} @kbd{b c} converts to the range @i{-128} to 127.@refill
17775
17776@kindex b w
17777@pindex calc-word-size
17778The default word size is 32 bits. All operations except the shifts and
17779rotates allow you to specify a different word size for that one
17780operation by giving a numeric prefix argument: @kbd{C-u 8 b c} clips the
17781top of stack to the range 0 to 255 regardless of the current word size.
17782To set the word size permanently, use @kbd{b w} (@code{calc-word-size}).
17783This command displays a prompt with the current word size; press @key{RET}
17784immediately to keep this word size, or type a new word size at the prompt.
17785
17786When the binary operations are written in symbolic form, they take an
17787optional second (or third) word-size parameter. When a formula like
17788@samp{and(a,b)} is finally evaluated, the word size current at that time
17789will be used, but when @samp{and(a,b,-8)} is evaluated, a word size of
17790@i{-8} will always be used. A symbolic binary function will be left
17791in symbolic form unless the all of its argument(s) are integers or
17792integer-valued floats.
17793
17794If either or both arguments are modulo forms for which @cite{M} is a
17795power of two, that power of two is taken as the word size unless a
17796numeric prefix argument overrides it. The current word size is never
17797consulted when modulo-power-of-two forms are involved.
17798
17799@kindex b a
17800@pindex calc-and
17801@tindex and
17802The @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise
17803AND of the two numbers on the top of the stack. In other words, for each
17804of the @cite{w} binary digits of the two numbers (pairwise), the corresponding
17805bit of the result is 1 if and only if both input bits are 1:
17806@samp{and(2#1100, 2#1010) = 2#1000}.
17807
17808@kindex b o
17809@pindex calc-or
17810@tindex or
17811The @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise
17812inclusive OR of two numbers. A bit is 1 if either of the input bits, or
17813both, are 1: @samp{or(2#1100, 2#1010) = 2#1110}.
17814
17815@kindex b x
17816@pindex calc-xor
17817@tindex xor
17818The @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise
17819exclusive OR of two numbers. A bit is 1 if exactly one of the input bits
17820is 1: @samp{xor(2#1100, 2#1010) = 2#0110}.
17821
17822@kindex b d
17823@pindex calc-diff
17824@tindex diff
17825The @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise
17826difference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))},
17827so that @samp{diff(2#1100, 2#1010) = 2#0100}.
17828
17829@kindex b n
17830@pindex calc-not
17831@tindex not
17832The @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise
17833NOT of a number. A bit is 1 if the input bit is 0 and vice-versa.
17834
17835@kindex b l
17836@pindex calc-lshift-binary
17837@tindex lsh
17838The @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a
17839number left by one bit, or by the number of bits specified in the numeric
17840prefix argument. A negative prefix argument performs a logical right shift,
17841in which zeros are shifted in on the left. In symbolic form, @samp{lsh(a)}
17842is short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}.
17843Bits shifted ``off the end,'' according to the current word size, are lost.
17844
17845@kindex H b l
17846@kindex H b r
17847@c @mindex @idots
17848@kindex H b L
17849@c @mindex @null
17850@kindex H b R
17851@c @mindex @null
17852@kindex H b t
17853The @kbd{H b l} command also does a left shift, but it takes two arguments
17854from the stack (the value to shift, and, at top-of-stack, the number of
17855bits to shift). This version interprets the prefix argument just like
17856the regular binary operations, i.e., as a word size. The Hyperbolic flag
17857has a similar effect on the rest of the binary shift and rotate commands.
17858
17859@kindex b r
17860@pindex calc-rshift-binary
17861@tindex rsh
17862The @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a
17863number right by one bit, or by the number of bits specified in the numeric
17864prefix argument: @samp{rsh(a,n) = lsh(a,-n)}.
17865
17866@kindex b L
17867@pindex calc-lshift-arith
17868@tindex ash
17869The @kbd{b L} (@code{calc-lshift-arith}) [@code{ash}] command shifts a
17870number left. It is analogous to @code{lsh}, except that if the shift
17871is rightward (the prefix argument is negative), an arithmetic shift
17872is performed as described below.
17873
17874@kindex b R
17875@pindex calc-rshift-arith
17876@tindex rash
17877The @kbd{b R} (@code{calc-rshift-arith}) [@code{rash}] command performs
17878an ``arithmetic'' shift to the right, in which the leftmost bit (according
17879to the current word size) is duplicated rather than shifting in zeros.
17880This corresponds to dividing by a power of two where the input is interpreted
17881as a signed, twos-complement number. (The distinction between the @samp{rsh}
17882and @samp{rash} operations is totally independent from whether the word
17883size is positive or negative.) With a negative prefix argument, this
17884performs a standard left shift.
17885
17886@kindex b t
17887@pindex calc-rotate-binary
17888@tindex rot
17889The @kbd{b t} (@code{calc-rotate-binary}) [@code{rot}] command rotates a
17890number one bit to the left. The leftmost bit (according to the current
17891word size) is dropped off the left and shifted in on the right. With a
17892numeric prefix argument, the number is rotated that many bits to the left
17893or right.
17894
17895@xref{Set Operations}, for the @kbd{b p} and @kbd{b u} commands that
17896pack and unpack binary integers into sets. (For example, @kbd{b u}
17897unpacks the number @samp{2#11001} to the set of bit-numbers
17898@samp{[0, 3, 4]}.) Type @kbd{b u V #} to count the number of ``1''
17899bits in a binary integer.
17900
17901Another interesting use of the set representation of binary integers
17902is to reverse the bits in, say, a 32-bit integer. Type @kbd{b u} to
17903unpack; type @kbd{31 TAB -} to replace each bit-number in the set
17904with 31 minus that bit-number; type @kbd{b p} to pack the set back
17905into a binary integer.
17906
17907@node Scientific Functions, Matrix Functions, Arithmetic, Top
17908@chapter Scientific Functions
17909
17910@noindent
17911The functions described here perform trigonometric and other transcendental
17912calculations. They generally produce floating-point answers correct to the
17913full current precision. The @kbd{H} (Hyperbolic) and @kbd{I} (Inverse)
17914flag keys must be used to get some of these functions from the keyboard.
17915
17916@kindex P
17917@pindex calc-pi
17918@cindex @code{pi} variable
17919@vindex pi
17920@kindex H P
17921@cindex @code{e} variable
17922@vindex e
17923@kindex I P
17924@cindex @code{gamma} variable
17925@vindex gamma
17926@cindex Gamma constant, Euler's
17927@cindex Euler's gamma constant
17928@kindex H I P
17929@cindex @code{phi} variable
17930@cindex Phi, golden ratio
17931@cindex Golden ratio
17932One miscellanous command is shift-@kbd{P} (@code{calc-pi}), which pushes
17933the value of @c{$\pi$}
17934@cite{pi} (at the current precision) onto the stack. With the
17935Hyperbolic flag, it pushes the value @cite{e}, the base of natural logarithms.
17936With the Inverse flag, it pushes Euler's constant @c{$\gamma$}
17937@cite{gamma} (about 0.5772). With both Inverse and Hyperbolic, it
17938pushes the ``golden ratio'' @c{$\phi$}
17939@cite{phi} (about 1.618). (At present, Euler's constant is not available
17940to unlimited precision; Calc knows only the first 100 digits.)
17941In Symbolic mode, these commands push the
17942actual variables @samp{pi}, @samp{e}, @samp{gamma}, and @samp{phi},
17943respectively, instead of their values; @pxref{Symbolic Mode}.@refill
17944
17945@c @mindex Q
17946@c @mindex I Q
17947@kindex I Q
17948@tindex sqr
17949The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] function is described elsewhere;
17950@pxref{Basic Arithmetic}. With the Inverse flag [@code{sqr}], this command
17951computes the square of the argument.
17952
17953@xref{Prefix Arguments}, for a discussion of the effect of numeric
17954prefix arguments on commands in this chapter which do not otherwise
17955interpret a prefix argument.
17956
17957@menu
17958* Logarithmic Functions::
17959* Trigonometric and Hyperbolic Functions::
17960* Advanced Math Functions::
17961* Branch Cuts::
17962* Random Numbers::
17963* Combinatorial Functions::
17964* Probability Distribution Functions::
17965@end menu
17966
17967@node Logarithmic Functions, Trigonometric and Hyperbolic Functions, Scientific Functions, Scientific Functions
17968@section Logarithmic Functions
17969
17970@noindent
17971@kindex L
17972@pindex calc-ln
17973@tindex ln
17974@c @mindex @null
17975@kindex I E
17976The shift-@kbd{L} (@code{calc-ln}) [@code{ln}] command computes the natural
17977logarithm of the real or complex number on the top of the stack. With
17978the Inverse flag it computes the exponential function instead, although
17979this is redundant with the @kbd{E} command.
17980
17981@kindex E
17982@pindex calc-exp
17983@tindex exp
17984@c @mindex @null
17985@kindex I L
17986The shift-@kbd{E} (@code{calc-exp}) [@code{exp}] command computes the
17987exponential, i.e., @cite{e} raised to the power of the number on the stack.
17988The meanings of the Inverse and Hyperbolic flags follow from those for
17989the @code{calc-ln} command.
17990
17991@kindex H L
17992@kindex H E
17993@pindex calc-log10
17994@tindex log10
17995@tindex exp10
17996@c @mindex @null
17997@kindex H I L
17998@c @mindex @null
17999@kindex H I E
18000The @kbd{H L} (@code{calc-log10}) [@code{log10}] command computes the common
18001(base-10) logarithm of a number. (With the Inverse flag [@code{exp10}],
18002it raises ten to a given power.) Note that the common logarithm of a
18003complex number is computed by taking the natural logarithm and dividing
18004by @c{$\ln10$}
18005@cite{ln(10)}.
18006
18007@kindex B
18008@kindex I B
18009@pindex calc-log
18010@tindex log
18011@tindex alog
18012The @kbd{B} (@code{calc-log}) [@code{log}] command computes a logarithm
18013to any base. For example, @kbd{1024 @key{RET} 2 B} produces 10, since
18014@c{$2^{10} = 1024$}
18015@cite{2^10 = 1024}. In certain cases like @samp{log(3,9)}, the result
18016will be either @cite{1:2} or @cite{0.5} depending on the current Fraction
18017Mode setting. With the Inverse flag [@code{alog}], this command is
18018similar to @kbd{^} except that the order of the arguments is reversed.
18019
18020@kindex f I
18021@pindex calc-ilog
18022@tindex ilog
18023The @kbd{f I} (@code{calc-ilog}) [@code{ilog}] command computes the
18024integer logarithm of a number to any base. The number and the base must
18025themselves be positive integers. This is the true logarithm, rounded
18026down to an integer. Thus @kbd{ilog(x,10)} is 3 for all @cite{x} in the
18027range from 1000 to 9999. If both arguments are positive integers, exact
18028integer arithmetic is used; otherwise, this is equivalent to
18029@samp{floor(log(x,b))}.
18030
18031@kindex f E
18032@pindex calc-expm1
18033@tindex expm1
18034The @kbd{f E} (@code{calc-expm1}) [@code{expm1}] command computes
18035@c{$e^x - 1$}
18036@cite{exp(x)-1}, but using an algorithm that produces a more accurate
18037answer when the result is close to zero, i.e., when @c{$e^x$}
18038@cite{exp(x)} is close
18039to one.
18040
18041@kindex f L
18042@pindex calc-lnp1
18043@tindex lnp1
18044The @kbd{f L} (@code{calc-lnp1}) [@code{lnp1}] command computes
18045@c{$\ln(x+1)$}
18046@cite{ln(x+1)}, producing a more accurate answer when @cite{x} is close
18047to zero.
18048
18049@node Trigonometric and Hyperbolic Functions, Advanced Math Functions, Logarithmic Functions, Scientific Functions
18050@section Trigonometric/Hyperbolic Functions
18051
18052@noindent
18053@kindex S
18054@pindex calc-sin
18055@tindex sin
18056The shift-@kbd{S} (@code{calc-sin}) [@code{sin}] command computes the sine
18057of an angle or complex number. If the input is an HMS form, it is interpreted
18058as degrees-minutes-seconds; otherwise, the input is interpreted according
18059to the current angular mode. It is best to use Radians mode when operating
18060on complex numbers.@refill
18061
18062Calc's ``units'' mechanism includes angular units like @code{deg},
18063@code{rad}, and @code{grad}. While @samp{sin(45 deg)} is not evaluated
18064all the time, the @kbd{u s} (@code{calc-simplify-units}) command will
18065simplify @samp{sin(45 deg)} by taking the sine of 45 degrees, regardless
18066of the current angular mode. @xref{Basic Operations on Units}.
18067
18068Also, the symbolic variable @code{pi} is not ordinarily recognized in
18069arguments to trigonometric functions, as in @samp{sin(3 pi / 4)}, but
18070the @kbd{a s} (@code{calc-simplify}) command recognizes many such
18071formulas when the current angular mode is radians @emph{and} symbolic
18072mode is enabled; this example would be replaced by @samp{sqrt(2) / 2}.
18073@xref{Symbolic Mode}. Beware, this simplification occurs even if you
18074have stored a different value in the variable @samp{pi}; this is one
18075reason why changing built-in variables is a bad idea. Arguments of
18076the form @cite{x} plus a multiple of @c{$\pi/2$}
18077@cite{pi/2} are also simplified.
18078Calc includes similar formulas for @code{cos} and @code{tan}.@refill
18079
18080The @kbd{a s} command knows all angles which are integer multiples of
18081@c{$\pi/12$}
18082@cite{pi/12}, @c{$\pi/10$}
18083@cite{pi/10}, or @c{$\pi/8$}
18084@cite{pi/8} radians. In degrees mode,
18085analogous simplifications occur for integer multiples of 15 or 18
18086degrees, and for arguments plus multiples of 90 degrees.
18087
18088@kindex I S
18089@pindex calc-arcsin
18090@tindex arcsin
18091With the Inverse flag, @code{calc-sin} computes an arcsine. This is also
18092available as the @code{calc-arcsin} command or @code{arcsin} algebraic
18093function. The returned argument is converted to degrees, radians, or HMS
18094notation depending on the current angular mode.
18095
18096@kindex H S
18097@pindex calc-sinh
18098@tindex sinh
18099@kindex H I S
18100@pindex calc-arcsinh
18101@tindex arcsinh
18102With the Hyperbolic flag, @code{calc-sin} computes the hyperbolic
18103sine, also available as @code{calc-sinh} [@code{sinh}]. With the
18104Hyperbolic and Inverse flags, it computes the hyperbolic arcsine
18105(@code{calc-arcsinh}) [@code{arcsinh}].
18106
18107@kindex C
18108@pindex calc-cos
18109@tindex cos
18110@c @mindex @idots
18111@kindex I C
18112@pindex calc-arccos
18113@c @mindex @null
18114@tindex arccos
18115@c @mindex @null
18116@kindex H C
18117@pindex calc-cosh
18118@c @mindex @null
18119@tindex cosh
18120@c @mindex @null
18121@kindex H I C
18122@pindex calc-arccosh
18123@c @mindex @null
18124@tindex arccosh
18125@c @mindex @null
18126@kindex T
18127@pindex calc-tan
18128@c @mindex @null
18129@tindex tan
18130@c @mindex @null
18131@kindex I T
18132@pindex calc-arctan
18133@c @mindex @null
18134@tindex arctan
18135@c @mindex @null
18136@kindex H T
18137@pindex calc-tanh
18138@c @mindex @null
18139@tindex tanh
18140@c @mindex @null
18141@kindex H I T
18142@pindex calc-arctanh
18143@c @mindex @null
18144@tindex arctanh
18145The shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine
18146of an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}]
18147computes the tangent, along with all the various inverse and hyperbolic
18148variants of these functions.
18149
18150@kindex f T
18151@pindex calc-arctan2
18152@tindex arctan2
18153The @kbd{f T} (@code{calc-arctan2}) [@code{arctan2}] command takes two
18154numbers from the stack and computes the arc tangent of their ratio. The
18155result is in the full range from @i{-180} (exclusive) to @i{+180}
18156(inclusive) degrees, or the analogous range in radians. A similar
18157result would be obtained with @kbd{/} followed by @kbd{I T}, but the
18158value would only be in the range from @i{-90} to @i{+90} degrees
18159since the division loses information about the signs of the two
18160components, and an error might result from an explicit division by zero
18161which @code{arctan2} would avoid. By (arbitrary) definition,
18162@samp{arctan2(0,0)=0}.
18163
18164@pindex calc-sincos
18165@c @starindex
18166@tindex sincos
18167@c @starindex
18168@c @mindex arc@idots
18169@tindex arcsincos
18170The @code{calc-sincos} [@code{sincos}] command computes the sine and
18171cosine of a number, returning them as a vector of the form
18172@samp{[@var{cos}, @var{sin}]}.
18173With the Inverse flag [@code{arcsincos}], this command takes a two-element
18174vector as an argument and computes @code{arctan2} of the elements.
18175(This command does not accept the Hyperbolic flag.)@refill
18176
18177@node Advanced Math Functions, Branch Cuts, Trigonometric and Hyperbolic Functions, Scientific Functions
18178@section Advanced Mathematical Functions
18179
18180@noindent
18181Calc can compute a variety of less common functions that arise in
18182various branches of mathematics. All of the functions described in
18183this section allow arbitrary complex arguments and, except as noted,
18184will work to arbitrarily large precisions. They can not at present
18185handle error forms or intervals as arguments.
18186
18187NOTE: These functions are still experimental. In particular, their
18188accuracy is not guaranteed in all domains. It is advisable to set the
18189current precision comfortably higher than you actually need when
18190using these functions. Also, these functions may be impractically
18191slow for some values of the arguments.
18192
18193@kindex f g
18194@pindex calc-gamma
18195@tindex gamma
18196The @kbd{f g} (@code{calc-gamma}) [@code{gamma}] command computes the Euler
18197gamma function. For positive integer arguments, this is related to the
18198factorial function: @samp{gamma(n+1) = fact(n)}. For general complex
18199arguments the gamma function can be defined by the following definite
18200integral: @c{$\Gamma(a) = \int_0^\infty t^{a-1} e^t dt$}
18201@cite{gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)}.
18202(The actual implementation uses far more efficient computational methods.)
18203
18204@kindex f G
18205@tindex gammaP
18206@c @mindex @idots
18207@kindex I f G
18208@c @mindex @null
18209@kindex H f G
18210@c @mindex @null
18211@kindex H I f G
18212@pindex calc-inc-gamma
18213@c @mindex @null
18214@tindex gammaQ
18215@c @mindex @null
18216@tindex gammag
18217@c @mindex @null
18218@tindex gammaG
18219The @kbd{f G} (@code{calc-inc-gamma}) [@code{gammaP}] command computes
18220the incomplete gamma function, denoted @samp{P(a,x)}. This is defined by
18221the integral, @c{$P(a,x) = \left( \int_0^x t^{a-1} e^t dt \right) / \Gamma(a)$}
18222@cite{gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)}.
18223This implies that @samp{gammaP(a,inf) = 1} for any @cite{a} (see the
18224definition of the normal gamma function).
18225
18226Several other varieties of incomplete gamma function are defined.
18227The complement of @cite{P(a,x)}, called @cite{Q(a,x) = 1-P(a,x)} by
18228some authors, is computed by the @kbd{I f G} [@code{gammaQ}] command.
18229You can think of this as taking the other half of the integral, from
18230@cite{x} to infinity.
18231
18232@ifinfo
18233The functions corresponding to the integrals that define @cite{P(a,x)}
18234and @cite{Q(a,x)} but without the normalizing @cite{1/gamma(a)}
18235factor are called @cite{g(a,x)} and @cite{G(a,x)}, respectively
18236(where @cite{g} and @cite{G} represent the lower- and upper-case Greek
18237letter gamma). You can obtain these using the @kbd{H f G} [@code{gammag}]
18238and @kbd{H I f G} [@code{gammaG}] commands.
18239@end ifinfo
18240@tex
18241\turnoffactive
18242The functions corresponding to the integrals that define $P(a,x)$
18243and $Q(a,x)$ but without the normalizing $1/\Gamma(a)$
18244factor are called $\gamma(a,x)$ and $\Gamma(a,x)$, respectively.
18245You can obtain these using the \kbd{H f G} [\code{gammag}] and
18246\kbd{I H f G} [\code{gammaG}] commands.
18247@end tex
18248
18249@kindex f b
18250@pindex calc-beta
18251@tindex beta
18252The @kbd{f b} (@code{calc-beta}) [@code{beta}] command computes the
18253Euler beta function, which is defined in terms of the gamma function as
18254@c{$B(a,b) = \Gamma(a) \Gamma(b) / \Gamma(a+b)$}
18255@cite{beta(a,b) = gamma(a) gamma(b) / gamma(a+b)}, or by
18256@c{$B(a,b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt$}
18257@cite{beta(a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, 1)}.
18258
18259@kindex f B
18260@kindex H f B
18261@pindex calc-inc-beta
18262@tindex betaI
18263@tindex betaB
18264The @kbd{f B} (@code{calc-inc-beta}) [@code{betaI}] command computes
18265the incomplete beta function @cite{I(x,a,b)}. It is defined by
18266@c{$I(x,a,b) = \left( \int_0^x t^{a-1} (1-t)^{b-1} dt \right) / B(a,b)$}
18267@cite{betaI(x,a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)}.
18268Once again, the @kbd{H} (hyperbolic) prefix gives the corresponding
18269un-normalized version [@code{betaB}].
18270
18271@kindex f e
18272@kindex I f e
18273@pindex calc-erf
18274@tindex erf
18275@tindex erfc
18276The @kbd{f e} (@code{calc-erf}) [@code{erf}] command computes the
18277error function @c{$\hbox{erf}(x) = {2 \over \sqrt{\pi}} \int_0^x e^{-t^2} dt$}
18278@cite{erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)}.
18279The complementary error function @kbd{I f e} (@code{calc-erfc}) [@code{erfc}]
18280is the corresponding integral from @samp{x} to infinity; the sum
18281@c{$\hbox{erf}(x) + \hbox{erfc}(x) = 1$}
18282@cite{erf(x) + erfc(x) = 1}.
18283
18284@kindex f j
18285@kindex f y
18286@pindex calc-bessel-J
18287@pindex calc-bessel-Y
18288@tindex besJ
18289@tindex besY
18290The @kbd{f j} (@code{calc-bessel-J}) [@code{besJ}] and @kbd{f y}
18291(@code{calc-bessel-Y}) [@code{besY}] commands compute the Bessel
18292functions of the first and second kinds, respectively.
18293In @samp{besJ(n,x)} and @samp{besY(n,x)} the ``order'' parameter
18294@cite{n} is often an integer, but is not required to be one.
18295Calc's implementation of the Bessel functions currently limits the
18296precision to 8 digits, and may not be exact even to that precision.
18297Use with care!@refill
18298
18299@node Branch Cuts, Random Numbers, Advanced Math Functions, Scientific Functions
18300@section Branch Cuts and Principal Values
18301
18302@noindent
18303@cindex Branch cuts
18304@cindex Principal values
18305All of the logarithmic, trigonometric, and other scientific functions are
18306defined for complex numbers as well as for reals.
18307This section describes the values
18308returned in cases where the general result is a family of possible values.
18309Calc follows section 12.5.3 of Steele's @dfn{Common Lisp, the Language},
18310second edition, in these matters. This section will describe each
18311function briefly; for a more detailed discussion (including some nifty
18312diagrams), consult Steele's book.
18313
18314Note that the branch cuts for @code{arctan} and @code{arctanh} were
18315changed between the first and second editions of Steele. Versions of
18316Calc starting with 2.00 follow the second edition.
18317
18318The new branch cuts exactly match those of the HP-28/48 calculators.
18319They also match those of Mathematica 1.2, except that Mathematica's
18320@code{arctan} cut is always in the right half of the complex plane,
18321and its @code{arctanh} cut is always in the top half of the plane.
18322Calc's cuts are continuous with quadrants I and III for @code{arctan},
18323or II and IV for @code{arctanh}.
18324
18325Note: The current implementations of these functions with complex arguments
18326are designed with proper behavior around the branch cuts in mind, @emph{not}
18327efficiency or accuracy. You may need to increase the floating precision
18328and wait a while to get suitable answers from them.
18329
18330For @samp{sqrt(a+bi)}: When @cite{a<0} and @cite{b} is small but positive
18331or zero, the result is close to the @cite{+i} axis. For @cite{b} small and
18332negative, the result is close to the @cite{-i} axis. The result always lies
18333in the right half of the complex plane.
18334
18335For @samp{ln(a+bi)}: The real part is defined as @samp{ln(abs(a+bi))}.
18336The imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}.
18337Thus the branch cuts for @code{sqrt} and @code{ln} both lie on the
18338negative real axis.
18339
18340The following table describes these branch cuts in another way.
18341If the real and imaginary parts of @cite{z} are as shown, then
18342the real and imaginary parts of @cite{f(z)} will be as shown.
18343Here @code{eps} stands for a small positive value; each
18344occurrence of @code{eps} may stand for a different small value.
18345
18346@smallexample
18347 z sqrt(z) ln(z)
18348----------------------------------------
18349 +, 0 +, 0 any, 0
18350 -, 0 0, + any, pi
18351 -, +eps +eps, + +eps, +
18352 -, -eps +eps, - +eps, -
18353@end smallexample
18354
18355For @samp{z1^z2}: This is defined by @samp{exp(ln(z1)*z2)}.
18356One interesting consequence of this is that @samp{(-8)^1:3} does
18357not evaluate to @i{-2} as you might expect, but to the complex
18358number @cite{(1., 1.732)}. Both of these are valid cube roots
18359of @i{-8} (as is @cite{(1., -1.732)}); Calc chooses a perhaps
18360less-obvious root for the sake of mathematical consistency.
18361
18362For @samp{arcsin(z)}: This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}.
18363The branch cuts are on the real axis, less than @i{-1} and greater than 1.
18364
18365For @samp{arccos(z)}: This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))},
18366or equivalently by @samp{pi/2 - arcsin(z)}. The branch cuts are on
18367the real axis, less than @i{-1} and greater than 1.
18368
18369For @samp{arctan(z)}: This is defined by
18370@samp{(ln(1+i*z) - ln(1-i*z)) / (2*i)}. The branch cuts are on the
18371imaginary axis, below @cite{-i} and above @cite{i}.
18372
18373For @samp{arcsinh(z)}: This is defined by @samp{ln(z + sqrt(1+z^2))}.
18374The branch cuts are on the imaginary axis, below @cite{-i} and
18375above @cite{i}.
18376
18377For @samp{arccosh(z)}: This is defined by
18378@samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}. The branch cut is on the
18379real axis less than 1.
18380
18381For @samp{arctanh(z)}: This is defined by @samp{(ln(1+z) - ln(1-z)) / 2}.
18382The branch cuts are on the real axis, less than @i{-1} and greater than 1.
18383
18384The following tables for @code{arcsin}, @code{arccos}, and
18385@code{arctan} assume the current angular mode is radians. The
18386hyperbolic functions operate independently of the angular mode.
18387
18388@smallexample
18389 z arcsin(z) arccos(z)
18390-------------------------------------------------------
18391 (-1..1), 0 (-pi/2..pi/2), 0 (0..pi), 0
18392 (-1..1), +eps (-pi/2..pi/2), +eps (0..pi), -eps
18393 (-1..1), -eps (-pi/2..pi/2), -eps (0..pi), +eps
18394 <-1, 0 -pi/2, + pi, -
18395 <-1, +eps -pi/2 + eps, + pi - eps, -
18396 <-1, -eps -pi/2 + eps, - pi - eps, +
18397 >1, 0 pi/2, - 0, +
18398 >1, +eps pi/2 - eps, + +eps, -
18399 >1, -eps pi/2 - eps, - +eps, +
18400@end smallexample
18401
18402@smallexample
18403 z arccosh(z) arctanh(z)
18404-----------------------------------------------------
18405 (-1..1), 0 0, (0..pi) any, 0
18406 (-1..1), +eps +eps, (0..pi) any, +eps
18407 (-1..1), -eps +eps, (-pi..0) any, -eps
18408 <-1, 0 +, pi -, pi/2
18409 <-1, +eps +, pi - eps -, pi/2 - eps
18410 <-1, -eps +, -pi + eps -, -pi/2 + eps
18411 >1, 0 +, 0 +, -pi/2
18412 >1, +eps +, +eps +, pi/2 - eps
18413 >1, -eps +, -eps +, -pi/2 + eps
18414@end smallexample
18415
18416@smallexample
18417 z arcsinh(z) arctan(z)
18418-----------------------------------------------------
18419 0, (-1..1) 0, (-pi/2..pi/2) 0, any
18420 0, <-1 -, -pi/2 -pi/2, -
18421 +eps, <-1 +, -pi/2 + eps pi/2 - eps, -
18422 -eps, <-1 -, -pi/2 + eps -pi/2 + eps, -
18423 0, >1 +, pi/2 pi/2, +
18424 +eps, >1 +, pi/2 - eps pi/2 - eps, +
18425 -eps, >1 -, pi/2 - eps -pi/2 + eps, +
18426@end smallexample
18427
18428Finally, the following identities help to illustrate the relationship
18429between the complex trigonometric and hyperbolic functions. They
18430are valid everywhere, including on the branch cuts.
18431
18432@smallexample
18433sin(i*z) = i*sinh(z) arcsin(i*z) = i*arcsinh(z)
18434cos(i*z) = cosh(z) arcsinh(i*z) = i*arcsin(z)
18435tan(i*z) = i*tanh(z) arctan(i*z) = i*arctanh(z)
18436sinh(i*z) = i*sin(z) cosh(i*z) = cos(z)
18437@end smallexample
18438
18439The ``advanced math'' functions (gamma, Bessel, etc.@:) are also defined
18440for general complex arguments, but their branch cuts and principal values
18441are not rigorously specified at present.
18442
18443@node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions
18444@section Random Numbers
18445
18446@noindent
18447@kindex k r
18448@pindex calc-random
18449@tindex random
18450The @kbd{k r} (@code{calc-random}) [@code{random}] command produces
18451random numbers of various sorts.
18452
18453Given a positive numeric prefix argument @cite{M}, it produces a random
18454integer @cite{N} in the range @c{$0 \le N < M$}
18455@cite{0 <= N < M}. Each of the @cite{M}
18456values appears with equal probability.@refill
18457
18458With no numeric prefix argument, the @kbd{k r} command takes its argument
18459from the stack instead. Once again, if this is a positive integer @cite{M}
18460the result is a random integer less than @cite{M}. However, note that
18461while numeric prefix arguments are limited to six digits or so, an @cite{M}
18462taken from the stack can be arbitrarily large. If @cite{M} is negative,
18463the result is a random integer in the range @c{$M < N \le 0$}
18464@cite{M < N <= 0}.
18465
18466If the value on the stack is a floating-point number @cite{M}, the result
18467is a random floating-point number @cite{N} in the range @c{$0 \le N < M$}
18468@cite{0 <= N < M}
18469or @c{$M < N \le 0$}
18470@cite{M < N <= 0}, according to the sign of @cite{M}.
18471
18472If @cite{M} is zero, the result is a Gaussian-distributed random real
18473number; the distribution has a mean of zero and a standard deviation
18474of one. The algorithm used generates random numbers in pairs; thus,
18475every other call to this function will be especially fast.
18476
18477If @cite{M} is an error form @c{$m$ @code{+/-} $\sigma$}
18478@samp{m +/- s} where @i{m}
18479and @c{$\sigma$}
18480@i{s} are both real numbers, the result uses a Gaussian
18481distribution with mean @i{m} and standard deviation @c{$\sigma$}
18482@i{s}.
18483
18484If @cite{M} is an interval form, the lower and upper bounds specify the
18485acceptable limits of the random numbers. If both bounds are integers,
18486the result is a random integer in the specified range. If either bound
18487is floating-point, the result is a random real number in the specified
18488range. If the interval is open at either end, the result will be sure
18489not to equal that end value. (This makes a big difference for integer
18490intervals, but for floating-point intervals it's relatively minor:
18491with a precision of 6, @samp{random([1.0..2.0))} will return any of one
18492million numbers from 1.00000 to 1.99999; @samp{random([1.0..2.0])} may
18493additionally return 2.00000, but the probability of this happening is
18494extremely small.)
18495
18496If @cite{M} is a vector, the result is one element taken at random from
18497the vector. All elements of the vector are given equal probabilities.
18498
18499@vindex RandSeed
18500The sequence of numbers produced by @kbd{k r} is completely random by
18501default, i.e., the sequence is seeded each time you start Calc using
18502the current time and other information. You can get a reproducible
18503sequence by storing a particular ``seed value'' in the Calc variable
18504@code{RandSeed}. Any integer will do for a seed; integers of from 1
18505to 12 digits are good. If you later store a different integer into
18506@code{RandSeed}, Calc will switch to a different pseudo-random
18507sequence. If you ``unstore'' @code{RandSeed}, Calc will re-seed itself
18508from the current time. If you store the same integer that you used
18509before back into @code{RandSeed}, you will get the exact same sequence
18510of random numbers as before.
18511
18512@pindex calc-rrandom
18513The @code{calc-rrandom} command (not on any key) produces a random real
18514number between zero and one. It is equivalent to @samp{random(1.0)}.
18515
18516@kindex k a
18517@pindex calc-random-again
18518The @kbd{k a} (@code{calc-random-again}) command produces another random
18519number, re-using the most recent value of @cite{M}. With a numeric
18520prefix argument @var{n}, it produces @var{n} more random numbers using
18521that value of @cite{M}.
18522
18523@kindex k h
18524@pindex calc-shuffle
18525@tindex shuffle
18526The @kbd{k h} (@code{calc-shuffle}) command produces a vector of several
18527random values with no duplicates. The value on the top of the stack
18528specifies the set from which the random values are drawn, and may be any
18529of the @cite{M} formats described above. The numeric prefix argument
18530gives the length of the desired list. (If you do not provide a numeric
18531prefix argument, the length of the list is taken from the top of the
18532stack, and @cite{M} from second-to-top.)
18533
18534If @cite{M} is a floating-point number, zero, or an error form (so
18535that the random values are being drawn from the set of real numbers)
18536there is little practical difference between using @kbd{k h} and using
18537@kbd{k r} several times. But if the set of possible values consists
18538of just a few integers, or the elements of a vector, then there is
18539a very real chance that multiple @kbd{k r}'s will produce the same
18540number more than once. The @kbd{k h} command produces a vector whose
18541elements are always distinct. (Actually, there is a slight exception:
18542If @cite{M} is a vector, no given vector element will be drawn more
18543than once, but if several elements of @cite{M} are equal, they may
18544each make it into the result vector.)
18545
18546One use of @kbd{k h} is to rearrange a list at random. This happens
18547if the prefix argument is equal to the number of values in the list:
18548@kbd{[1, 1.5, 2, 2.5, 3] 5 k h} might produce the permuted list
18549@samp{[2.5, 1, 1.5, 3, 2]}. As a convenient feature, if the argument
18550@var{n} is negative it is replaced by the size of the set represented
18551by @cite{M}. Naturally, this is allowed only when @cite{M} specifies
18552a small discrete set of possibilities.
18553
18554To do the equivalent of @kbd{k h} but with duplications allowed,
18555given @cite{M} on the stack and with @var{n} just entered as a numeric
18556prefix, use @kbd{v b} to build a vector of copies of @cite{M}, then use
18557@kbd{V M k r} to ``map'' the normal @kbd{k r} function over the
18558elements of this vector. @xref{Matrix Functions}.
18559
18560@menu
18561* Random Number Generator:: (Complete description of Calc's algorithm)
18562@end menu
18563
18564@node Random Number Generator, , Random Numbers, Random Numbers
18565@subsection Random Number Generator
18566
18567Calc's random number generator uses several methods to ensure that
18568the numbers it produces are highly random. Knuth's @emph{Art of
18569Computer Programming}, Volume II, contains a thorough description
18570of the theory of random number generators and their measurement and
18571characterization.
18572
18573If @code{RandSeed} has no stored value, Calc calls Emacs' built-in
18574@code{random} function to get a stream of random numbers, which it
18575then treats in various ways to avoid problems inherent in the simple
18576random number generators that many systems use to implement @code{random}.
18577
18578When Calc's random number generator is first invoked, it ``seeds''
18579the low-level random sequence using the time of day, so that the
18580random number sequence will be different every time you use Calc.
18581
18582Since Emacs Lisp doesn't specify the range of values that will be
18583returned by its @code{random} function, Calc exercises the function
18584several times to estimate the range. When Calc subsequently uses
18585the @code{random} function, it takes only 10 bits of the result
18586near the most-significant end. (It avoids at least the bottom
18587four bits, preferably more, and also tries to avoid the top two
18588bits.) This strategy works well with the linear congruential
18589generators that are typically used to implement @code{random}.
18590
18591If @code{RandSeed} contains an integer, Calc uses this integer to
18592seed an ``additive congruential'' method (Knuth's algorithm 3.2.2A,
18593computing @c{$X_{n-55} - X_{n-24}$}
18594@cite{X_n-55 - X_n-24}). This method expands the seed
18595value into a large table which is maintained internally; the variable
18596@code{RandSeed} is changed from, e.g., 42 to the vector @cite{[42]}
18597to indicate that the seed has been absorbed into this table. When
18598@code{RandSeed} contains a vector, @kbd{k r} and related commands
18599continue to use the same internal table as last time. There is no
18600way to extract the complete state of the random number generator
18601so that you can restart it from any point; you can only restart it
18602from the same initial seed value. A simple way to restart from the
18603same seed is to type @kbd{s r RandSeed} to get the seed vector,
18604@kbd{v u} to unpack it back into a number, then @kbd{s t RandSeed}
18605to reseed the generator with that number.
18606
18607Calc uses a ``shuffling'' method as described in algorithm 3.2.2B
18608of Knuth. It fills a table with 13 random 10-bit numbers. Then,
18609to generate a new random number, it uses the previous number to
18610index into the table, picks the value it finds there as the new
18611random number, then replaces that table entry with a new value
18612obtained from a call to the base random number generator (either
18613the additive congruential generator or the @code{random} function
18614supplied by the system). If there are any flaws in the base
18615generator, shuffling will tend to even them out. But if the system
18616provides an excellent @code{random} function, shuffling will not
18617damage its randomness.
18618
18619To create a random integer of a certain number of digits, Calc
18620builds the integer three decimal digits at a time. For each group
18621of three digits, Calc calls its 10-bit shuffling random number generator
18622(which returns a value from 0 to 1023); if the random value is 1000
18623or more, Calc throws it out and tries again until it gets a suitable
18624value.
18625
18626To create a random floating-point number with precision @var{p}, Calc
18627simply creates a random @var{p}-digit integer and multiplies by
18628@c{$10^{-p}$}
18629@cite{10^-p}. The resulting random numbers should be very clean, but note
18630that relatively small numbers will have few significant random digits.
18631In other words, with a precision of 12, you will occasionally get
18632numbers on the order of @c{$10^{-9}$}
18633@cite{10^-9} or @c{$10^{-10}$}
18634@cite{10^-10}, but those numbers
18635will only have two or three random digits since they correspond to small
18636integers times @c{$10^{-12}$}
18637@cite{10^-12}.
18638
18639To create a random integer in the interval @samp{[0 .. @var{m})}, Calc
18640counts the digits in @var{m}, creates a random integer with three
18641additional digits, then reduces modulo @var{m}. Unless @var{m} is a
18642power of ten the resulting values will be very slightly biased toward
18643the lower numbers, but this bias will be less than 0.1%. (For example,
18644if @var{m} is 42, Calc will reduce a random integer less than 100000
18645modulo 42 to get a result less than 42. It is easy to show that the
18646numbers 40 and 41 will be only 2380/2381 as likely to result from this
18647modulo operation as numbers 39 and below.) If @var{m} is a power of
18648ten, however, the numbers should be completely unbiased.
18649
18650The Gaussian random numbers generated by @samp{random(0.0)} use the
18651``polar'' method described in Knuth section 3.4.1C. This method
18652generates a pair of Gaussian random numbers at a time, so only every
18653other call to @samp{random(0.0)} will require significant calculations.
18654
18655@node Combinatorial Functions, Probability Distribution Functions, Random Numbers, Scientific Functions
18656@section Combinatorial Functions
18657
18658@noindent
18659Commands relating to combinatorics and number theory begin with the
18660@kbd{k} key prefix.
18661
18662@kindex k g
18663@pindex calc-gcd
18664@tindex gcd
18665The @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the
18666Greatest Common Divisor of two integers. It also accepts fractions;
18667the GCD of two fractions is defined by taking the GCD of the
18668numerators, and the LCM of the denominators. This definition is
18669consistent with the idea that @samp{a / gcd(a,x)} should yield an
18670integer for any @samp{a} and @samp{x}. For other types of arguments,
18671the operation is left in symbolic form.@refill
18672
18673@kindex k l
18674@pindex calc-lcm
18675@tindex lcm
18676The @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the
18677Least Common Multiple of two integers or fractions. The product of
18678the LCM and GCD of two numbers is equal to the product of the
18679numbers.@refill
18680
18681@kindex k E
18682@pindex calc-extended-gcd
18683@tindex egcd
18684The @kbd{k E} (@code{calc-extended-gcd}) [@code{egcd}] command computes
18685the GCD of two integers @cite{x} and @cite{y} and returns a vector
18686@cite{[g, a, b]} where @c{$g = \gcd(x,y) = a x + b y$}
18687@cite{g = gcd(x,y) = a x + b y}.
18688
18689@kindex !
18690@pindex calc-factorial
18691@tindex fact
18692@c @mindex @null
18693@tindex !
18694The @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the
18695factorial of the number at the top of the stack. If the number is an
18696integer, the result is an exact integer. If the number is an
18697integer-valued float, the result is a floating-point approximation. If
18698the number is a non-integral real number, the generalized factorial is used,
18699as defined by the Euler Gamma function. Please note that computation of
18700large factorials can be slow; using floating-point format will help
18701since fewer digits must be maintained. The same is true of many of
18702the commands in this section.@refill
18703
18704@kindex k d
18705@pindex calc-double-factorial
18706@tindex dfact
18707@c @mindex @null
18708@tindex !!
18709The @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command
18710computes the ``double factorial'' of an integer. For an even integer,
18711this is the product of even integers from 2 to @cite{N}. For an odd
18712integer, this is the product of odd integers from 3 to @cite{N}. If
18713the argument is an integer-valued float, the result is a floating-point
18714approximation. This function is undefined for negative even integers.
18715The notation @cite{N!!} is also recognized for double factorials.@refill
18716
18717@kindex k c
18718@pindex calc-choose
18719@tindex choose
18720The @kbd{k c} (@code{calc-choose}) [@code{choose}] command computes the
18721binomial coefficient @cite{N}-choose-@cite{M}, where @cite{M} is the number
18722on the top of the stack and @cite{N} is second-to-top. If both arguments
18723are integers, the result is an exact integer. Otherwise, the result is a
18724floating-point approximation. The binomial coefficient is defined for all
18725real numbers by @c{$N! \over M! (N-M)!\,$}
18726@cite{N! / M! (N-M)!}.
18727
18728@kindex H k c
18729@pindex calc-perm
18730@tindex perm
18731@ifinfo
18732The @kbd{H k c} (@code{calc-perm}) [@code{perm}] command computes the
18733number-of-permutations function @cite{N! / (N-M)!}.
18734@end ifinfo
18735@tex
18736The \kbd{H k c} (\code{calc-perm}) [\code{perm}] command computes the
18737number-of-perm\-utations function $N! \over (N-M)!\,$.
18738@end tex
18739
18740@kindex k b
18741@kindex H k b
18742@pindex calc-bernoulli-number
18743@tindex bern
18744The @kbd{k b} (@code{calc-bernoulli-number}) [@code{bern}] command
18745computes a given Bernoulli number. The value at the top of the stack
18746is a nonnegative integer @cite{n} that specifies which Bernoulli number
18747is desired. The @kbd{H k b} command computes a Bernoulli polynomial,
18748taking @cite{n} from the second-to-top position and @cite{x} from the
18749top of the stack. If @cite{x} is a variable or formula the result is
18750a polynomial in @cite{x}; if @cite{x} is a number the result is a number.
18751
18752@kindex k e
18753@kindex H k e
18754@pindex calc-euler-number
18755@tindex euler
18756The @kbd{k e} (@code{calc-euler-number}) [@code{euler}] command similarly
18757computes an Euler number, and @w{@kbd{H k e}} computes an Euler polynomial.
18758Bernoulli and Euler numbers occur in the Taylor expansions of several
18759functions.
18760
18761@kindex k s
18762@kindex H k s
18763@pindex calc-stirling-number
18764@tindex stir1
18765@tindex stir2
18766The @kbd{k s} (@code{calc-stirling-number}) [@code{stir1}] command
18767computes a Stirling number of the first kind@c{ $n \brack m$}
18768@asis{}, given two integers
18769@cite{n} and @cite{m} on the stack. The @kbd{H k s} [@code{stir2}]
18770command computes a Stirling number of the second kind@c{ $n \brace m$}
18771@asis{}. These are
18772the number of @cite{m}-cycle permutations of @cite{n} objects, and
18773the number of ways to partition @cite{n} objects into @cite{m}
18774non-empty sets, respectively.
18775
18776@kindex k p
18777@pindex calc-prime-test
18778@cindex Primes
18779The @kbd{k p} (@code{calc-prime-test}) command checks if the integer on
18780the top of the stack is prime. For integers less than eight million, the
18781answer is always exact and reasonably fast. For larger integers, a
18782probabilistic method is used (see Knuth vol. II, section 4.5.4, algorithm P).
18783The number is first checked against small prime factors (up to 13). Then,
18784any number of iterations of the algorithm are performed. Each step either
18785discovers that the number is non-prime, or substantially increases the
18786certainty that the number is prime. After a few steps, the chance that
18787a number was mistakenly described as prime will be less than one percent.
18788(Indeed, this is a worst-case estimate of the probability; in practice
18789even a single iteration is quite reliable.) After the @kbd{k p} command,
18790the number will be reported as definitely prime or non-prime if possible,
18791or otherwise ``probably'' prime with a certain probability of error.
18792
18793@c @starindex
18794@tindex prime
18795The normal @kbd{k p} command performs one iteration of the primality
18796test. Pressing @kbd{k p} repeatedly for the same integer will perform
18797additional iterations. Also, @kbd{k p} with a numeric prefix performs
18798the specified number of iterations. There is also an algebraic function
18799@samp{prime(n)} or @samp{prime(n,iters)} which returns 1 if @cite{n}
18800is (probably) prime and 0 if not.
18801
18802@kindex k f
18803@pindex calc-prime-factors
18804@tindex prfac
18805The @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command
18806attempts to decompose an integer into its prime factors. For numbers up
18807to 25 million, the answer is exact although it may take some time. The
18808result is a vector of the prime factors in increasing order. For larger
18809inputs, prime factors above 5000 may not be found, in which case the
18810last number in the vector will be an unfactored integer greater than 25
18811million (with a warning message). For negative integers, the first
18812element of the list will be @i{-1}. For inputs @i{-1}, @i{0}, and
18813@i{1}, the result is a list of the same number.
18814
18815@kindex k n
18816@pindex calc-next-prime
18817@c @mindex nextpr@idots
18818@tindex nextprime
18819The @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds
18820the next prime above a given number. Essentially, it searches by calling
18821@code{calc-prime-test} on successive integers until it finds one that
18822passes the test. This is quite fast for integers less than eight million,
18823but once the probabilistic test comes into play the search may be rather
18824slow. Ordinarily this command stops for any prime that passes one iteration
18825of the primality test. With a numeric prefix argument, a number must pass
18826the specified number of iterations before the search stops. (This only
18827matters when searching above eight million.) You can always use additional
18828@kbd{k p} commands to increase your certainty that the number is indeed
18829prime.
18830
18831@kindex I k n
18832@pindex calc-prev-prime
18833@c @mindex prevpr@idots
18834@tindex prevprime
18835The @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command
18836analogously finds the next prime less than a given number.
18837
18838@kindex k t
18839@pindex calc-totient
18840@tindex totient
18841The @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the
18842Euler ``totient'' function@c{ $\phi(n)$}
18843@asis{}, the number of integers less than @cite{n} which
18844are relatively prime to @cite{n}.
18845
18846@kindex k m
18847@pindex calc-moebius
18848@tindex moebius
18849The @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the
18850@c{M\"obius $\mu$}
18851@asis{Moebius ``mu''} function. If the input number is a product of @cite{k}
18852distinct factors, this is @cite{(-1)^k}. If the input number has any
18853duplicate factors (i.e., can be divided by the same prime more than once),
18854the result is zero.
18855
18856@node Probability Distribution Functions, , Combinatorial Functions, Scientific Functions
18857@section Probability Distribution Functions
18858
18859@noindent
18860The functions in this section compute various probability distributions.
18861For continuous distributions, this is the integral of the probability
18862density function from @cite{x} to infinity. (These are the ``upper
18863tail'' distribution functions; there are also corresponding ``lower
18864tail'' functions which integrate from minus infinity to @cite{x}.)
18865For discrete distributions, the upper tail function gives the sum
18866from @cite{x} to infinity; the lower tail function gives the sum
18867from minus infinity up to, but not including,@w{ }@cite{x}.
18868
18869To integrate from @cite{x} to @cite{y}, just use the distribution
18870function twice and subtract. For example, the probability that a
18871Gaussian random variable with mean 2 and standard deviation 1 will
18872lie in the range from 2.5 to 2.8 is @samp{utpn(2.5,2,1) - utpn(2.8,2,1)}
18873(``the probability that it is greater than 2.5, but not greater than 2.8''),
18874or equivalently @samp{ltpn(2.8,2,1) - ltpn(2.5,2,1)}.
18875
18876@kindex k B
18877@kindex I k B
18878@pindex calc-utpb
18879@tindex utpb
18880@tindex ltpb
18881The @kbd{k B} (@code{calc-utpb}) [@code{utpb}] function uses the
18882binomial distribution. Push the parameters @var{n}, @var{p}, and
18883then @var{x} onto the stack; the result (@samp{utpb(x,n,p)}) is the
18884probability that an event will occur @var{x} or more times out
18885of @var{n} trials, if its probability of occurring in any given
18886trial is @var{p}. The @kbd{I k B} [@code{ltpb}] function is
18887the probability that the event will occur fewer than @var{x} times.
18888
18889The other probability distribution functions similarly take the
18890form @kbd{k @var{X}} (@code{calc-utp@var{x}}) [@code{utp@var{x}}]
18891and @kbd{I k @var{X}} [@code{ltp@var{x}}], for various letters
18892@var{x}. The arguments to the algebraic functions are the value of
18893the random variable first, then whatever other parameters define the
18894distribution. Note these are among the few Calc functions where the
18895order of the arguments in algebraic form differs from the order of
18896arguments as found on the stack. (The random variable comes last on
18897the stack, so that you can type, e.g., @kbd{2 @key{RET} 1 @key{RET} 2.5
18898k N M-@key{RET} @key{DEL} 2.8 k N -}, using @kbd{M-@key{RET} @key{DEL}} to
18899recover the original arguments but substitute a new value for @cite{x}.)
18900
18901@kindex k C
18902@pindex calc-utpc
18903@tindex utpc
18904@c @mindex @idots
18905@kindex I k C
18906@c @mindex @null
18907@tindex ltpc
18908The @samp{utpc(x,v)} function uses the chi-square distribution with
18909@c{$\nu$}
18910@cite{v} degrees of freedom. It is the probability that a model is
18911correct if its chi-square statistic is @cite{x}.
18912
18913@kindex k F
18914@pindex calc-utpf
18915@tindex utpf
18916@c @mindex @idots
18917@kindex I k F
18918@c @mindex @null
18919@tindex ltpf
18920The @samp{utpf(F,v1,v2)} function uses the F distribution, used in
18921various statistical tests. The parameters @c{$\nu_1$}
18922@cite{v1} and @c{$\nu_2$}
18923@cite{v2}
18924are the degrees of freedom in the numerator and denominator,
18925respectively, used in computing the statistic @cite{F}.
18926
18927@kindex k N
18928@pindex calc-utpn
18929@tindex utpn
18930@c @mindex @idots
18931@kindex I k N
18932@c @mindex @null
18933@tindex ltpn
18934The @samp{utpn(x,m,s)} function uses a normal (Gaussian) distribution
18935with mean @cite{m} and standard deviation @c{$\sigma$}
18936@cite{s}. It is the
18937probability that such a normal-distributed random variable would
18938exceed @cite{x}.
18939
18940@kindex k P
18941@pindex calc-utpp
18942@tindex utpp
18943@c @mindex @idots
18944@kindex I k P
18945@c @mindex @null
18946@tindex ltpp
18947The @samp{utpp(n,x)} function uses a Poisson distribution with
18948mean @cite{x}. It is the probability that @cite{n} or more such
18949Poisson random events will occur.
18950
18951@kindex k T
18952@pindex calc-ltpt
18953@tindex utpt
18954@c @mindex @idots
18955@kindex I k T
18956@c @mindex @null
18957@tindex ltpt
18958The @samp{utpt(t,v)} function uses the Student's ``t'' distribution
18959with @c{$\nu$}
18960@cite{v} degrees of freedom. It is the probability that a
18961t-distributed random variable will be greater than @cite{t}.
18962(Note: This computes the distribution function @c{$A(t|\nu)$}
18963@cite{A(t|v)}
18964where @c{$A(0|\nu) = 1$}
18965@cite{A(0|v) = 1} and @c{$A(\infty|\nu) \to 0$}
18966@cite{A(inf|v) -> 0}. The
18967@code{UTPT} operation on the HP-48 uses a different definition
18968which returns half of Calc's value: @samp{UTPT(t,v) = .5*utpt(t,v)}.)
18969
18970While Calc does not provide inverses of the probability distribution
18971functions, the @kbd{a R} command can be used to solve for the inverse.
18972Since the distribution functions are monotonic, @kbd{a R} is guaranteed
18973to be able to find a solution given any initial guess.
18974@xref{Numerical Solutions}.
18975
18976@node Matrix Functions, Algebra, Scientific Functions, Top
18977@chapter Vector/Matrix Functions
18978
18979@noindent
18980Many of the commands described here begin with the @kbd{v} prefix.
18981(For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.)
18982The commands usually apply to both plain vectors and matrices; some
18983apply only to matrices or only to square matrices. If the argument
18984has the wrong dimensions the operation is left in symbolic form.
18985
18986Vectors are entered and displayed using @samp{[a,b,c]} notation.
18987Matrices are vectors of which all elements are vectors of equal length.
18988(Though none of the standard Calc commands use this concept, a
18989three-dimensional matrix or rank-3 tensor could be defined as a
18990vector of matrices, and so on.)
18991
18992@menu
18993* Packing and Unpacking::
18994* Building Vectors::
18995* Extracting Elements::
18996* Manipulating Vectors::
18997* Vector and Matrix Arithmetic::
18998* Set Operations::
18999* Statistical Operations::
19000* Reducing and Mapping::
19001* Vector and Matrix Formats::
19002@end menu
19003
19004@node Packing and Unpacking, Building Vectors, Matrix Functions, Matrix Functions
19005@section Packing and Unpacking
19006
19007@noindent
19008Calc's ``pack'' and ``unpack'' commands collect stack entries to build
19009composite objects such as vectors and complex numbers. They are
19010described in this chapter because they are most often used to build
19011vectors.
19012
19013@kindex v p
19014@pindex calc-pack
19015The @kbd{v p} (@code{calc-pack}) [@code{pack}] command collects several
19016elements from the stack into a matrix, complex number, HMS form, error
19017form, etc. It uses a numeric prefix argument to specify the kind of
19018object to be built; this argument is referred to as the ``packing mode.''
19019If the packing mode is a nonnegative integer, a vector of that
19020length is created. For example, @kbd{C-u 5 v p} will pop the top
19021five stack elements and push back a single vector of those five
19022elements. (@kbd{C-u 0 v p} simply creates an empty vector.)
19023
19024The same effect can be had by pressing @kbd{[} to push an incomplete
19025vector on the stack, using @key{TAB} (@code{calc-roll-down}) to sneak
19026the incomplete object up past a certain number of elements, and
19027then pressing @kbd{]} to complete the vector.
19028
19029Negative packing modes create other kinds of composite objects:
19030
19031@table @cite
19032@item -1
19033Two values are collected to build a complex number. For example,
19034@kbd{5 @key{RET} 7 C-u -1 v p} creates the complex number
19035@cite{(5, 7)}. The result is always a rectangular complex
19036number. The two input values must both be real numbers,
19037i.e., integers, fractions, or floats. If they are not, Calc
19038will instead build a formula like @samp{a + (0, 1) b}. (The
19039other packing modes also create a symbolic answer if the
19040components are not suitable.)
19041
19042@item -2
19043Two values are collected to build a polar complex number.
19044The first is the magnitude; the second is the phase expressed
19045in either degrees or radians according to the current angular
19046mode.
19047
19048@item -3
19049Three values are collected into an HMS form. The first
19050two values (hours and minutes) must be integers or
19051integer-valued floats. The third value may be any real
19052number.
19053
19054@item -4
19055Two values are collected into an error form. The inputs
19056may be real numbers or formulas.
19057
19058@item -5
19059Two values are collected into a modulo form. The inputs
19060must be real numbers.
19061
19062@item -6
19063Two values are collected into the interval @samp{[a .. b]}.
19064The inputs may be real numbers, HMS or date forms, or formulas.
19065
19066@item -7
19067Two values are collected into the interval @samp{[a .. b)}.
19068
19069@item -8
19070Two values are collected into the interval @samp{(a .. b]}.
19071
19072@item -9
19073Two values are collected into the interval @samp{(a .. b)}.
19074
19075@item -10
19076Two integer values are collected into a fraction.
19077
19078@item -11
19079Two values are collected into a floating-point number.
19080The first is the mantissa; the second, which must be an
19081integer, is the exponent. The result is the mantissa
19082times ten to the power of the exponent.
19083
19084@item -12
19085This is treated the same as @i{-11} by the @kbd{v p} command.
19086When unpacking, @i{-12} specifies that a floating-point mantissa
19087is desired.
19088
19089@item -13
19090A real number is converted into a date form.
19091
19092@item -14
19093Three numbers (year, month, day) are packed into a pure date form.
19094
19095@item -15
19096Six numbers are packed into a date/time form.
19097@end table
19098
19099With any of the two-input negative packing modes, either or both
19100of the inputs may be vectors. If both are vectors of the same
19101length, the result is another vector made by packing corresponding
19102elements of the input vectors. If one input is a vector and the
19103other is a plain number, the number is packed along with each vector
19104element to produce a new vector. For example, @kbd{C-u -4 v p}
19105could be used to convert a vector of numbers and a vector of errors
19106into a single vector of error forms; @kbd{C-u -5 v p} could convert
19107a vector of numbers and a single number @var{M} into a vector of
19108numbers modulo @var{M}.
19109
19110If you don't give a prefix argument to @kbd{v p}, it takes
19111the packing mode from the top of the stack. The elements to
19112be packed then begin at stack level 2. Thus
19113@kbd{1 @key{RET} 2 @key{RET} 4 n v p} is another way to
19114enter the error form @samp{1 +/- 2}.
19115
19116If the packing mode taken from the stack is a vector, the result is a
19117matrix with the dimensions specified by the elements of the vector,
19118which must each be integers. For example, if the packing mode is
19119@samp{[2, 3]}, then six numbers will be taken from the stack and
19120returned in the form @samp{[@w{[a, b, c]}, [d, e, f]]}.
19121
19122If any elements of the vector are negative, other kinds of
19123packing are done at that level as described above. For
19124example, @samp{[2, 3, -4]} takes 12 objects and creates a
19125@c{$2\times3$}
19126@asis{2x3} matrix of error forms: @samp{[[a +/- b, c +/- d ... ]]}.
19127Also, @samp{[-4, -10]} will convert four integers into an
19128error form consisting of two fractions: @samp{a:b +/- c:d}.
19129
19130@c @starindex
19131@tindex pack
19132There is an equivalent algebraic function,
19133@samp{pack(@var{mode}, @var{items})} where @var{mode} is a
19134packing mode (an integer or a vector of integers) and @var{items}
19135is a vector of objects to be packed (re-packed, really) according
19136to that mode. For example, @samp{pack([3, -4], [a,b,c,d,e,f])}
19137yields @samp{[a +/- b, @w{c +/- d}, e +/- f]}. The function is
19138left in symbolic form if the packing mode is illegal, or if the
19139number of data items does not match the number of items required
19140by the mode.
19141
19142@kindex v u
19143@pindex calc-unpack
19144The @kbd{v u} (@code{calc-unpack}) command takes the vector, complex
19145number, HMS form, or other composite object on the top of the stack and
19146``unpacks'' it, pushing each of its elements onto the stack as separate
19147objects. Thus, it is the ``inverse'' of @kbd{v p}. If the value
19148at the top of the stack is a formula, @kbd{v u} unpacks it by pushing
19149each of the arguments of the top-level operator onto the stack.
19150
19151You can optionally give a numeric prefix argument to @kbd{v u}
19152to specify an explicit (un)packing mode. If the packing mode is
19153negative and the input is actually a vector or matrix, the result
19154will be two or more similar vectors or matrices of the elements.
19155For example, given the vector @samp{[@w{a +/- b}, c^2, d +/- 7]},
19156the result of @kbd{C-u -4 v u} will be the two vectors
19157@samp{[a, c^2, d]} and @w{@samp{[b, 0, 7]}}.
19158
19159Note that the prefix argument can have an effect even when the input is
19160not a vector. For example, if the input is the number @i{-5}, then
19161@kbd{c-u -1 v u} yields @i{-5} and 0 (the components of @i{-5}
19162when viewed as a rectangular complex number); @kbd{C-u -2 v u} yields 5
19163and 180 (assuming degrees mode); and @kbd{C-u -10 v u} yields @i{-5}
19164and 1 (the numerator and denominator of @i{-5}, viewed as a rational
19165number). Plain @kbd{v u} with this input would complain that the input
19166is not a composite object.
19167
19168Unpacking mode @i{-11} converts a float into an integer mantissa and
19169an integer exponent, where the mantissa is not divisible by 10
19170(except that 0.0 is represented by a mantissa and exponent of 0).
19171Unpacking mode @i{-12} converts a float into a floating-point mantissa
19172and integer exponent, where the mantissa (for non-zero numbers)
19173is guaranteed to lie in the range [1 .. 10). In both cases,
19174the mantissa is shifted left or right (and the exponent adjusted
19175to compensate) in order to satisfy these constraints.
19176
19177Positive unpacking modes are treated differently than for @kbd{v p}.
19178A mode of 1 is much like plain @kbd{v u} with no prefix argument,
19179except that in addition to the components of the input object,
19180a suitable packing mode to re-pack the object is also pushed.
19181Thus, @kbd{C-u 1 v u} followed by @kbd{v p} will re-build the
19182original object.
19183
19184A mode of 2 unpacks two levels of the object; the resulting
19185re-packing mode will be a vector of length 2. This might be used
19186to unpack a matrix, say, or a vector of error forms. Higher
19187unpacking modes unpack the input even more deeply.
19188
19189@c @starindex
19190@tindex unpack
19191There are two algebraic functions analogous to @kbd{v u}.
19192The @samp{unpack(@var{mode}, @var{item})} function unpacks the
19193@var{item} using the given @var{mode}, returning the result as
19194a vector of components. Here the @var{mode} must be an
19195integer, not a vector. For example, @samp{unpack(-4, a +/- b)}
19196returns @samp{[a, b]}, as does @samp{unpack(1, a +/- b)}.
19197
19198@c @starindex
19199@tindex unpackt
19200The @code{unpackt} function is like @code{unpack} but instead
19201of returning a simple vector of items, it returns a vector of
19202two things: The mode, and the vector of items. For example,
19203@samp{unpackt(1, 2:3 +/- 1:4)} returns @samp{[-4, [2:3, 1:4]]},
19204and @samp{unpackt(2, 2:3 +/- 1:4)} returns @samp{[[-4, -10], [2, 3, 1, 4]]}.
19205The identity for re-building the original object is
19206@samp{apply(pack, unpackt(@var{n}, @var{x})) = @var{x}}. (The
19207@code{apply} function builds a function call given the function
19208name and a vector of arguments.)
19209
19210@cindex Numerator of a fraction, extracting
19211Subscript notation is a useful way to extract a particular part
19212of an object. For example, to get the numerator of a rational
19213number, you can use @samp{unpack(-10, @var{x})_1}.
19214
19215@node Building Vectors, Extracting Elements, Packing and Unpacking, Matrix Functions
19216@section Building Vectors
19217
19218@noindent
19219Vectors and matrices can be added,
19220subtracted, multiplied, and divided; @pxref{Basic Arithmetic}.@refill
19221
19222@kindex |
19223@pindex calc-concat
19224@c @mindex @null
19225@tindex |
19226The @kbd{|} (@code{calc-concat}) command ``concatenates'' two vectors
19227into one. For example, after @kbd{@w{[ 1 , 2 ]} [ 3 , 4 ] |}, the stack
19228will contain the single vector @samp{[1, 2, 3, 4]}. If the arguments
19229are matrices, the rows of the first matrix are concatenated with the
19230rows of the second. (In other words, two matrices are just two vectors
19231of row-vectors as far as @kbd{|} is concerned.)
19232
19233If either argument to @kbd{|} is a scalar (a non-vector), it is treated
19234like a one-element vector for purposes of concatenation: @kbd{1 [ 2 , 3 ] |}
19235produces the vector @samp{[1, 2, 3]}. Likewise, if one argument is a
19236matrix and the other is a plain vector, the vector is treated as a
19237one-row matrix.
19238
19239@kindex H |
19240@tindex append
19241The @kbd{H |} (@code{calc-append}) [@code{append}] command concatenates
19242two vectors without any special cases. Both inputs must be vectors.
19243Whether or not they are matrices is not taken into account. If either
19244argument is a scalar, the @code{append} function is left in symbolic form.
19245See also @code{cons} and @code{rcons} below.
19246
19247@kindex I |
19248@kindex H I |
19249The @kbd{I |} and @kbd{H I |} commands are similar, but they use their
19250two stack arguments in the opposite order. Thus @kbd{I |} is equivalent
19251to @kbd{TAB |}, but possibly more convenient and also a bit faster.
19252
19253@kindex v d
19254@pindex calc-diag
19255@tindex diag
19256The @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal
19257square matrix. The optional numeric prefix gives the number of rows
19258and columns in the matrix. If the value at the top of the stack is a
19259vector, the elements of the vector are used as the diagonal elements; the
19260prefix, if specified, must match the size of the vector. If the value on
19261the stack is a scalar, it is used for each element on the diagonal, and
19262the prefix argument is required.
19263
19264To build a constant square matrix, e.g., a @c{$3\times3$}
19265@asis{3x3} matrix filled with ones,
19266use @kbd{0 M-3 v d 1 +}, i.e., build a zero matrix first and then add a
19267constant value to that matrix. (Another alternative would be to use
19268@kbd{v b} and @kbd{v a}; see below.)
19269
19270@kindex v i
19271@pindex calc-ident
19272@tindex idn
19273The @kbd{v i} (@code{calc-ident}) [@code{idn}] function builds an identity
19274matrix of the specified size. It is a convenient form of @kbd{v d}
19275where the diagonal element is always one. If no prefix argument is given,
19276this command prompts for one.
19277
19278In algebraic notation, @samp{idn(a,n)} acts much like @samp{diag(a,n)},
19279except that @cite{a} is required to be a scalar (non-vector) quantity.
19280If @cite{n} is omitted, @samp{idn(a)} represents @cite{a} times an
19281identity matrix of unknown size. Calc can operate algebraically on
19282such generic identity matrices, and if one is combined with a matrix
19283whose size is known, it is converted automatically to an identity
19284matrix of a suitable matching size. The @kbd{v i} command with an
19285argument of zero creates a generic identity matrix, @samp{idn(1)}.
19286Note that in dimensioned matrix mode (@pxref{Matrix Mode}), generic
19287identity matrices are immediately expanded to the current default
19288dimensions.
19289
19290@kindex v x
19291@pindex calc-index
19292@tindex index
19293The @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector
19294of consecutive integers from 1 to @var{n}, where @var{n} is the numeric
19295prefix argument. If you do not provide a prefix argument, you will be
19296prompted to enter a suitable number. If @var{n} is negative, the result
19297is a vector of negative integers from @var{n} to @i{-1}.
19298
19299With a prefix argument of just @kbd{C-u}, the @kbd{v x} command takes
19300three values from the stack: @var{n}, @var{start}, and @var{incr} (with
19301@var{incr} at top-of-stack). Counting starts at @var{start} and increases
19302by @var{incr} for successive vector elements. If @var{start} or @var{n}
19303is in floating-point format, the resulting vector elements will also be
19304floats. Note that @var{start} and @var{incr} may in fact be any kind
19305of numbers or formulas.
19306
19307When @var{start} and @var{incr} are specified, a negative @var{n} has a
19308different interpretation: It causes a geometric instead of arithmetic
19309sequence to be generated. For example, @samp{index(-3, a, b)} produces
19310@samp{[a, a b, a b^2]}. If you omit @var{incr} in the algebraic form,
19311@samp{index(@var{n}, @var{start})}, the default value for @var{incr}
19312is one for positive @var{n} or two for negative @var{n}.
19313
19314@kindex v b
19315@pindex calc-build-vector
19316@tindex cvec
19317The @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a
19318vector of @var{n} copies of the value on the top of the stack, where @var{n}
19319is the numeric prefix argument. In algebraic formulas, @samp{cvec(x,n,m)}
19320can also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}.
19321(Interactively, just use @kbd{v b} twice: once to build a row, then again
19322to build a matrix of copies of that row.)
19323
19324@kindex v h
19325@kindex I v h
19326@pindex calc-head
19327@pindex calc-tail
19328@tindex head
19329@tindex tail
19330The @kbd{v h} (@code{calc-head}) [@code{head}] function returns the first
19331element of a vector. The @kbd{I v h} (@code{calc-tail}) [@code{tail}]
19332function returns the vector with its first element removed. In both
19333cases, the argument must be a non-empty vector.
19334
19335@kindex v k
19336@pindex calc-cons
19337@tindex cons
19338The @kbd{v k} (@code{calc-cons}) [@code{cons}] function takes a value @var{h}
19339and a vector @var{t} from the stack, and produces the vector whose head is
19340@var{h} and whose tail is @var{t}. This is similar to @kbd{|}, except
19341if @var{h} is itself a vector, @kbd{|} will concatenate the two vectors
19342whereas @code{cons} will insert @var{h} at the front of the vector @var{t}.
19343
19344@kindex H v h
19345@tindex rhead
19346@c @mindex @idots
19347@kindex H I v h
19348@c @mindex @null
19349@kindex H v k
19350@c @mindex @null
19351@tindex rtail
19352@c @mindex @null
19353@tindex rcons
19354Each of these three functions also accepts the Hyperbolic flag [@code{rhead},
19355@code{rtail}, @code{rcons}] in which case @var{t} instead represents
19356the @emph{last} single element of the vector, with @var{h}
19357representing the remainder of the vector. Thus the vector
19358@samp{[a, b, c, d] = cons(a, [b, c, d]) = rcons([a, b, c], d)}.
19359Also, @samp{head([a, b, c, d]) = a}, @samp{tail([a, b, c, d]) = [b, c, d]},
19360@samp{rhead([a, b, c, d]) = [a, b, c]}, and @samp{rtail([a, b, c, d]) = d}.
19361
19362@node Extracting Elements, Manipulating Vectors, Building Vectors, Matrix Functions
19363@section Extracting Vector Elements
19364
19365@noindent
19366@kindex v r
19367@pindex calc-mrow
19368@tindex mrow
19369The @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of
19370the matrix on the top of the stack, or one element of the plain vector on
19371the top of the stack. The row or element is specified by the numeric
19372prefix argument; the default is to prompt for the row or element number.
19373The matrix or vector is replaced by the specified row or element in the
19374form of a vector or scalar, respectively.
19375
19376@cindex Permutations, applying
19377With a prefix argument of @kbd{C-u} only, @kbd{v r} takes the index of
19378the element or row from the top of the stack, and the vector or matrix
19379from the second-to-top position. If the index is itself a vector of
19380integers, the result is a vector of the corresponding elements of the
19381input vector, or a matrix of the corresponding rows of the input matrix.
19382This command can be used to obtain any permutation of a vector.
19383
19384With @kbd{C-u}, if the index is an interval form with integer components,
19385it is interpreted as a range of indices and the corresponding subvector or
19386submatrix is returned.
19387
19388@cindex Subscript notation
19389@kindex a _
19390@pindex calc-subscript
19391@tindex subscr
19392@tindex _
19393Subscript notation in algebraic formulas (@samp{a_b}) stands for the
19394Calc function @code{subscr}, which is synonymous with @code{mrow}.
19395Thus, @samp{[x, y, z]_k} produces @cite{x}, @cite{y}, or @cite{z} if
19396@cite{k} is one, two, or three, respectively. A double subscript
19397(@samp{M_i_j}, equivalent to @samp{subscr(subscr(M, i), j)}) will
19398access the element at row @cite{i}, column @cite{j} of a matrix.
19399The @kbd{a _} (@code{calc-subscript}) command creates a subscript
19400formula @samp{a_b} out of two stack entries. (It is on the @kbd{a}
19401``algebra'' prefix because subscripted variables are often used
19402purely as an algebraic notation.)
19403
19404@tindex mrrow
19405Given a negative prefix argument, @kbd{v r} instead deletes one row or
19406element from the matrix or vector on the top of the stack. Thus
19407@kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r}
19408replaces the matrix with the same matrix with its second row removed.
19409In algebraic form this function is called @code{mrrow}.
19410
19411@tindex getdiag
19412Given a prefix argument of zero, @kbd{v r} extracts the diagonal elements
19413of a square matrix in the form of a vector. In algebraic form this
19414function is called @code{getdiag}.
19415
19416@kindex v c
19417@pindex calc-mcol
19418@tindex mcol
19419@tindex mrcol
19420The @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is
19421the analogous operation on columns of a matrix. Given a plain vector
19422it extracts (or removes) one element, just like @kbd{v r}. If the
19423index in @kbd{C-u v c} is an interval or vector and the argument is a
19424matrix, the result is a submatrix with only the specified columns
19425retained (and possibly permuted in the case of a vector index).@refill
19426
19427To extract a matrix element at a given row and column, use @kbd{v r} to
19428extract the row as a vector, then @kbd{v c} to extract the column element
19429from that vector. In algebraic formulas, it is often more convenient to
19430use subscript notation: @samp{m_i_j} gives row @cite{i}, column @cite{j}
19431of matrix @cite{m}.
19432
19433@kindex v s
19434@pindex calc-subvector
19435@tindex subvec
19436The @kbd{v s} (@code{calc-subvector}) [@code{subvec}] command extracts
19437a subvector of a vector. The arguments are the vector, the starting
19438index, and the ending index, with the ending index in the top-of-stack
19439position. The starting index indicates the first element of the vector
19440to take. The ending index indicates the first element @emph{past} the
19441range to be taken. Thus, @samp{subvec([a, b, c, d, e], 2, 4)} produces
19442the subvector @samp{[b, c]}. You could get the same result using
19443@samp{mrow([a, b, c, d, e], @w{[2 .. 4)})}.
19444
19445If either the start or the end index is zero or negative, it is
19446interpreted as relative to the end of the vector. Thus
19447@samp{subvec([a, b, c, d, e], 2, -2)} also produces @samp{[b, c]}. In
19448the algebraic form, the end index can be omitted in which case it
19449is taken as zero, i.e., elements from the starting element to the
19450end of the vector are used. The infinity symbol, @code{inf}, also
19451has this effect when used as the ending index.
19452
19453@kindex I v s
19454@tindex rsubvec
19455With the Inverse flag, @kbd{I v s} [@code{rsubvec}] removes a subvector
19456from a vector. The arguments are interpreted the same as for the
19457normal @kbd{v s} command. Thus, @samp{rsubvec([a, b, c, d, e], 2, 4)}
19458produces @samp{[a, d, e]}. It is always true that @code{subvec} and
19459@code{rsubvec} return complementary parts of the input vector.
19460
19461@xref{Selecting Subformulas}, for an alternative way to operate on
19462vectors one element at a time.
19463
19464@node Manipulating Vectors, Vector and Matrix Arithmetic, Extracting Elements, Matrix Functions
19465@section Manipulating Vectors
19466
19467@noindent
19468@kindex v l
19469@pindex calc-vlength
19470@tindex vlen
19471The @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the
19472length of a vector. The length of a non-vector is considered to be zero.
19473Note that matrices are just vectors of vectors for the purposes of this
19474command.@refill
19475
19476@kindex H v l
19477@tindex mdims
19478With the Hyperbolic flag, @kbd{H v l} [@code{mdims}] computes a vector
19479of the dimensions of a vector, matrix, or higher-order object. For
19480example, @samp{mdims([[a,b,c],[d,e,f]])} returns @samp{[2, 3]} since
19481its argument is a @c{$2\times3$}
19482@asis{2x3} matrix.
19483
19484@kindex v f
19485@pindex calc-vector-find
19486@tindex find
19487The @kbd{v f} (@code{calc-vector-find}) [@code{find}] command searches
19488along a vector for the first element equal to a given target. The target
19489is on the top of the stack; the vector is in the second-to-top position.
19490If a match is found, the result is the index of the matching element.
19491Otherwise, the result is zero. The numeric prefix argument, if given,
19492allows you to select any starting index for the search.
19493
19494@kindex v a
19495@pindex calc-arrange-vector
19496@tindex arrange
19497@cindex Arranging a matrix
19498@cindex Reshaping a matrix
19499@cindex Flattening a matrix
19500The @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] command
19501rearranges a vector to have a certain number of columns and rows. The
19502numeric prefix argument specifies the number of columns; if you do not
19503provide an argument, you will be prompted for the number of columns.
19504The vector or matrix on the top of the stack is @dfn{flattened} into a
19505plain vector. If the number of columns is nonzero, this vector is
19506then formed into a matrix by taking successive groups of @var{n} elements.
19507If the number of columns does not evenly divide the number of elements
19508in the vector, the last row will be short and the result will not be
19509suitable for use as a matrix. For example, with the matrix
19510@samp{[[1, 2], @w{[3, 4]}]} on the stack, @kbd{v a 4} produces
19511@samp{[[1, 2, 3, 4]]} (a @c{$1\times4$}
19512@asis{1x4} matrix), @kbd{v a 1} produces
19513@samp{[[1], [2], [3], [4]]} (a @c{$4\times1$}
19514@asis{4x1} matrix), @kbd{v a 2} produces
19515@samp{[[1, 2], [3, 4]]} (the original @c{$2\times2$}
19516@asis{2x2} matrix), @w{@kbd{v a 3}} produces
19517@samp{[[1, 2, 3], [4]]} (not a matrix), and @kbd{v a 0} produces
19518the flattened list @samp{[1, 2, @w{3, 4}]}.
19519
19520@cindex Sorting data
19521@kindex V S
19522@kindex I V S
19523@pindex calc-sort
19524@tindex sort
19525@tindex rsort
19526The @kbd{V S} (@code{calc-sort}) [@code{sort}] command sorts the elements of
19527a vector into increasing order. Real numbers, real infinities, and
19528constant interval forms come first in this ordering; next come other
19529kinds of numbers, then variables (in alphabetical order), then finally
19530come formulas and other kinds of objects; these are sorted according
19531to a kind of lexicographic ordering with the useful property that
19532one vector is less or greater than another if the first corresponding
19533unequal elements are less or greater, respectively. Since quoted strings
19534are stored by Calc internally as vectors of ASCII character codes
19535(@pxref{Strings}), this means vectors of strings are also sorted into
19536alphabetical order by this command.
19537
19538The @kbd{I V S} [@code{rsort}] command sorts a vector into decreasing order.
19539
19540@cindex Permutation, inverse of
19541@cindex Inverse of permutation
19542@cindex Index tables
19543@cindex Rank tables
19544@kindex V G
19545@kindex I V G
19546@pindex calc-grade
19547@tindex grade
19548@tindex rgrade
19549The @kbd{V G} (@code{calc-grade}) [@code{grade}, @code{rgrade}] command
19550produces an index table or permutation vector which, if applied to the
19551input vector (as the index of @kbd{C-u v r}, say), would sort the vector.
19552A permutation vector is just a vector of integers from 1 to @var{n}, where
19553each integer occurs exactly once. One application of this is to sort a
19554matrix of data rows using one column as the sort key; extract that column,
19555grade it with @kbd{V G}, then use the result to reorder the original matrix
19556with @kbd{C-u v r}. Another interesting property of the @code{V G} command
19557is that, if the input is itself a permutation vector, the result will
19558be the inverse of the permutation. The inverse of an index table is
19559a rank table, whose @var{k}th element says where the @var{k}th original
19560vector element will rest when the vector is sorted. To get a rank
19561table, just use @kbd{V G V G}.
19562
19563With the Inverse flag, @kbd{I V G} produces an index table that would
19564sort the input into decreasing order. Note that @kbd{V S} and @kbd{V G}
19565use a ``stable'' sorting algorithm, i.e., any two elements which are equal
19566will not be moved out of their original order. Generally there is no way
19567to tell with @kbd{V S}, since two elements which are equal look the same,
19568but with @kbd{V G} this can be an important issue. In the matrix-of-rows
19569example, suppose you have names and telephone numbers as two columns and
19570you wish to sort by phone number primarily, and by name when the numbers
19571are equal. You can sort the data matrix by names first, and then again
19572by phone numbers. Because the sort is stable, any two rows with equal
19573phone numbers will remain sorted by name even after the second sort.
19574
19575@cindex Histograms
19576@kindex V H
19577@pindex calc-histogram
19578@c @mindex histo@idots
19579@tindex histogram
19580The @kbd{V H} (@code{calc-histogram}) [@code{histogram}] command builds a
19581histogram of a vector of numbers. Vector elements are assumed to be
19582integers or real numbers in the range [0..@var{n}) for some ``number of
19583bins'' @var{n}, which is the numeric prefix argument given to the
19584command. The result is a vector of @var{n} counts of how many times
19585each value appeared in the original vector. Non-integers in the input
19586are rounded down to integers. Any vector elements outside the specified
19587range are ignored. (You can tell if elements have been ignored by noting
19588that the counts in the result vector don't add up to the length of the
19589input vector.)
19590
19591@kindex H V H
19592With the Hyperbolic flag, @kbd{H V H} pulls two vectors from the stack.
19593The second-to-top vector is the list of numbers as before. The top
19594vector is an equal-sized list of ``weights'' to attach to the elements
19595of the data vector. For example, if the first data element is 4.2 and
19596the first weight is 10, then 10 will be added to bin 4 of the result
19597vector. Without the hyperbolic flag, every element has a weight of one.
19598
19599@kindex v t
19600@pindex calc-transpose
19601@tindex trn
19602The @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes
19603the transpose of the matrix at the top of the stack. If the argument
19604is a plain vector, it is treated as a row vector and transposed into
19605a one-column matrix.
19606
19607@kindex v v
19608@pindex calc-reverse-vector
19609@tindex rev
19610The @kbd{v v} (@code{calc-reverse-vector}) [@code{vec}] command reverses
19611a vector end-for-end. Given a matrix, it reverses the order of the rows.
19612(To reverse the columns instead, just use @kbd{v t v v v t}. The same
19613principle can be used to apply other vector commands to the columns of
19614a matrix.)
19615
19616@kindex v m
19617@pindex calc-mask-vector
19618@tindex vmask
19619The @kbd{v m} (@code{calc-mask-vector}) [@code{vmask}] command uses
19620one vector as a mask to extract elements of another vector. The mask
19621is in the second-to-top position; the target vector is on the top of
19622the stack. These vectors must have the same length. The result is
19623the same as the target vector, but with all elements which correspond
19624to zeros in the mask vector deleted. Thus, for example,
19625@samp{vmask([1, 0, 1, 0, 1], [a, b, c, d, e])} produces @samp{[a, c, e]}.
19626@xref{Logical Operations}.
19627
19628@kindex v e
19629@pindex calc-expand-vector
19630@tindex vexp
19631The @kbd{v e} (@code{calc-expand-vector}) [@code{vexp}] command
19632expands a vector according to another mask vector. The result is a
19633vector the same length as the mask, but with nonzero elements replaced
19634by successive elements from the target vector. The length of the target
19635vector is normally the number of nonzero elements in the mask. If the
19636target vector is longer, its last few elements are lost. If the target
19637vector is shorter, the last few nonzero mask elements are left
19638unreplaced in the result. Thus @samp{vexp([2, 0, 3, 0, 7], [a, b])}
19639produces @samp{[a, 0, b, 0, 7]}.
19640
19641@kindex H v e
19642With the Hyperbolic flag, @kbd{H v e} takes a filler value from the
19643top of the stack; the mask and target vectors come from the third and
19644second elements of the stack. This filler is used where the mask is
19645zero: @samp{vexp([2, 0, 3, 0, 7], [a, b], z)} produces
19646@samp{[a, z, c, z, 7]}. If the filler value is itself a vector,
19647then successive values are taken from it, so that the effect is to
19648interleave two vectors according to the mask:
19649@samp{vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])} produces
19650@samp{[a, x, b, 7, y, 0]}.
19651
19652Another variation on the masking idea is to combine @samp{[a, b, c, d, e]}
19653with the mask @samp{[1, 0, 1, 0, 1]} to produce @samp{[a, 0, c, 0, e]}.
19654You can accomplish this with @kbd{V M a &}, mapping the logical ``and''
19655operation across the two vectors. @xref{Logical Operations}. Note that
19656the @code{? :} operation also discussed there allows other types of
19657masking using vectors.
19658
19659@node Vector and Matrix Arithmetic, Set Operations, Manipulating Vectors, Matrix Functions
19660@section Vector and Matrix Arithmetic
19661
19662@noindent
19663Basic arithmetic operations like addition and multiplication are defined
19664for vectors and matrices as well as for numbers. Division of matrices, in
19665the sense of multiplying by the inverse, is supported. (Division by a
19666matrix actually uses LU-decomposition for greater accuracy and speed.)
19667@xref{Basic Arithmetic}.
19668
19669The following functions are applied element-wise if their arguments are
19670vectors or matrices: @code{change-sign}, @code{conj}, @code{arg},
19671@code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean},
19672@code{float}, @code{frac}. @xref{Function Index}.@refill
19673
19674@kindex V J
19675@pindex calc-conj-transpose
19676@tindex ctrn
19677The @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes
19678the conjugate transpose of its argument, i.e., @samp{conj(trn(x))}.
19679
19680@c @mindex A
19681@kindex A (vectors)
19682@pindex calc-abs (vectors)
19683@c @mindex abs
19684@tindex abs (vectors)
19685The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the
19686Frobenius norm of a vector or matrix argument. This is the square
19687root of the sum of the squares of the absolute values of the
19688elements of the vector or matrix. If the vector is interpreted as
19689a point in two- or three-dimensional space, this is the distance
19690from that point to the origin.@refill
19691
19692@kindex v n
19693@pindex calc-rnorm
19694@tindex rnorm
19695The @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes
19696the row norm, or infinity-norm, of a vector or matrix. For a plain
19697vector, this is the maximum of the absolute values of the elements.
19698For a matrix, this is the maximum of the row-absolute-value-sums,
19699i.e., of the sums of the absolute values of the elements along the
19700various rows.
19701
19702@kindex V N
19703@pindex calc-cnorm
19704@tindex cnorm
19705The @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes
19706the column norm, or one-norm, of a vector or matrix. For a plain
19707vector, this is the sum of the absolute values of the elements.
19708For a matrix, this is the maximum of the column-absolute-value-sums.
19709General @cite{k}-norms for @cite{k} other than one or infinity are
19710not provided.
19711
19712@kindex V C
19713@pindex calc-cross
19714@tindex cross
19715The @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the
19716right-handed cross product of two vectors, each of which must have
19717exactly three elements.
19718
19719@c @mindex &
19720@kindex & (matrices)
19721@pindex calc-inv (matrices)
19722@c @mindex inv
19723@tindex inv (matrices)
19724The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
19725inverse of a square matrix. If the matrix is singular, the inverse
19726operation is left in symbolic form. Matrix inverses are recorded so
19727that once an inverse (or determinant) of a particular matrix has been
19728computed, the inverse and determinant of the matrix can be recomputed
19729quickly in the future.
19730
19731If the argument to @kbd{&} is a plain number @cite{x}, this
19732command simply computes @cite{1/x}. This is okay, because the
19733@samp{/} operator also does a matrix inversion when dividing one
19734by a matrix.
19735
19736@kindex V D
19737@pindex calc-mdet
19738@tindex det
19739The @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the
19740determinant of a square matrix.
19741
19742@kindex V L
19743@pindex calc-mlud
19744@tindex lud
19745The @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the
19746LU decomposition of a matrix. The result is a list of three matrices
19747which, when multiplied together left-to-right, form the original matrix.
19748The first is a permutation matrix that arises from pivoting in the
19749algorithm, the second is lower-triangular with ones on the diagonal,
19750and the third is upper-triangular.
19751
19752@kindex V T
19753@pindex calc-mtrace
19754@tindex tr
19755The @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the
19756trace of a square matrix. This is defined as the sum of the diagonal
19757elements of the matrix.
19758
19759@node Set Operations, Statistical Operations, Vector and Matrix Arithmetic, Matrix Functions
19760@section Set Operations using Vectors
19761
19762@noindent
19763@cindex Sets, as vectors
19764Calc includes several commands which interpret vectors as @dfn{sets} of
19765objects. A set is a collection of objects; any given object can appear
19766only once in the set. Calc stores sets as vectors of objects in
19767sorted order. Objects in a Calc set can be any of the usual things,
19768such as numbers, variables, or formulas. Two set elements are considered
19769equal if they are identical, except that numerically equal numbers like
19770the integer 4 and the float 4.0 are considered equal even though they
19771are not ``identical.'' Variables are treated like plain symbols without
19772attached values by the set operations; subtracting the set @samp{[b]}
19773from @samp{[a, b]} always yields the set @samp{[a]} even though if
19774the variables @samp{a} and @samp{b} both equalled 17, you might
19775expect the answer @samp{[]}.
19776
19777If a set contains interval forms, then it is assumed to be a set of
19778real numbers. In this case, all set operations require the elements
19779of the set to be only things that are allowed in intervals: Real
19780numbers, plus and minus infinity, HMS forms, and date forms. If
19781there are variables or other non-real objects present in a real set,
19782all set operations on it will be left in unevaluated form.
19783
19784If the input to a set operation is a plain number or interval form
19785@var{a}, it is treated like the one-element vector @samp{[@var{a}]}.
19786The result is always a vector, except that if the set consists of a
19787single interval, the interval itself is returned instead.
19788
19789@xref{Logical Operations}, for the @code{in} function which tests if
19790a certain value is a member of a given set. To test if the set @cite{A}
19791is a subset of the set @cite{B}, use @samp{vdiff(A, B) = []}.
19792
19793@kindex V +
19794@pindex calc-remove-duplicates
19795@tindex rdup
19796The @kbd{V +} (@code{calc-remove-duplicates}) [@code{rdup}] command
19797converts an arbitrary vector into set notation. It works by sorting
19798the vector as if by @kbd{V S}, then removing duplicates. (For example,
19799@kbd{[a, 5, 4, a, 4.0]} is sorted to @samp{[4, 4.0, 5, a, a]} and then
19800reduced to @samp{[4, 5, a]}). Overlapping intervals are merged as
19801necessary. You rarely need to use @kbd{V +} explicitly, since all the
19802other set-based commands apply @kbd{V +} to their inputs before using
19803them.
19804
19805@kindex V V
19806@pindex calc-set-union
19807@tindex vunion
19808The @kbd{V V} (@code{calc-set-union}) [@code{vunion}] command computes
19809the union of two sets. An object is in the union of two sets if and
19810only if it is in either (or both) of the input sets. (You could
19811accomplish the same thing by concatenating the sets with @kbd{|},
19812then using @kbd{V +}.)
19813
19814@kindex V ^
19815@pindex calc-set-intersect
19816@tindex vint
19817The @kbd{V ^} (@code{calc-set-intersect}) [@code{vint}] command computes
19818the intersection of two sets. An object is in the intersection if
19819and only if it is in both of the input sets. Thus if the input
19820sets are disjoint, i.e., if they share no common elements, the result
19821will be the empty vector @samp{[]}. Note that the characters @kbd{V}
19822and @kbd{^} were chosen to be close to the conventional mathematical
19823notation for set union@c{ ($A \cup B$)}
19824@asis{} and intersection@c{ ($A \cap B$)}
19825@asis{}.
19826
19827@kindex V -
19828@pindex calc-set-difference
19829@tindex vdiff
19830The @kbd{V -} (@code{calc-set-difference}) [@code{vdiff}] command computes
19831the difference between two sets. An object is in the difference
19832@cite{A - B} if and only if it is in @cite{A} but not in @cite{B}.
19833Thus subtracting @samp{[y,z]} from a set will remove the elements
19834@samp{y} and @samp{z} if they are present. You can also think of this
19835as a general @dfn{set complement} operator; if @cite{A} is the set of
19836all possible values, then @cite{A - B} is the ``complement'' of @cite{B}.
19837Obviously this is only practical if the set of all possible values in
19838your problem is small enough to list in a Calc vector (or simple
19839enough to express in a few intervals).
19840
19841@kindex V X
19842@pindex calc-set-xor
19843@tindex vxor
19844The @kbd{V X} (@code{calc-set-xor}) [@code{vxor}] command computes
19845the ``exclusive-or,'' or ``symmetric difference'' of two sets.
19846An object is in the symmetric difference of two sets if and only
19847if it is in one, but @emph{not} both, of the sets. Objects that
19848occur in both sets ``cancel out.''
19849
19850@kindex V ~
19851@pindex calc-set-complement
19852@tindex vcompl
19853The @kbd{V ~} (@code{calc-set-complement}) [@code{vcompl}] command
19854computes the complement of a set with respect to the real numbers.
19855Thus @samp{vcompl(x)} is equivalent to @samp{vdiff([-inf .. inf], x)}.
19856For example, @samp{vcompl([2, (3 .. 4]])} evaluates to
19857@samp{[[-inf .. 2), (2 .. 3], (4 .. inf]]}.
19858
19859@kindex V F
19860@pindex calc-set-floor
19861@tindex vfloor
19862The @kbd{V F} (@code{calc-set-floor}) [@code{vfloor}] command
19863reinterprets a set as a set of integers. Any non-integer values,
19864and intervals that do not enclose any integers, are removed. Open
19865intervals are converted to equivalent closed intervals. Successive
19866integers are converted into intervals of integers. For example, the
19867complement of the set @samp{[2, 6, 7, 8]} is messy, but if you wanted
19868the complement with respect to the set of integers you could type
19869@kbd{V ~ V F} to get @samp{[[-inf .. 1], [3 .. 5], [9 .. inf]]}.
19870
19871@kindex V E
19872@pindex calc-set-enumerate
19873@tindex venum
19874The @kbd{V E} (@code{calc-set-enumerate}) [@code{venum}] command
19875converts a set of integers into an explicit vector. Intervals in
19876the set are expanded out to lists of all integers encompassed by
19877the intervals. This only works for finite sets (i.e., sets which
19878do not involve @samp{-inf} or @samp{inf}).
19879
19880@kindex V :
19881@pindex calc-set-span
19882@tindex vspan
19883The @kbd{V :} (@code{calc-set-span}) [@code{vspan}] command converts any
19884set of reals into an interval form that encompasses all its elements.
19885The lower limit will be the smallest element in the set; the upper
19886limit will be the largest element. For an empty set, @samp{vspan([])}
19887returns the empty interval @w{@samp{[0 .. 0)}}.
19888
19889@kindex V #
19890@pindex calc-set-cardinality
19891@tindex vcard
19892The @kbd{V #} (@code{calc-set-cardinality}) [@code{vcard}] command counts
19893the number of integers in a set. The result is the length of the vector
19894that would be produced by @kbd{V E}, although the computation is much
19895more efficient than actually producing that vector.
19896
19897@cindex Sets, as binary numbers
19898Another representation for sets that may be more appropriate in some
19899cases is binary numbers. If you are dealing with sets of integers
19900in the range 0 to 49, you can use a 50-bit binary number where a
19901particular bit is 1 if the corresponding element is in the set.
19902@xref{Binary Functions}, for a list of commands that operate on
19903binary numbers. Note that many of the above set operations have
19904direct equivalents in binary arithmetic: @kbd{b o} (@code{calc-or}),
19905@kbd{b a} (@code{calc-and}), @kbd{b d} (@code{calc-diff}),
19906@kbd{b x} (@code{calc-xor}), and @kbd{b n} (@code{calc-not}),
19907respectively. You can use whatever representation for sets is most
19908convenient to you.
19909
19910@kindex b p
19911@kindex b u
19912@pindex calc-pack-bits
19913@pindex calc-unpack-bits
19914@tindex vpack
19915@tindex vunpack
19916The @kbd{b u} (@code{calc-unpack-bits}) [@code{vunpack}] command
19917converts an integer that represents a set in binary into a set
19918in vector/interval notation. For example, @samp{vunpack(67)}
19919returns @samp{[[0 .. 1], 6]}. If the input is negative, the set
19920it represents is semi-infinite: @samp{vunpack(-4) = [2 .. inf)}.
19921Use @kbd{V E} afterwards to expand intervals to individual
19922values if you wish. Note that this command uses the @kbd{b}
19923(binary) prefix key.
19924
19925The @kbd{b p} (@code{calc-pack-bits}) [@code{vpack}] command
19926converts the other way, from a vector or interval representing
19927a set of nonnegative integers into a binary integer describing
19928the same set. The set may include positive infinity, but must
19929not include any negative numbers. The input is interpreted as a
19930set of integers in the sense of @kbd{V F} (@code{vfloor}). Beware
19931that a simple input like @samp{[100]} can result in a huge integer
19932representation (@c{$2^{100}$}
19933@cite{2^100}, a 31-digit integer, in this case).
19934
19935@node Statistical Operations, Reducing and Mapping, Set Operations, Matrix Functions
19936@section Statistical Operations on Vectors
19937
19938@noindent
19939@cindex Statistical functions
19940The commands in this section take vectors as arguments and compute
19941various statistical measures on the data stored in the vectors. The
19942references used in the definitions of these functions are Bevington's
19943@emph{Data Reduction and Error Analysis for the Physical Sciences},
19944and @emph{Numerical Recipes} by Press, Flannery, Teukolsky and
19945Vetterling.
19946
19947The statistical commands use the @kbd{u} prefix key followed by
19948a shifted letter or other character.
19949
19950@xref{Manipulating Vectors}, for a description of @kbd{V H}
19951(@code{calc-histogram}).
19952
19953@xref{Curve Fitting}, for the @kbd{a F} command for doing
19954least-squares fits to statistical data.
19955
19956@xref{Probability Distribution Functions}, for several common
19957probability distribution functions.
19958
19959@menu
19960* Single-Variable Statistics::
19961* Paired-Sample Statistics::
19962@end menu
19963
19964@node Single-Variable Statistics, Paired-Sample Statistics, Statistical Operations, Statistical Operations
19965@subsection Single-Variable Statistics
19966
19967@noindent
19968These functions do various statistical computations on single
19969vectors. Given a numeric prefix argument, they actually pop
19970@var{n} objects from the stack and combine them into a data
19971vector. Each object may be either a number or a vector; if a
19972vector, any sub-vectors inside it are ``flattened'' as if by
19973@kbd{v a 0}; @pxref{Manipulating Vectors}. By default one object
19974is popped, which (in order to be useful) is usually a vector.
19975
19976If an argument is a variable name, and the value stored in that
19977variable is a vector, then the stored vector is used. This method
19978has the advantage that if your data vector is large, you can avoid
19979the slow process of manipulating it directly on the stack.
19980
19981These functions are left in symbolic form if any of their arguments
19982are not numbers or vectors, e.g., if an argument is a formula, or
19983a non-vector variable. However, formulas embedded within vector
19984arguments are accepted; the result is a symbolic representation
19985of the computation, based on the assumption that the formula does
19986not itself represent a vector. All varieties of numbers such as
19987error forms and interval forms are acceptable.
19988
19989Some of the functions in this section also accept a single error form
19990or interval as an argument. They then describe a property of the
19991normal or uniform (respectively) statistical distribution described
19992by the argument. The arguments are interpreted in the same way as
19993the @var{M} argument of the random number function @kbd{k r}. In
19994particular, an interval with integer limits is considered an integer
19995distribution, so that @samp{[2 .. 6)} is the same as @samp{[2 .. 5]}.
19996An interval with at least one floating-point limit is a continuous
19997distribution: @samp{[2.0 .. 6.0)} is @emph{not} the same as
19998@samp{[2.0 .. 5.0]}!
19999
20000@kindex u #
20001@pindex calc-vector-count
20002@tindex vcount
20003The @kbd{u #} (@code{calc-vector-count}) [@code{vcount}] command
20004computes the number of data values represented by the inputs.
20005For example, @samp{vcount(1, [2, 3], [[4, 5], [], x, y])} returns 7.
20006If the argument is a single vector with no sub-vectors, this
20007simply computes the length of the vector.
20008
20009@kindex u +
20010@kindex u *
20011@pindex calc-vector-sum
20012@pindex calc-vector-prod
20013@tindex vsum
20014@tindex vprod
20015@cindex Summations (statistical)
20016The @kbd{u +} (@code{calc-vector-sum}) [@code{vsum}] command
20017computes the sum of the data values. The @kbd{u *}
20018(@code{calc-vector-prod}) [@code{vprod}] command computes the
20019product of the data values. If the input is a single flat vector,
20020these are the same as @kbd{V R +} and @kbd{V R *}
20021(@pxref{Reducing and Mapping}).@refill
20022
20023@kindex u X
20024@kindex u N
20025@pindex calc-vector-max
20026@pindex calc-vector-min
20027@tindex vmax
20028@tindex vmin
20029The @kbd{u X} (@code{calc-vector-max}) [@code{vmax}] command
20030computes the maximum of the data values, and the @kbd{u N}
20031(@code{calc-vector-min}) [@code{vmin}] command computes the minimum.
20032If the argument is an interval, this finds the minimum or maximum
20033value in the interval. (Note that @samp{vmax([2..6)) = 5} as
20034described above.) If the argument is an error form, this returns
20035plus or minus infinity.
20036
20037@kindex u M
20038@pindex calc-vector-mean
20039@tindex vmean
20040@cindex Mean of data values
20041The @kbd{u M} (@code{calc-vector-mean}) [@code{vmean}] command
20042computes the average (arithmetic mean) of the data values.
20043If the inputs are error forms @c{$x$ @code{+/-} $\sigma$}
20044@samp{x +/- s}, this is the weighted
20045mean of the @cite{x} values with weights @c{$1 / \sigma^2$}
20046@cite{1 / s^2}.
20047@tex
20048\turnoffactive
20049$$ \mu = { \displaystyle \sum { x_i \over \sigma_i^2 } \over
20050 \displaystyle \sum { 1 \over \sigma_i^2 } } $$
20051@end tex
20052If the inputs are not error forms, this is simply the sum of the
20053values divided by the count of the values.@refill
20054
20055Note that a plain number can be considered an error form with
20056error @c{$\sigma = 0$}
20057@cite{s = 0}. If the input to @kbd{u M} is a mixture of
20058plain numbers and error forms, the result is the mean of the
20059plain numbers, ignoring all values with non-zero errors. (By the
20060above definitions it's clear that a plain number effectively
20061has an infinite weight, next to which an error form with a finite
20062weight is completely negligible.)
20063
20064This function also works for distributions (error forms or
20065intervals). The mean of an error form `@i{a} @t{+/-} @i{b}' is simply
20066@cite{a}. The mean of an interval is the mean of the minimum
20067and maximum values of the interval.
20068
20069@kindex I u M
20070@pindex calc-vector-mean-error
20071@tindex vmeane
20072The @kbd{I u M} (@code{calc-vector-mean-error}) [@code{vmeane}]
20073command computes the mean of the data points expressed as an
20074error form. This includes the estimated error associated with
20075the mean. If the inputs are error forms, the error is the square
20076root of the reciprocal of the sum of the reciprocals of the squares
20077of the input errors. (I.e., the variance is the reciprocal of the
20078sum of the reciprocals of the variances.)
20079@tex
20080\turnoffactive
20081$$ \sigma_\mu^2 = {1 \over \displaystyle \sum {1 \over \sigma_i^2}} $$
20082@end tex
20083If the inputs are plain
20084numbers, the error is equal to the standard deviation of the values
20085divided by the square root of the number of values. (This works
20086out to be equivalent to calculating the standard deviation and
20087then assuming each value's error is equal to this standard
20088deviation.)@refill
20089@tex
20090\turnoffactive
20091$$ \sigma_\mu^2 = {\sigma^2 \over N} $$
20092@end tex
20093
20094@kindex H u M
20095@pindex calc-vector-median
20096@tindex vmedian
20097@cindex Median of data values
20098The @kbd{H u M} (@code{calc-vector-median}) [@code{vmedian}]
20099command computes the median of the data values. The values are
20100first sorted into numerical order; the median is the middle
20101value after sorting. (If the number of data values is even,
20102the median is taken to be the average of the two middle values.)
20103The median function is different from the other functions in
20104this section in that the arguments must all be real numbers;
20105variables are not accepted even when nested inside vectors.
20106(Otherwise it is not possible to sort the data values.) If
20107any of the input values are error forms, their error parts are
20108ignored.
20109
20110The median function also accepts distributions. For both normal
20111(error form) and uniform (interval) distributions, the median is
20112the same as the mean.
20113
20114@kindex H I u M
20115@pindex calc-vector-harmonic-mean
20116@tindex vhmean
20117@cindex Harmonic mean
20118The @kbd{H I u M} (@code{calc-vector-harmonic-mean}) [@code{vhmean}]
20119command computes the harmonic mean of the data values. This is
20120defined as the reciprocal of the arithmetic mean of the reciprocals
20121of the values.
20122@tex
20123\turnoffactive
20124$$ { N \over \displaystyle \sum {1 \over x_i} } $$
20125@end tex
20126
20127@kindex u G
20128@pindex calc-vector-geometric-mean
20129@tindex vgmean
20130@cindex Geometric mean
20131The @kbd{u G} (@code{calc-vector-geometric-mean}) [@code{vgmean}]
20132command computes the geometric mean of the data values. This
20133is the @i{N}th root of the product of the values. This is also
20134equal to the @code{exp} of the arithmetic mean of the logarithms
20135of the data values.
20136@tex
20137\turnoffactive
20138$$ \exp \left ( \sum { \ln x_i } \right ) =
20139 \left ( \prod { x_i } \right)^{1 / N} $$
20140@end tex
20141
20142@kindex H u G
20143@tindex agmean
20144The @kbd{H u G} [@code{agmean}] command computes the ``arithmetic-geometric
20145mean'' of two numbers taken from the stack. This is computed by
20146replacing the two numbers with their arithmetic mean and geometric
20147mean, then repeating until the two values converge.
20148@tex
20149\turnoffactive
20150$$ a_{i+1} = { a_i + b_i \over 2 } , \qquad b_{i+1} = \sqrt{a_i b_i} $$
20151@end tex
20152
20153@cindex Root-mean-square
20154Another commonly used mean, the RMS (root-mean-square), can be computed
20155for a vector of numbers simply by using the @kbd{A} command.
20156
20157@kindex u S
20158@pindex calc-vector-sdev
20159@tindex vsdev
20160@cindex Standard deviation
20161@cindex Sample statistics
20162The @kbd{u S} (@code{calc-vector-sdev}) [@code{vsdev}] command
20163computes the standard deviation@c{ $\sigma$}
20164@asis{} of the data values. If the
20165values are error forms, the errors are used as weights just
20166as for @kbd{u M}. This is the @emph{sample} standard deviation,
20167whose value is the square root of the sum of the squares of the
20168differences between the values and the mean of the @cite{N} values,
20169divided by @cite{N-1}.
20170@tex
20171\turnoffactive
20172$$ \sigma^2 = {1 \over N - 1} \sum (x_i - \mu)^2 $$
20173@end tex
20174
20175This function also applies to distributions. The standard deviation
20176of a single error form is simply the error part. The standard deviation
20177of a continuous interval happens to equal the difference between the
20178limits, divided by @c{$\sqrt{12}$}
20179@cite{sqrt(12)}. The standard deviation of an
20180integer interval is the same as the standard deviation of a vector
20181of those integers.
20182
20183@kindex I u S
20184@pindex calc-vector-pop-sdev
20185@tindex vpsdev
20186@cindex Population statistics
20187The @kbd{I u S} (@code{calc-vector-pop-sdev}) [@code{vpsdev}]
20188command computes the @emph{population} standard deviation.
20189It is defined by the same formula as above but dividing
20190by @cite{N} instead of by @cite{N-1}. The population standard
20191deviation is used when the input represents the entire set of
20192data values in the distribution; the sample standard deviation
20193is used when the input represents a sample of the set of all
20194data values, so that the mean computed from the input is itself
20195only an estimate of the true mean.
20196@tex
20197\turnoffactive
20198$$ \sigma^2 = {1 \over N} \sum (x_i - \mu)^2 $$
20199@end tex
20200
20201For error forms and continuous intervals, @code{vpsdev} works
20202exactly like @code{vsdev}. For integer intervals, it computes the
20203population standard deviation of the equivalent vector of integers.
20204
20205@kindex H u S
20206@kindex H I u S
20207@pindex calc-vector-variance
20208@pindex calc-vector-pop-variance
20209@tindex vvar
20210@tindex vpvar
20211@cindex Variance of data values
20212The @kbd{H u S} (@code{calc-vector-variance}) [@code{vvar}] and
20213@kbd{H I u S} (@code{calc-vector-pop-variance}) [@code{vpvar}]
20214commands compute the variance of the data values. The variance
20215is the square@c{ $\sigma^2$}
20216@asis{} of the standard deviation, i.e., the sum of the
20217squares of the deviations of the data values from the mean.
20218(This definition also applies when the argument is a distribution.)
20219
20220@c @starindex
20221@tindex vflat
20222The @code{vflat} algebraic function returns a vector of its
20223arguments, interpreted in the same way as the other functions
20224in this section. For example, @samp{vflat(1, [2, [3, 4]], 5)}
20225returns @samp{[1, 2, 3, 4, 5]}.
20226
20227@node Paired-Sample Statistics, , Single-Variable Statistics, Statistical Operations
20228@subsection Paired-Sample Statistics
20229
20230@noindent
20231The functions in this section take two arguments, which must be
20232vectors of equal size. The vectors are each flattened in the same
20233way as by the single-variable statistical functions. Given a numeric
20234prefix argument of 1, these functions instead take one object from
20235the stack, which must be an @c{$N\times2$}
20236@asis{Nx2} matrix of data values. Once
20237again, variable names can be used in place of actual vectors and
20238matrices.
20239
20240@kindex u C
20241@pindex calc-vector-covariance
20242@tindex vcov
20243@cindex Covariance
20244The @kbd{u C} (@code{calc-vector-covariance}) [@code{vcov}] command
20245computes the sample covariance of two vectors. The covariance
20246of vectors @var{x} and @var{y} is the sum of the products of the
20247differences between the elements of @var{x} and the mean of @var{x}
20248times the differences between the corresponding elements of @var{y}
20249and the mean of @var{y}, all divided by @cite{N-1}. Note that
20250the variance of a vector is just the covariance of the vector
20251with itself. Once again, if the inputs are error forms the
20252errors are used as weight factors. If both @var{x} and @var{y}
20253are composed of error forms, the error for a given data point
20254is taken as the square root of the sum of the squares of the two
20255input errors.
20256@tex
20257\turnoffactive
20258$$ \sigma_{x\!y}^2 = {1 \over N-1} \sum (x_i - \mu_x) (y_i - \mu_y) $$
20259$$ \sigma_{x\!y}^2 =
20260 {\displaystyle {1 \over N-1}
20261 \sum {(x_i - \mu_x) (y_i - \mu_y) \over \sigma_i^2}
20262 \over \displaystyle {1 \over N} \sum {1 \over \sigma_i^2}}
20263$$
20264@end tex
20265
20266@kindex I u C
20267@pindex calc-vector-pop-covariance
20268@tindex vpcov
20269The @kbd{I u C} (@code{calc-vector-pop-covariance}) [@code{vpcov}]
20270command computes the population covariance, which is the same as the
20271sample covariance computed by @kbd{u C} except dividing by @cite{N}
20272instead of @cite{N-1}.
20273
20274@kindex H u C
20275@pindex calc-vector-correlation
20276@tindex vcorr
20277@cindex Correlation coefficient
20278@cindex Linear correlation
20279The @kbd{H u C} (@code{calc-vector-correlation}) [@code{vcorr}]
20280command computes the linear correlation coefficient of two vectors.
20281This is defined by the covariance of the vectors divided by the
20282product of their standard deviations. (There is no difference
20283between sample or population statistics here.)
20284@tex
20285\turnoffactive
20286$$ r_{x\!y} = { \sigma_{x\!y}^2 \over \sigma_x^2 \sigma_y^2 } $$
20287@end tex
20288
20289@node Reducing and Mapping, Vector and Matrix Formats, Statistical Operations, Matrix Functions
20290@section Reducing and Mapping Vectors
20291
20292@noindent
20293The commands in this section allow for more general operations on the
20294elements of vectors.
20295
20296@kindex V A
20297@pindex calc-apply
20298@tindex apply
20299The simplest of these operations is @kbd{V A} (@code{calc-apply})
20300[@code{apply}], which applies a given operator to the elements of a vector.
20301For example, applying the hypothetical function @code{f} to the vector
20302@w{@samp{[1, 2, 3]}} would produce the function call @samp{f(1, 2, 3)}.
20303Applying the @code{+} function to the vector @samp{[a, b]} gives
20304@samp{a + b}. Applying @code{+} to the vector @samp{[a, b, c]} is an
20305error, since the @code{+} function expects exactly two arguments.
20306
20307While @kbd{V A} is useful in some cases, you will usually find that either
20308@kbd{V R} or @kbd{V M}, described below, is closer to what you want.
20309
20310@menu
20311* Specifying Operators::
20312* Mapping::
20313* Reducing::
20314* Nesting and Fixed Points::
20315* Generalized Products::
20316@end menu
20317
20318@node Specifying Operators, Mapping, Reducing and Mapping, Reducing and Mapping
20319@subsection Specifying Operators
20320
20321@noindent
20322Commands in this section (like @kbd{V A}) prompt you to press the key
20323corresponding to the desired operator. Press @kbd{?} for a partial
20324list of the available operators. Generally, an operator is any key or
20325sequence of keys that would normally take one or more arguments from
20326the stack and replace them with a result. For example, @kbd{V A H C}
20327uses the hyperbolic cosine operator, @code{cosh}. (Since @code{cosh}
20328expects one argument, @kbd{V A H C} requires a vector with a single
20329element as its argument.)
20330
20331You can press @kbd{x} at the operator prompt to select any algebraic
20332function by name to use as the operator. This includes functions you
20333have defined yourself using the @kbd{Z F} command. (@xref{Algebraic
20334Definitions}.) If you give a name for which no function has been
20335defined, the result is left in symbolic form, as in @samp{f(1, 2, 3)}.
20336Calc will prompt for the number of arguments the function takes if it
20337can't figure it out on its own (say, because you named a function that
20338is currently undefined). It is also possible to type a digit key before
20339the function name to specify the number of arguments, e.g.,
20340@kbd{V M 3 x f RET} calls @code{f} with three arguments even if it
20341looks like it ought to have only two. This technique may be necessary
20342if the function allows a variable number of arguments. For example,
20343the @kbd{v e} [@code{vexp}] function accepts two or three arguments;
20344if you want to map with the three-argument version, you will have to
20345type @kbd{V M 3 v e}.
20346
20347It is also possible to apply any formula to a vector by treating that
20348formula as a function. When prompted for the operator to use, press
20349@kbd{'} (the apostrophe) and type your formula as an algebraic entry.
20350You will then be prompted for the argument list, which defaults to a
20351list of all variables that appear in the formula, sorted into alphabetic
20352order. For example, suppose you enter the formula @w{@samp{x + 2y^x}}.
20353The default argument list would be @samp{(x y)}, which means that if
20354this function is applied to the arguments @samp{[3, 10]} the result will
20355be @samp{3 + 2*10^3}. (If you plan to use a certain formula in this
20356way often, you might consider defining it as a function with @kbd{Z F}.)
20357
20358Another way to specify the arguments to the formula you enter is with
20359@kbd{$}, @kbd{$$}, and so on. For example, @kbd{V A ' $$ + 2$^$$}
20360has the same effect as the previous example. The argument list is
20361automatically taken to be @samp{($$ $)}. (The order of the arguments
20362may seem backwards, but it is analogous to the way normal algebraic
20363entry interacts with the stack.)
20364
20365If you press @kbd{$} at the operator prompt, the effect is similar to
20366the apostrophe except that the relevant formula is taken from top-of-stack
20367instead. The actual vector arguments of the @kbd{V A $} or related command
20368then start at the second-to-top stack position. You will still be
20369prompted for an argument list.
20370
20371@cindex Nameless functions
20372@cindex Generic functions
20373A function can be written without a name using the notation @samp{<#1 - #2>},
20374which means ``a function of two arguments that computes the first
20375argument minus the second argument.'' The symbols @samp{#1} and @samp{#2}
20376are placeholders for the arguments. You can use any names for these
20377placeholders if you wish, by including an argument list followed by a
20378colon: @samp{<x, y : x - y>}. When you type @kbd{V A ' $$ + 2$^$$ RET},
20379Calc builds the nameless function @samp{<#1 + 2 #2^#1>} as the function
20380to map across the vectors. When you type @kbd{V A ' x + 2y^x RET RET},
20381Calc builds the nameless function @w{@samp{<x, y : x + 2 y^x>}}. In both
20382cases, Calc also writes the nameless function to the Trail so that you
20383can get it back later if you wish.
20384
20385If there is only one argument, you can write @samp{#} in place of @samp{#1}.
20386(Note that @samp{< >} notation is also used for date forms. Calc tells
20387that @samp{<@var{stuff}>} is a nameless function by the presence of
20388@samp{#} signs inside @var{stuff}, or by the fact that @var{stuff}
20389begins with a list of variables followed by a colon.)
20390
20391You can type a nameless function directly to @kbd{V A '}, or put one on
20392the stack and use it with @w{@kbd{V A $}}. Calc will not prompt for an
20393argument list in this case, since the nameless function specifies the
20394argument list as well as the function itself. In @kbd{V A '}, you can
20395omit the @samp{< >} marks if you use @samp{#} notation for the arguments,
20396so that @kbd{V A ' #1+#2 RET} is the same as @kbd{V A ' <#1+#2> RET},
20397which in turn is the same as @kbd{V A ' $$+$ RET}.
20398
20399@cindex Lambda expressions
20400@c @starindex
20401@tindex lambda
20402The internal format for @samp{<x, y : x + y>} is @samp{lambda(x, y, x + y)}.
20403(The word @code{lambda} derives from Lisp notation and the theory of
20404functions.) The internal format for @samp{<#1 + #2>} is @samp{lambda(ArgA,
20405ArgB, ArgA + ArgB)}. Note that there is no actual Calc function called
20406@code{lambda}; the whole point is that the @code{lambda} expression is
20407used in its symbolic form, not evaluated for an answer until it is applied
20408to specific arguments by a command like @kbd{V A} or @kbd{V M}.
20409
20410(Actually, @code{lambda} does have one special property: Its arguments
20411are never evaluated; for example, putting @samp{<(2/3) #>} on the stack
20412will not simplify the @samp{2/3} until the nameless function is actually
20413called.)
20414
20415@tindex add
20416@tindex sub
20417@c @mindex @idots
20418@tindex mul
20419@c @mindex @null
20420@tindex div
20421@c @mindex @null
20422@tindex pow
20423@c @mindex @null
20424@tindex neg
20425@c @mindex @null
20426@tindex mod
20427@c @mindex @null
20428@tindex vconcat
20429As usual, commands like @kbd{V A} have algebraic function name equivalents.
20430For example, @kbd{V A k g} with an argument of @samp{v} is equivalent to
20431@samp{apply(gcd, v)}. The first argument specifies the operator name,
20432and is either a variable whose name is the same as the function name,
20433or a nameless function like @samp{<#^3+1>}. Operators that are normally
20434written as algebraic symbols have the names @code{add}, @code{sub},
20435@code{mul}, @code{div}, @code{pow}, @code{neg}, @code{mod}, and
20436@code{vconcat}.@refill
20437
20438@c @starindex
20439@tindex call
20440The @code{call} function builds a function call out of several arguments:
20441@samp{call(gcd, x, y)} is the same as @samp{apply(gcd, [x, y])}, which
20442in turn is the same as @samp{gcd(x, y)}. The first argument of @code{call},
20443like the other functions described here, may be either a variable naming a
20444function, or a nameless function (@samp{call(<#1+2#2>, x, y)} is the same
20445as @samp{x + 2y}).
20446
20447(Experts will notice that it's not quite proper to use a variable to name
20448a function, since the name @code{gcd} corresponds to the Lisp variable
20449@code{var-gcd} but to the Lisp function @code{calcFunc-gcd}. Calc
20450automatically makes this translation, so you don't have to worry
20451about it.)
20452
20453@node Mapping, Reducing, Specifying Operators, Reducing and Mapping
20454@subsection Mapping
20455
20456@noindent
20457@kindex V M
20458@pindex calc-map
20459@tindex map
20460The @kbd{V M} (@code{calc-map}) [@code{map}] command applies a given
20461operator elementwise to one or more vectors. For example, mapping
20462@code{A} [@code{abs}] produces a vector of the absolute values of the
20463elements in the input vector. Mapping @code{+} pops two vectors from
20464the stack, which must be of equal length, and produces a vector of the
20465pairwise sums of the elements. If either argument is a non-vector, it
20466is duplicated for each element of the other vector. For example,
20467@kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector.
20468With the 2 listed first, it would have computed a vector of powers of
20469two. Mapping a user-defined function pops as many arguments from the
20470stack as the function requires. If you give an undefined name, you will
20471be prompted for the number of arguments to use.@refill
20472
20473If any argument to @kbd{V M} is a matrix, the operator is normally mapped
20474across all elements of the matrix. For example, given the matrix
20475@cite{[[1, -2, 3], [-4, 5, -6]]}, @kbd{V M A} takes six absolute values to
20476produce another @c{$3\times2$}
20477@asis{3x2} matrix, @cite{[[1, 2, 3], [4, 5, 6]]}.
20478
20479@tindex mapr
20480The command @kbd{V M _} [@code{mapr}] (i.e., type an underscore at the
20481operator prompt) maps by rows instead. For example, @kbd{V M _ A} views
20482the above matrix as a vector of two 3-element row vectors. It produces
20483a new vector which contains the absolute values of those row vectors,
20484namely @cite{[3.74, 8.77]}. (Recall, the absolute value of a vector is
20485defined as the square root of the sum of the squares of the elements.)
20486Some operators accept vectors and return new vectors; for example,
20487@kbd{v v} reverses a vector, so @kbd{V M _ v v} would reverse each row
20488of the matrix to get a new matrix, @cite{[[3, -2, 1], [-6, 5, -4]]}.
20489
20490Sometimes a vector of vectors (representing, say, strings, sets, or lists)
20491happens to look like a matrix. If so, remember to use @kbd{V M _} if you
20492want to map a function across the whole strings or sets rather than across
20493their individual elements.
20494
20495@tindex mapc
20496The command @kbd{V M :} [@code{mapc}] maps by columns. Basically, it
20497transposes the input matrix, maps by rows, and then, if the result is a
20498matrix, transposes again. For example, @kbd{V M : A} takes the absolute
20499values of the three columns of the matrix, treating each as a 2-vector,
20500and @kbd{V M : v v} reverses the columns to get the matrix
20501@cite{[[-4, 5, -6], [1, -2, 3]]}.
20502
20503(The symbols @kbd{_} and @kbd{:} were chosen because they had row-like
20504and column-like appearances, and were not already taken by useful
20505operators. Also, they appear shifted on most keyboards so they are easy
20506to type after @kbd{V M}.)
20507
20508The @kbd{_} and @kbd{:} modifiers have no effect on arguments that are
20509not matrices (so if none of the arguments are matrices, they have no
20510effect at all). If some of the arguments are matrices and others are
20511plain numbers, the plain numbers are held constant for all rows of the
20512matrix (so that @kbd{2 V M _ ^} squares every row of a matrix; squaring
20513a vector takes a dot product of the vector with itself).
20514
20515If some of the arguments are vectors with the same lengths as the
20516rows (for @kbd{V M _}) or columns (for @kbd{V M :}) of the matrix
20517arguments, those vectors are also held constant for every row or
20518column.
20519
20520Sometimes it is useful to specify another mapping command as the operator
20521to use with @kbd{V M}. For example, @kbd{V M _ V A +} applies @kbd{V A +}
20522to each row of the input matrix, which in turn adds the two values on that
20523row. If you give another vector-operator command as the operator for
20524@kbd{V M}, it automatically uses map-by-rows mode if you don't specify
20525otherwise; thus @kbd{V M V A +} is equivalent to @kbd{V M _ V A +}. (If
20526you really want to map-by-elements another mapping command, you can use
20527a triple-nested mapping command: @kbd{V M V M V A +} means to map
20528@kbd{V M V A +} over the rows of the matrix; in turn, @kbd{V A +} is
20529mapped over the elements of each row.)
20530
20531@tindex mapa
20532@tindex mapd
20533Previous versions of Calc had ``map across'' and ``map down'' modes
20534that are now considered obsolete; the old ``map across'' is now simply
20535@kbd{V M V A}, and ``map down'' is now @kbd{V M : V A}. The algebraic
20536functions @code{mapa} and @code{mapd} are still supported, though.
20537Note also that, while the old mapping modes were persistent (once you
20538set the mode, it would apply to later mapping commands until you reset
20539it), the new @kbd{:} and @kbd{_} modifiers apply only to the current
20540mapping command. The default @kbd{V M} always means map-by-elements.
20541
20542@xref{Algebraic Manipulation}, for the @kbd{a M} command, which is like
20543@kbd{V M} but for equations and inequalities instead of vectors.
20544@xref{Storing Variables}, for the @kbd{s m} command which modifies a
20545variable's stored value using a @kbd{V M}-like operator.
20546
20547@node Reducing, Nesting and Fixed Points, Mapping, Reducing and Mapping
20548@subsection Reducing
20549
20550@noindent
20551@kindex V R
20552@pindex calc-reduce
20553@tindex reduce
20554The @kbd{V R} (@code{calc-reduce}) [@code{reduce}] command applies a given
20555binary operator across all the elements of a vector. A binary operator is
20556a function such as @code{+} or @code{max} which takes two arguments. For
20557example, reducing @code{+} over a vector computes the sum of the elements
20558of the vector. Reducing @code{-} computes the first element minus each of
20559the remaining elements. Reducing @code{max} computes the maximum element
20560and so on. In general, reducing @code{f} over the vector @samp{[a, b, c, d]}
20561produces @samp{f(f(f(a, b), c), d)}.
20562
20563@kindex I V R
20564@tindex rreduce
20565The @kbd{I V R} [@code{rreduce}] command is similar to @kbd{V R} except
20566that works from right to left through the vector. For example, plain
20567@kbd{V R -} on the vector @samp{[a, b, c, d]} produces @samp{a - b - c - d}
20568but @kbd{I V R -} on the same vector produces @samp{a - (b - (c - d))},
20569or @samp{a - b + c - d}. This ``alternating sum'' occurs frequently
20570in power series expansions.
20571
20572@kindex V U
20573@tindex accum
20574The @kbd{V U} (@code{calc-accumulate}) [@code{accum}] command does an
20575accumulation operation. Here Calc does the corresponding reduction
20576operation, but instead of producing only the final result, it produces
20577a vector of all the intermediate results. Accumulating @code{+} over
20578the vector @samp{[a, b, c, d]} produces the vector
20579@samp{[a, a + b, a + b + c, a + b + c + d]}.
20580
20581@kindex I V U
20582@tindex raccum
20583The @kbd{I V U} [@code{raccum}] command does a right-to-left accumulation.
20584For example, @kbd{I V U -} on the vector @samp{[a, b, c, d]} produces the
20585vector @samp{[a - b + c - d, b - c + d, c - d, d]}.
20586
20587@tindex reducea
20588@tindex rreducea
20589@tindex reduced
20590@tindex rreduced
20591As for @kbd{V M}, @kbd{V R} normally reduces a matrix elementwise. For
20592example, given the matrix @cite{[[a, b, c], [d, e, f]]}, @kbd{V R +} will
20593compute @cite{a + b + c + d + e + f}. You can type @kbd{V R _} or
20594@kbd{V R :} to modify this behavior. The @kbd{V R _} [@code{reducea}]
20595command reduces ``across'' the matrix; it reduces each row of the matrix
20596as a vector, then collects the results. Thus @kbd{V R _ +} of this
20597matrix would produce @cite{[a + b + c, d + e + f]}. Similarly, @kbd{V R :}
20598[@code{reduced}] reduces down; @kbd{V R : +} would produce @cite{[a + d,
20599b + e, c + f]}.
20600
20601@tindex reducer
20602@tindex rreducer
20603There is a third ``by rows'' mode for reduction that is occasionally
20604useful; @kbd{V R =} [@code{reducer}] simply reduces the operator over
20605the rows of the matrix themselves. Thus @kbd{V R = +} on the above
20606matrix would get the same result as @kbd{V R : +}, since adding two
20607row vectors is equivalent to adding their elements. But @kbd{V R = *}
20608would multiply the two rows (to get a single number, their dot product),
20609while @kbd{V R : *} would produce a vector of the products of the columns.
20610
20611These three matrix reduction modes work with @kbd{V R} and @kbd{I V R},
20612but they are not currently supported with @kbd{V U} or @kbd{I V U}.
20613
20614@tindex reducec
20615@tindex rreducec
20616The obsolete reduce-by-columns function, @code{reducec}, is still
20617supported but there is no way to get it through the @kbd{V R} command.
20618
20619The commands @kbd{M-# :} and @kbd{M-# _} are equivalent to typing
20620@kbd{M-# r} to grab a rectangle of data into Calc, and then typing
20621@kbd{V R : +} or @kbd{V R _ +}, respectively, to sum the columns or
20622rows of the matrix. @xref{Grabbing From Buffers}.
20623
20624@node Nesting and Fixed Points, Generalized Products, Reducing, Reducing and Mapping
20625@subsection Nesting and Fixed Points
20626
20627@noindent
20628@kindex H V R
20629@tindex nest
20630The @kbd{H V R} [@code{nest}] command applies a function to a given
20631argument repeatedly. It takes two values, @samp{a} and @samp{n}, from
20632the stack, where @samp{n} must be an integer. It then applies the
20633function nested @samp{n} times; if the function is @samp{f} and @samp{n}
20634is 3, the result is @samp{f(f(f(a)))}. The number @samp{n} may be
20635negative if Calc knows an inverse for the function @samp{f}; for
20636example, @samp{nest(sin, a, -2)} returns @samp{arcsin(arcsin(a))}.
20637
20638@kindex H V U
20639@tindex anest
20640The @kbd{H V U} [@code{anest}] command is an accumulating version of
20641@code{nest}: It returns a vector of @samp{n+1} values, e.g.,
20642@samp{[a, f(a), f(f(a)), f(f(f(a)))]}. If @samp{n} is negative and
20643@samp{F} is the inverse of @samp{f}, then the result is of the
20644form @samp{[a, F(a), F(F(a)), F(F(F(a)))]}.
20645
20646@kindex H I V R
20647@tindex fixp
20648@cindex Fixed points
20649The @kbd{H I V R} [@code{fixp}] command is like @kbd{H V R}, except
20650that it takes only an @samp{a} value from the stack; the function is
20651applied until it reaches a ``fixed point,'' i.e., until the result
20652no longer changes.
20653
20654@kindex H I V U
20655@tindex afixp
20656The @kbd{H I V U} [@code{afixp}] command is an accumulating @code{fixp}.
20657The first element of the return vector will be the initial value @samp{a};
20658the last element will be the final result that would have been returned
20659by @code{fixp}.
20660
20661For example, 0.739085 is a fixed point of the cosine function (in radians):
20662@samp{cos(0.739085) = 0.739085}. You can find this value by putting, say,
206631.0 on the stack and typing @kbd{H I V U C}. (We use the accumulating
20664version so we can see the intermediate results: @samp{[1, 0.540302, 0.857553,
206650.65329, ...]}. With a precision of six, this command will take 36 steps
20666to converge to 0.739085.)
20667
20668Newton's method for finding roots is a classic example of iteration
20669to a fixed point. To find the square root of five starting with an
20670initial guess, Newton's method would look for a fixed point of the
20671function @samp{(x + 5/x) / 2}. Putting a guess of 1 on the stack
20672and typing @kbd{H I V R ' ($ + 5/$)/2 RET} quickly yields the result
206732.23607. This is equivalent to using the @kbd{a R} (@code{calc-find-root})
20674command to find a root of the equation @samp{x^2 = 5}.
20675
20676These examples used numbers for @samp{a} values. Calc keeps applying
20677the function until two successive results are equal to within the
20678current precision. For complex numbers, both the real parts and the
20679imaginary parts must be equal to within the current precision. If
20680@samp{a} is a formula (say, a variable name), then the function is
20681applied until two successive results are exactly the same formula.
20682It is up to you to ensure that the function will eventually converge;
20683if it doesn't, you may have to press @kbd{C-g} to stop the Calculator.
20684
20685The algebraic @code{fixp} function takes two optional arguments, @samp{n}
20686and @samp{tol}. The first is the maximum number of steps to be allowed,
20687and must be either an integer or the symbol @samp{inf} (infinity, the
20688default). The second is a convergence tolerance. If a tolerance is
20689specified, all results during the calculation must be numbers, not
20690formulas, and the iteration stops when the magnitude of the difference
20691between two successive results is less than or equal to the tolerance.
20692(This implies that a tolerance of zero iterates until the results are
20693exactly equal.)
20694
20695Putting it all together, @samp{fixp(<(# + A/#)/2>, B, 20, 1e-10)}
20696computes the square root of @samp{A} given the initial guess @samp{B},
20697stopping when the result is correct within the specified tolerance, or
20698when 20 steps have been taken, whichever is sooner.
20699
20700@node Generalized Products, , Nesting and Fixed Points, Reducing and Mapping
20701@subsection Generalized Products
20702
20703@kindex V O
20704@pindex calc-outer-product
20705@tindex outer
20706The @kbd{V O} (@code{calc-outer-product}) [@code{outer}] command applies
20707a given binary operator to all possible pairs of elements from two
20708vectors, to produce a matrix. For example, @kbd{V O *} with @samp{[a, b]}
20709and @samp{[x, y, z]} on the stack produces a multiplication table:
20710@samp{[[a x, a y, a z], [b x, b y, b z]]}. Element @var{r},@var{c} of
20711the result matrix is obtained by applying the operator to element @var{r}
20712of the lefthand vector and element @var{c} of the righthand vector.
20713
20714@kindex V I
20715@pindex calc-inner-product
20716@tindex inner
20717The @kbd{V I} (@code{calc-inner-product}) [@code{inner}] command computes
20718the generalized inner product of two vectors or matrices, given a
20719``multiplicative'' operator and an ``additive'' operator. These can each
20720actually be any binary operators; if they are @samp{*} and @samp{+},
20721respectively, the result is a standard matrix multiplication. Element
20722@var{r},@var{c} of the result matrix is obtained by mapping the
20723multiplicative operator across row @var{r} of the lefthand matrix and
20724column @var{c} of the righthand matrix, and then reducing with the additive
20725operator. Just as for the standard @kbd{*} command, this can also do a
20726vector-matrix or matrix-vector inner product, or a vector-vector
20727generalized dot product.
20728
20729Since @kbd{V I} requires two operators, it prompts twice. In each case,
20730you can use any of the usual methods for entering the operator. If you
20731use @kbd{$} twice to take both operator formulas from the stack, the
20732first (multiplicative) operator is taken from the top of the stack
20733and the second (additive) operator is taken from second-to-top.
20734
20735@node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions
20736@section Vector and Matrix Display Formats
20737
20738@noindent
20739Commands for controlling vector and matrix display use the @kbd{v} prefix
20740instead of the usual @kbd{d} prefix. But they are display modes; in
20741particular, they are influenced by the @kbd{I} and @kbd{H} prefix keys
20742in the same way (@pxref{Display Modes}). Matrix display is also
20743influenced by the @kbd{d O} (@code{calc-flat-language}) mode;
20744@pxref{Normal Language Modes}.
20745
20746@kindex V <
20747@pindex calc-matrix-left-justify
20748@kindex V =
20749@pindex calc-matrix-center-justify
20750@kindex V >
20751@pindex calc-matrix-right-justify
20752The commands @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >}
20753(@code{calc-matrix-right-justify}), and @w{@kbd{v =}}
20754(@code{calc-matrix-center-justify}) control whether matrix elements
20755are justified to the left, right, or center of their columns.@refill
20756
20757@kindex V [
20758@pindex calc-vector-brackets
20759@kindex V @{
20760@pindex calc-vector-braces
20761@kindex V (
20762@pindex calc-vector-parens
20763The @kbd{v [} (@code{calc-vector-brackets}) command turns the square
20764brackets that surround vectors and matrices displayed in the stack on
20765and off. The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (}
20766(@code{calc-vector-parens}) commands use curly braces or parentheses,
20767respectively, instead of square brackets. For example, @kbd{v @{} might
20768be used in preparation for yanking a matrix into a buffer running
20769Mathematica. (In fact, the Mathematica language mode uses this mode;
20770@pxref{Mathematica Language Mode}.) Note that, regardless of the
20771display mode, either brackets or braces may be used to enter vectors,
20772and parentheses may never be used for this purpose.@refill
20773
20774@kindex V ]
20775@pindex calc-matrix-brackets
20776The @kbd{v ]} (@code{calc-matrix-brackets}) command controls the
20777``big'' style display of matrices. It prompts for a string of code
20778letters; currently implemented letters are @code{R}, which enables
20779brackets on each row of the matrix; @code{O}, which enables outer
20780brackets in opposite corners of the matrix; and @code{C}, which
20781enables commas or semicolons at the ends of all rows but the last.
20782The default format is @samp{RO}. (Before Calc 2.00, the format
20783was fixed at @samp{ROC}.) Here are some example matrices:
20784
20785@group
20786@example
20787[ [ 123, 0, 0 ] [ [ 123, 0, 0 ],
20788 [ 0, 123, 0 ] [ 0, 123, 0 ],
20789 [ 0, 0, 123 ] ] [ 0, 0, 123 ] ]
20790
20791 RO ROC
20792
20793@end example
20794@end group
20795@noindent
20796@group
20797@example
20798 [ 123, 0, 0 [ 123, 0, 0 ;
20799 0, 123, 0 0, 123, 0 ;
20800 0, 0, 123 ] 0, 0, 123 ]
20801
20802 O OC
20803
20804@end example
20805@end group
20806@noindent
20807@group
20808@example
20809 [ 123, 0, 0 ] 123, 0, 0
20810 [ 0, 123, 0 ] 0, 123, 0
20811 [ 0, 0, 123 ] 0, 0, 123
20812
20813 R @r{blank}
20814@end example
20815@end group
20816
20817@noindent
20818Note that of the formats shown here, @samp{RO}, @samp{ROC}, and
20819@samp{OC} are all recognized as matrices during reading, while
20820the others are useful for display only.
20821
20822@kindex V ,
20823@pindex calc-vector-commas
20824The @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and
20825off in vector and matrix display.@refill
20826
20827In vectors of length one, and in all vectors when commas have been
20828turned off, Calc adds extra parentheses around formulas that might
20829otherwise be ambiguous. For example, @samp{[a b]} could be a vector
20830of the one formula @samp{a b}, or it could be a vector of two
20831variables with commas turned off. Calc will display the former
20832case as @samp{[(a b)]}. You can disable these extra parentheses
20833(to make the output less cluttered at the expense of allowing some
20834ambiguity) by adding the letter @code{P} to the control string you
20835give to @kbd{v ]} (as described above).
20836
20837@kindex V .
20838@pindex calc-full-vectors
20839The @kbd{v .} (@code{calc-full-vectors}) command turns abbreviated
20840display of long vectors on and off. In this mode, vectors of six
20841or more elements, or matrices of six or more rows or columns, will
20842be displayed in an abbreviated form that displays only the first
20843three elements and the last element: @samp{[a, b, c, ..., z]}.
20844When very large vectors are involved this will substantially
20845improve Calc's display speed.
20846
20847@kindex t .
20848@pindex calc-full-trail-vectors
20849The @kbd{t .} (@code{calc-full-trail-vectors}) command controls a
20850similar mode for recording vectors in the Trail. If you turn on
20851this mode, vectors of six or more elements and matrices of six or
20852more rows or columns will be abbreviated when they are put in the
20853Trail. The @kbd{t y} (@code{calc-trail-yank}) command will be
20854unable to recover those vectors. If you are working with very
20855large vectors, this mode will improve the speed of all operations
20856that involve the trail.
20857
20858@kindex V /
20859@pindex calc-break-vectors
20860The @kbd{v /} (@code{calc-break-vectors}) command turns multi-line
20861vector display on and off. Normally, matrices are displayed with one
20862row per line but all other types of vectors are displayed in a single
20863line. This mode causes all vectors, whether matrices or not, to be
20864displayed with a single element per line. Sub-vectors within the
20865vectors will still use the normal linear form.
20866
20867@node Algebra, Units, Matrix Functions, Top
20868@chapter Algebra
20869
20870@noindent
20871This section covers the Calc features that help you work with
20872algebraic formulas. First, the general sub-formula selection
20873mechanism is described; this works in conjunction with any Calc
20874commands. Then, commands for specific algebraic operations are
20875described. Finally, the flexible @dfn{rewrite rule} mechanism
20876is discussed.
20877
20878The algebraic commands use the @kbd{a} key prefix; selection
20879commands use the @kbd{j} (for ``just a letter that wasn't used
20880for anything else'') prefix.
20881
20882@xref{Editing Stack Entries}, to see how to manipulate formulas
20883using regular Emacs editing commands.@refill
20884
20885When doing algebraic work, you may find several of the Calculator's
20886modes to be helpful, including algebraic-simplification mode (@kbd{m A})
20887or no-simplification mode (@kbd{m O}),
20888algebraic-entry mode (@kbd{m a}), fraction mode (@kbd{m f}), and
20889symbolic mode (@kbd{m s}). @xref{Mode Settings}, for discussions
20890of these modes. You may also wish to select ``big'' display mode (@kbd{d B}).
20891@xref{Normal Language Modes}.@refill
20892
20893@menu
20894* Selecting Subformulas::
20895* Algebraic Manipulation::
20896* Simplifying Formulas::
20897* Polynomials::
20898* Calculus::
20899* Solving Equations::
20900* Numerical Solutions::
20901* Curve Fitting::
20902* Summations::
20903* Logical Operations::
20904* Rewrite Rules::
20905@end menu
20906
20907@node Selecting Subformulas, Algebraic Manipulation, Algebra, Algebra
20908@section Selecting Sub-Formulas
20909
20910@noindent
20911@cindex Selections
20912@cindex Sub-formulas
20913@cindex Parts of formulas
20914When working with an algebraic formula it is often necessary to
20915manipulate a portion of the formula rather than the formula as a
20916whole. Calc allows you to ``select'' a portion of any formula on
20917the stack. Commands which would normally operate on that stack
20918entry will now operate only on the sub-formula, leaving the
20919surrounding part of the stack entry alone.
20920
20921One common non-algebraic use for selection involves vectors. To work
20922on one element of a vector in-place, simply select that element as a
20923``sub-formula'' of the vector.
20924
20925@menu
20926* Making Selections::
20927* Changing Selections::
20928* Displaying Selections::
20929* Operating on Selections::
20930* Rearranging with Selections::
20931@end menu
20932
20933@node Making Selections, Changing Selections, Selecting Subformulas, Selecting Subformulas
20934@subsection Making Selections
20935
20936@noindent
20937@kindex j s
20938@pindex calc-select-here
20939To select a sub-formula, move the Emacs cursor to any character in that
20940sub-formula, and press @w{@kbd{j s}} (@code{calc-select-here}). Calc will
20941highlight the smallest portion of the formula that contains that
20942character. By default the sub-formula is highlighted by blanking out
20943all of the rest of the formula with dots. Selection works in any
20944display mode but is perhaps easiest in ``big'' (@kbd{d B}) mode.
20945Suppose you enter the following formula:
20946
20947@group
20948@smallexample
20949 3 ___
20950 (a + b) + V c
209511: ---------------
20952 2 x + 1
20953@end smallexample
20954@end group
20955
20956@noindent
20957(by typing @kbd{' ((a+b)^3 + sqrt(c)) / (2x+1)}). If you move the
20958cursor to the letter @samp{b} and press @w{@kbd{j s}}, the display changes
20959to
20960
20961@group
20962@smallexample
20963 . ...
20964 .. . b. . . .
209651* ...............
20966 . . . .
20967@end smallexample
20968@end group
20969
20970@noindent
20971Every character not part of the sub-formula @samp{b} has been changed
20972to a dot. The @samp{*} next to the line number is to remind you that
20973the formula has a portion of it selected. (In this case, it's very
20974obvious, but it might not always be. If Embedded Mode is enabled,
20975the word @samp{Sel} also appears in the mode line because the stack
20976may not be visible. @pxref{Embedded Mode}.)
20977
20978If you had instead placed the cursor on the parenthesis immediately to
20979the right of the @samp{b}, the selection would have been:
20980
20981@group
20982@smallexample
20983 . ...
20984 (a + b) . . .
209851* ...............
20986 . . . .
20987@end smallexample
20988@end group
20989
20990@noindent
20991The portion selected is always large enough to be considered a complete
20992formula all by itself, so selecting the parenthesis selects the whole
20993formula that it encloses. Putting the cursor on the the @samp{+} sign
20994would have had the same effect.
20995
20996(Strictly speaking, the Emacs cursor is really the manifestation of
20997the Emacs ``point,'' which is a position @emph{between} two characters
20998in the buffer. So purists would say that Calc selects the smallest
20999sub-formula which contains the character to the right of ``point.'')
21000
21001If you supply a numeric prefix argument @var{n}, the selection is
21002expanded to the @var{n}th enclosing sub-formula. Thus, positioning
21003the cursor on the @samp{b} and typing @kbd{C-u 1 j s} will select
21004@samp{a + b}; typing @kbd{C-u 2 j s} will select @samp{(a + b)^3},
21005and so on.
21006
21007If the cursor is not on any part of the formula, or if you give a
21008numeric prefix that is too large, the entire formula is selected.
21009
21010If the cursor is on the @samp{.} line that marks the top of the stack
21011(i.e., its normal ``rest position''), this command selects the entire
21012formula at stack level 1. Most selection commands similarly operate
21013on the formula at the top of the stack if you haven't positioned the
21014cursor on any stack entry.
21015
21016@kindex j a
21017@pindex calc-select-additional
21018The @kbd{j a} (@code{calc-select-additional}) command enlarges the
21019current selection to encompass the cursor. To select the smallest
21020sub-formula defined by two different points, move to the first and
21021press @kbd{j s}, then move to the other and press @kbd{j a}. This
21022is roughly analogous to using @kbd{C-@@} (@code{set-mark-command}) to
21023select the two ends of a region of text during normal Emacs editing.
21024
21025@kindex j o
21026@pindex calc-select-once
21027The @kbd{j o} (@code{calc-select-once}) command selects a formula in
21028exactly the same way as @kbd{j s}, except that the selection will
21029last only as long as the next command that uses it. For example,
21030@kbd{j o 1 +} is a handy way to add one to the sub-formula indicated
21031by the cursor.
21032
21033(A somewhat more precise definition: The @kbd{j o} command sets a flag
21034such that the next command involving selected stack entries will clear
21035the selections on those stack entries afterwards. All other selection
21036commands except @kbd{j a} and @kbd{j O} clear this flag.)
21037
21038@kindex j S
21039@kindex j O
21040@pindex calc-select-here-maybe
21041@pindex calc-select-once-maybe
21042The @kbd{j S} (@code{calc-select-here-maybe}) and @kbd{j O}
21043(@code{calc-select-once-maybe}) commands are equivalent to @kbd{j s}
21044and @kbd{j o}, respectively, except that if the formula already
21045has a selection they have no effect. This is analogous to the
21046behavior of some commands such as @kbd{j r} (@code{calc-rewrite-selection};
21047@pxref{Selections with Rewrite Rules}) and is mainly intended to be
21048used in keyboard macros that implement your own selection-oriented
21049commands.@refill
21050
21051Selection of sub-formulas normally treats associative terms like
21052@samp{a + b - c + d} and @samp{x * y * z} as single levels of the formula.
21053If you place the cursor anywhere inside @samp{a + b - c + d} except
21054on one of the variable names and use @kbd{j s}, you will select the
21055entire four-term sum.
21056
21057@kindex j b
21058@pindex calc-break-selections
21059The @kbd{j b} (@code{calc-break-selections}) command controls a mode
21060in which the ``deep structure'' of these associative formulas shows
21061through. Calc actually stores the above formulas as @samp{((a + b) - c) + d}
21062and @samp{x * (y * z)}. (Note that for certain obscure reasons, Calc
21063treats multiplication as right-associative.) Once you have enabled
21064@kbd{j b} mode, selecting with the cursor on the @samp{-} sign would
21065only select the @samp{a + b - c} portion, which makes sense when the
21066deep structure of the sum is considered. There is no way to select
21067the @samp{b - c + d} portion; although this might initially look
21068like just as legitimate a sub-formula as @samp{a + b - c}, the deep
21069structure shows that it isn't. The @kbd{d U} command can be used
21070to view the deep structure of any formula (@pxref{Normal Language Modes}).
21071
21072When @kbd{j b} mode has not been enabled, the deep structure is
21073generally hidden by the selection commands---what you see is what
21074you get.
21075
21076@kindex j u
21077@pindex calc-unselect
21078The @kbd{j u} (@code{calc-unselect}) command unselects the formula
21079that the cursor is on. If there was no selection in the formula,
21080this command has no effect. With a numeric prefix argument, it
21081unselects the @var{n}th stack element rather than using the cursor
21082position.
21083
21084@kindex j c
21085@pindex calc-clear-selections
21086The @kbd{j c} (@code{calc-clear-selections}) command unselects all
21087stack elements.
21088
21089@node Changing Selections, Displaying Selections, Making Selections, Selecting Subformulas
21090@subsection Changing Selections
21091
21092@noindent
21093@kindex j m
21094@pindex calc-select-more
21095Once you have selected a sub-formula, you can expand it using the
21096@w{@kbd{j m}} (@code{calc-select-more}) command. If @samp{a + b} is
21097selected, pressing @w{@kbd{j m}} repeatedly works as follows:
21098
21099@group
21100@smallexample
21101 3 ... 3 ___ 3 ___
21102 (a + b) . . . (a + b) + V c (a + b) + V c
211031* ............... 1* ............... 1* ---------------
21104 . . . . . . . . 2 x + 1
21105@end smallexample
21106@end group
21107
21108@noindent
21109In the last example, the entire formula is selected. This is roughly
21110the same as having no selection at all, but because there are subtle
21111differences the @samp{*} character is still there on the line number.
21112
21113With a numeric prefix argument @var{n}, @kbd{j m} expands @var{n}
21114times (or until the entire formula is selected). Note that @kbd{j s}
21115with argument @var{n} is equivalent to plain @kbd{j s} followed by
21116@kbd{j m} with argument @var{n}. If @w{@kbd{j m}} is used when there
21117is no current selection, it is equivalent to @w{@kbd{j s}}.
21118
21119Even though @kbd{j m} does not explicitly use the location of the
21120cursor within the formula, it nevertheless uses the cursor to determine
21121which stack element to operate on. As usual, @kbd{j m} when the cursor
21122is not on any stack element operates on the top stack element.
21123
21124@kindex j l
21125@pindex calc-select-less
21126The @kbd{j l} (@code{calc-select-less}) command reduces the current
21127selection around the cursor position. That is, it selects the
21128immediate sub-formula of the current selection which contains the
21129cursor, the opposite of @kbd{j m}. If the cursor is not inside the
21130current selection, the command de-selects the formula.
21131
21132@kindex j 1-9
21133@pindex calc-select-part
21134The @kbd{j 1} through @kbd{j 9} (@code{calc-select-part}) commands
21135select the @var{n}th sub-formula of the current selection. They are
21136like @kbd{j l} (@code{calc-select-less}) except they use counting
21137rather than the cursor position to decide which sub-formula to select.
21138For example, if the current selection is @kbd{a + b + c} or
21139@kbd{f(a, b, c)} or @kbd{[a, b, c]}, then @kbd{j 1} selects @samp{a},
21140@kbd{j 2} selects @samp{b}, and @kbd{j 3} selects @samp{c}; in each of
21141these cases, @kbd{j 4} through @kbd{j 9} would be errors.
21142
21143If there is no current selection, @kbd{j 1} through @kbd{j 9} select
21144the @var{n}th top-level sub-formula. (In other words, they act as if
21145the entire stack entry were selected first.) To select the @var{n}th
21146sub-formula where @var{n} is greater than nine, you must instead invoke
21147@w{@kbd{j 1}} with @var{n} as a numeric prefix argument.@refill
21148
21149@kindex j n
21150@kindex j p
21151@pindex calc-select-next
21152@pindex calc-select-previous
21153The @kbd{j n} (@code{calc-select-next}) and @kbd{j p}
21154(@code{calc-select-previous}) commands change the current selection
21155to the next or previous sub-formula at the same level. For example,
21156if @samp{b} is selected in @w{@samp{2 + a*b*c + x}}, then @kbd{j n}
21157selects @samp{c}. Further @kbd{j n} commands would be in error because,
21158even though there is something to the right of @samp{c} (namely, @samp{x}),
21159it is not at the same level; in this case, it is not a term of the
21160same product as @samp{b} and @samp{c}. However, @kbd{j m} (to select
21161the whole product @samp{a*b*c} as a term of the sum) followed by
21162@w{@kbd{j n}} would successfully select the @samp{x}.
21163
21164Similarly, @kbd{j p} moves the selection from the @samp{b} in this
21165sample formula to the @samp{a}. Both commands accept numeric prefix
21166arguments to move several steps at a time.
21167
21168It is interesting to compare Calc's selection commands with the
21169Emacs Info system's commands for navigating through hierarchically
21170organized documentation. Calc's @kbd{j n} command is completely
21171analogous to Info's @kbd{n} command. Likewise, @kbd{j p} maps to
21172@kbd{p}, @kbd{j 2} maps to @kbd{2}, and Info's @kbd{u} is like @kbd{j m}.
21173(Note that @kbd{j u} stands for @code{calc-unselect}, not ``up''.)
21174The Info @kbd{m} command is somewhat similar to Calc's @kbd{j s} and
21175@kbd{j l}; in each case, you can jump directly to a sub-component
21176of the hierarchy simply by pointing to it with the cursor.
21177
21178@node Displaying Selections, Operating on Selections, Changing Selections, Selecting Subformulas
21179@subsection Displaying Selections
21180
21181@noindent
21182@kindex j d
21183@pindex calc-show-selections
21184The @kbd{j d} (@code{calc-show-selections}) command controls how
21185selected sub-formulas are displayed. One of the alternatives is
21186illustrated in the above examples; if we press @kbd{j d} we switch
21187to the other style in which the selected portion itself is obscured
21188by @samp{#} signs:
21189
21190@group
21191@smallexample
21192 3 ... # ___
21193 (a + b) . . . ## # ## + V c
211941* ............... 1* ---------------
21195 . . . . 2 x + 1
21196@end smallexample
21197@end group
21198
21199@node Operating on Selections, Rearranging with Selections, Displaying Selections, Selecting Subformulas
21200@subsection Operating on Selections
21201
21202@noindent
21203Once a selection is made, all Calc commands that manipulate items
21204on the stack will operate on the selected portions of the items
21205instead. (Note that several stack elements may have selections
21206at once, though there can be only one selection at a time in any
21207given stack element.)
21208
21209@kindex j e
21210@pindex calc-enable-selections
21211The @kbd{j e} (@code{calc-enable-selections}) command disables the
21212effect that selections have on Calc commands. The current selections
21213still exist, but Calc commands operate on whole stack elements anyway.
21214This mode can be identified by the fact that the @samp{*} markers on
21215the line numbers are gone, even though selections are visible. To
21216reactivate the selections, press @kbd{j e} again.
21217
21218To extract a sub-formula as a new formula, simply select the
21219sub-formula and press @key{RET}. This normally duplicates the top
21220stack element; here it duplicates only the selected portion of that
21221element.
21222
21223To replace a sub-formula with something different, you can enter the
21224new value onto the stack and press @key{TAB}. This normally exchanges
21225the top two stack elements; here it swaps the value you entered into
21226the selected portion of the formula, returning the old selected
21227portion to the top of the stack.
21228
21229@group
21230@smallexample
21231 3 ... ... ___
21232 (a + b) . . . 17 x y . . . 17 x y + V c
212332* ............... 2* ............. 2: -------------
21234 . . . . . . . . 2 x + 1
21235
21236 3 3
212371: 17 x y 1: (a + b) 1: (a + b)
21238@end smallexample
21239@end group
21240
21241In this example we select a sub-formula of our original example,
21242enter a new formula, @key{TAB} it into place, then deselect to see
21243the complete, edited formula.
21244
21245If you want to swap whole formulas around even though they contain
21246selections, just use @kbd{j e} before and after.
21247
21248@kindex j '
21249@pindex calc-enter-selection
21250The @kbd{j '} (@code{calc-enter-selection}) command is another way
21251to replace a selected sub-formula. This command does an algebraic
21252entry just like the regular @kbd{'} key. When you press @key{RET},
21253the formula you type replaces the original selection. You can use
21254the @samp{$} symbol in the formula to refer to the original
21255selection. If there is no selection in the formula under the cursor,
21256the cursor is used to make a temporary selection for the purposes of
21257the command. Thus, to change a term of a formula, all you have to
21258do is move the Emacs cursor to that term and press @kbd{j '}.
21259
21260@kindex j `
21261@pindex calc-edit-selection
21262The @kbd{j `} (@code{calc-edit-selection}) command is a similar
21263analogue of the @kbd{`} (@code{calc-edit}) command. It edits the
21264selected sub-formula in a separate buffer. If there is no
21265selection, it edits the sub-formula indicated by the cursor.
21266
21267To delete a sub-formula, press @key{DEL}. This generally replaces
21268the sub-formula with the constant zero, but in a few suitable contexts
21269it uses the constant one instead. The @key{DEL} key automatically
21270deselects and re-simplifies the entire formula afterwards. Thus:
21271
21272@group
21273@smallexample
21274 ###
21275 17 x y + # # 17 x y 17 # y 17 y
212761* ------------- 1: ------- 1* ------- 1: -------
21277 2 x + 1 2 x + 1 2 x + 1 2 x + 1
21278@end smallexample
21279@end group
21280
21281In this example, we first delete the @samp{sqrt(c)} term; Calc
21282accomplishes this by replacing @samp{sqrt(c)} with zero and
21283resimplifying. We then delete the @kbd{x} in the numerator;
21284since this is part of a product, Calc replaces it with @samp{1}
21285and resimplifies.
21286
21287If you select an element of a vector and press @key{DEL}, that
21288element is deleted from the vector. If you delete one side of
21289an equation or inequality, only the opposite side remains.
21290
21291@kindex j DEL
21292@pindex calc-del-selection
21293The @kbd{j @key{DEL}} (@code{calc-del-selection}) command is like
21294@key{DEL} but with the auto-selecting behavior of @kbd{j '} and
21295@kbd{j `}. It deletes the selected portion of the formula
21296indicated by the cursor, or, in the absence of a selection, it
21297deletes the sub-formula indicated by the cursor position.
21298
21299@kindex j RET
21300@pindex calc-grab-selection
21301(There is also an auto-selecting @kbd{j @key{RET}} (@code{calc-copy-selection})
21302command.)
21303
21304Normal arithmetic operations also apply to sub-formulas. Here we
21305select the denominator, press @kbd{5 -} to subtract five from the
21306denominator, press @kbd{n} to negate the denominator, then
21307press @kbd{Q} to take the square root.
21308
21309@group
21310@smallexample
21311 .. . .. . .. . .. .
213121* ....... 1* ....... 1* ....... 1* ..........
21313 2 x + 1 2 x - 4 4 - 2 x _________
21314 V 4 - 2 x
21315@end smallexample
21316@end group
21317
21318Certain types of operations on selections are not allowed. For
21319example, for an arithmetic function like @kbd{-} no more than one of
21320the arguments may be a selected sub-formula. (As the above example
21321shows, the result of the subtraction is spliced back into the argument
21322which had the selection; if there were more than one selection involved,
21323this would not be well-defined.) If you try to subtract two selections,
21324the command will abort with an error message.
21325
21326Operations on sub-formulas sometimes leave the formula as a whole
21327in an ``un-natural'' state. Consider negating the @samp{2 x} term
21328of our sample formula by selecting it and pressing @kbd{n}
21329(@code{calc-change-sign}).@refill
21330
21331@group
21332@smallexample
21333 .. . .. .
213341* .......... 1* ...........
21335 ......... ..........
21336 . . . 2 x . . . -2 x
21337@end smallexample
21338@end group
21339
21340Unselecting the sub-formula reveals that the minus sign, which would
21341normally have cancelled out with the subtraction automatically, has
21342not been able to do so because the subtraction was not part of the
21343selected portion. Pressing @kbd{=} (@code{calc-evaluate}) or doing
21344any other mathematical operation on the whole formula will cause it
21345to be simplified.
21346
21347@group
21348@smallexample
21349 17 y 17 y
213501: ----------- 1: ----------
21351 __________ _________
21352 V 4 - -2 x V 4 + 2 x
21353@end smallexample
21354@end group
21355
21356@node Rearranging with Selections, , Operating on Selections, Selecting Subformulas
21357@subsection Rearranging Formulas using Selections
21358
21359@noindent
21360@kindex j R
21361@pindex calc-commute-right
21362The @kbd{j R} (@code{calc-commute-right}) command moves the selected
21363sub-formula to the right in its surrounding formula. Generally the
21364selection is one term of a sum or product; the sum or product is
21365rearranged according to the commutative laws of algebra.
21366
21367As with @kbd{j '} and @kbd{j DEL}, the term under the cursor is used
21368if there is no selection in the current formula. All commands described
21369in this section share this property. In this example, we place the
21370cursor on the @samp{a} and type @kbd{j R}, then repeat.
21371
21372@smallexample
213731: a + b - c 1: b + a - c 1: b - c + a
21374@end smallexample
21375
21376@noindent
21377Note that in the final step above, the @samp{a} is switched with
21378the @samp{c} but the signs are adjusted accordingly. When moving
21379terms of sums and products, @kbd{j R} will never change the
21380mathematical meaning of the formula.
21381
21382The selected term may also be an element of a vector or an argument
21383of a function. The term is exchanged with the one to its right.
21384In this case, the ``meaning'' of the vector or function may of
21385course be drastically changed.
21386
21387@smallexample
213881: [a, b, c] 1: [b, a, c] 1: [b, c, a]
21389
213901: f(a, b, c) 1: f(b, a, c) 1: f(b, c, a)
21391@end smallexample
21392
21393@kindex j L
21394@pindex calc-commute-left
21395The @kbd{j L} (@code{calc-commute-left}) command is like @kbd{j R}
21396except that it swaps the selected term with the one to its left.
21397
21398With numeric prefix arguments, these commands move the selected
21399term several steps at a time. It is an error to try to move a
21400term left or right past the end of its enclosing formula.
21401With numeric prefix arguments of zero, these commands move the
21402selected term as far as possible in the given direction.
21403
21404@kindex j D
21405@pindex calc-sel-distribute
21406The @kbd{j D} (@code{calc-sel-distribute}) command mixes the selected
21407sum or product into the surrounding formula using the distributive
21408law. For example, in @samp{a * (b - c)} with the @samp{b - c}
21409selected, the result is @samp{a b - a c}. This also distributes
21410products or quotients into surrounding powers, and can also do
21411transformations like @samp{exp(a + b)} to @samp{exp(a) exp(b)},
21412where @samp{a + b} is the selected term, and @samp{ln(a ^ b)}
21413to @samp{ln(a) b}, where @samp{a ^ b} is the selected term.
21414
21415For multiple-term sums or products, @kbd{j D} takes off one term
21416at a time: @samp{a * (b + c - d)} goes to @samp{a * (c - d) + a b}
21417with the @samp{c - d} selected so that you can type @kbd{j D}
21418repeatedly to expand completely. The @kbd{j D} command allows a
21419numeric prefix argument which specifies the maximum number of
21420times to expand at once; the default is one time only.
21421
21422@vindex DistribRules
21423The @kbd{j D} command is implemented using rewrite rules.
21424@xref{Selections with Rewrite Rules}. The rules are stored in
21425the Calc variable @code{DistribRules}. A convenient way to view
21426these rules is to use @kbd{s e} (@code{calc-edit-variable}) which
21427displays and edits the stored value of a variable. Press @key{M-# M-#}
21428to return from editing mode; be careful not to make any actual changes
21429or else you will affect the behavior of future @kbd{j D} commands!
21430
21431To extend @kbd{j D} to handle new cases, just edit @code{DistribRules}
21432as described above. You can then use the @kbd{s p} command to save
21433this variable's value permanently for future Calc sessions.
21434@xref{Operations on Variables}.
21435
21436@kindex j M
21437@pindex calc-sel-merge
21438@vindex MergeRules
21439The @kbd{j M} (@code{calc-sel-merge}) command is the complement
21440of @kbd{j D}; given @samp{a b - a c} with either @samp{a b} or
21441@samp{a c} selected, the result is @samp{a * (b - c)}. Once
21442again, @kbd{j M} can also merge calls to functions like @code{exp}
21443and @code{ln}; examine the variable @code{MergeRules} to see all
21444the relevant rules.
21445
21446@kindex j C
21447@pindex calc-sel-commute
21448@vindex CommuteRules
21449The @kbd{j C} (@code{calc-sel-commute}) command swaps the arguments
21450of the selected sum, product, or equation. It always behaves as
21451if @kbd{j b} mode were in effect, i.e., the sum @samp{a + b + c} is
21452treated as the nested sums @samp{(a + b) + c} by this command.
21453If you put the cursor on the first @samp{+}, the result is
21454@samp{(b + a) + c}; if you put the cursor on the second @samp{+}, the
21455result is @samp{c + (a + b)} (which the default simplifications
21456will rearrange to @samp{(c + a) + b}). The relevant rules are stored
21457in the variable @code{CommuteRules}.
21458
21459You may need to turn default simplifications off (with the @kbd{m O}
21460command) in order to get the full benefit of @kbd{j C}. For example,
21461commuting @samp{a - b} produces @samp{-b + a}, but the default
21462simplifications will ``simplify'' this right back to @samp{a - b} if
21463you don't turn them off. The same is true of some of the other
21464manipulations described in this section.
21465
21466@kindex j N
21467@pindex calc-sel-negate
21468@vindex NegateRules
21469The @kbd{j N} (@code{calc-sel-negate}) command replaces the selected
21470term with the negative of that term, then adjusts the surrounding
21471formula in order to preserve the meaning. For example, given
21472@samp{exp(a - b)} where @samp{a - b} is selected, the result is
21473@samp{1 / exp(b - a)}. By contrast, selecting a term and using the
21474regular @kbd{n} (@code{calc-change-sign}) command negates the
21475term without adjusting the surroundings, thus changing the meaning
21476of the formula as a whole. The rules variable is @code{NegateRules}.
21477
21478@kindex j &
21479@pindex calc-sel-invert
21480@vindex InvertRules
21481The @kbd{j &} (@code{calc-sel-invert}) command is similar to @kbd{j N}
21482except it takes the reciprocal of the selected term. For example,
21483given @samp{a - ln(b)} with @samp{b} selected, the result is
21484@samp{a + ln(1/b)}. The rules variable is @code{InvertRules}.
21485
21486@kindex j E
21487@pindex calc-sel-jump-equals
21488@vindex JumpRules
21489The @kbd{j E} (@code{calc-sel-jump-equals}) command moves the
21490selected term from one side of an equation to the other. Given
21491@samp{a + b = c + d} with @samp{c} selected, the result is
21492@samp{a + b - c = d}. This command also works if the selected
21493term is part of a @samp{*}, @samp{/}, or @samp{^} formula. The
21494relevant rules variable is @code{JumpRules}.
21495
21496@kindex j I
21497@kindex H j I
21498@pindex calc-sel-isolate
21499The @kbd{j I} (@code{calc-sel-isolate}) command isolates the
21500selected term on its side of an equation. It uses the @kbd{a S}
21501(@code{calc-solve-for}) command to solve the equation, and the
21502Hyperbolic flag affects it in the same way. @xref{Solving Equations}.
21503When it applies, @kbd{j I} is often easier to use than @kbd{j E}.
21504It understands more rules of algebra, and works for inequalities
21505as well as equations.
21506
21507@kindex j *
21508@kindex j /
21509@pindex calc-sel-mult-both-sides
21510@pindex calc-sel-div-both-sides
21511The @kbd{j *} (@code{calc-sel-mult-both-sides}) command prompts for a
21512formula using algebraic entry, then multiplies both sides of the
21513selected quotient or equation by that formula. It simplifies each
21514side with @kbd{a s} (@code{calc-simplify}) before re-forming the
21515quotient or equation. You can suppress this simplification by
21516providing any numeric prefix argument. There is also a @kbd{j /}
21517(@code{calc-sel-div-both-sides}) which is similar to @kbd{j *} but
21518dividing instead of multiplying by the factor you enter.
21519
21520As a special feature, if the numerator of the quotient is 1, then
21521the denominator is expanded at the top level using the distributive
21522law (i.e., using the @kbd{C-u -1 a x} command). Suppose the
21523formula on the stack is @samp{1 / (sqrt(a) + 1)}, and you wish
21524to eliminate the square root in the denominator by multiplying both
21525sides by @samp{sqrt(a) - 1}. Calc's default simplifications would
21526change the result @samp{(sqrt(a) - 1) / (sqrt(a) - 1) (sqrt(a) + 1)}
21527right back to the original form by cancellation; Calc expands the
21528denominator to @samp{sqrt(a) (sqrt(a) - 1) + sqrt(a) - 1} to prevent
21529this. (You would now want to use an @kbd{a x} command to expand
21530the rest of the way, whereupon the denominator would cancel out to
21531the desired form, @samp{a - 1}.) When the numerator is not 1, this
21532initial expansion is not necessary because Calc's default
21533simplifications will not notice the potential cancellation.
21534
21535If the selection is an inequality, @kbd{j *} and @kbd{j /} will
21536accept any factor, but will warn unless they can prove the factor
21537is either positive or negative. (In the latter case the direction
21538of the inequality will be switched appropriately.) @xref{Declarations},
21539for ways to inform Calc that a given variable is positive or
21540negative. If Calc can't tell for sure what the sign of the factor
21541will be, it will assume it is positive and display a warning
21542message.
21543
21544For selections that are not quotients, equations, or inequalities,
21545these commands pull out a multiplicative factor: They divide (or
21546multiply) by the entered formula, simplify, then multiply (or divide)
21547back by the formula.
21548
21549@kindex j +
21550@kindex j -
21551@pindex calc-sel-add-both-sides
21552@pindex calc-sel-sub-both-sides
21553The @kbd{j +} (@code{calc-sel-add-both-sides}) and @kbd{j -}
21554(@code{calc-sel-sub-both-sides}) commands analogously add to or
21555subtract from both sides of an equation or inequality. For other
21556types of selections, they extract an additive factor. A numeric
21557prefix argument suppresses simplification of the intermediate
21558results.
21559
21560@kindex j U
21561@pindex calc-sel-unpack
21562The @kbd{j U} (@code{calc-sel-unpack}) command replaces the
21563selected function call with its argument. For example, given
21564@samp{a + sin(x^2)} with @samp{sin(x^2)} selected, the result
21565is @samp{a + x^2}. (The @samp{x^2} will remain selected; if you
21566wanted to change the @code{sin} to @code{cos}, just press @kbd{C}
21567now to take the cosine of the selected part.)
21568
21569@kindex j v
21570@pindex calc-sel-evaluate
21571The @kbd{j v} (@code{calc-sel-evaluate}) command performs the
21572normal default simplifications on the selected sub-formula.
21573These are the simplifications that are normally done automatically
21574on all results, but which may have been partially inhibited by
21575previous selection-related operations, or turned off altogether
21576by the @kbd{m O} command. This command is just an auto-selecting
21577version of the @w{@kbd{a v}} command (@pxref{Algebraic Manipulation}).
21578
21579With a numeric prefix argument of 2, @kbd{C-u 2 j v} applies
21580the @kbd{a s} (@code{calc-simplify}) command to the selected
21581sub-formula. With a prefix argument of 3 or more, e.g., @kbd{C-u j v}
21582applies the @kbd{a e} (@code{calc-simplify-extended}) command.
21583@xref{Simplifying Formulas}. With a negative prefix argument
21584it simplifies at the top level only, just as with @kbd{a v}.
21585Here the ``top'' level refers to the top level of the selected
21586sub-formula.
21587
21588@kindex j "
21589@pindex calc-sel-expand-formula
21590The @kbd{j "} (@code{calc-sel-expand-formula}) command is to @kbd{a "}
21591(@pxref{Algebraic Manipulation}) what @kbd{j v} is to @kbd{a v}.
21592
21593You can use the @kbd{j r} (@code{calc-rewrite-selection}) command
21594to define other algebraic operations on sub-formulas. @xref{Rewrite Rules}.
21595
21596@node Algebraic Manipulation, Simplifying Formulas, Selecting Subformulas, Algebra
21597@section Algebraic Manipulation
21598
21599@noindent
21600The commands in this section perform general-purpose algebraic
21601manipulations. They work on the whole formula at the top of the
21602stack (unless, of course, you have made a selection in that
21603formula).
21604
21605Many algebra commands prompt for a variable name or formula. If you
21606answer the prompt with a blank line, the variable or formula is taken
21607from top-of-stack, and the normal argument for the command is taken
21608from the second-to-top stack level.
21609
21610@kindex a v
21611@pindex calc-alg-evaluate
21612The @kbd{a v} (@code{calc-alg-evaluate}) command performs the normal
21613default simplifications on a formula; for example, @samp{a - -b} is
21614changed to @samp{a + b}. These simplifications are normally done
21615automatically on all Calc results, so this command is useful only if
21616you have turned default simplifications off with an @kbd{m O}
21617command. @xref{Simplification Modes}.
21618
21619It is often more convenient to type @kbd{=}, which is like @kbd{a v}
21620but which also substitutes stored values for variables in the formula.
21621Use @kbd{a v} if you want the variables to ignore their stored values.
21622
21623If you give a numeric prefix argument of 2 to @kbd{a v}, it simplifies
21624as if in algebraic simplification mode. This is equivalent to typing
21625@kbd{a s}; @pxref{Simplifying Formulas}. If you give a numeric prefix
21626of 3 or more, it uses extended simplification mode (@kbd{a e}).
21627
21628If you give a negative prefix argument @i{-1}, @i{-2}, or @i{-3},
21629it simplifies in the corresponding mode but only works on the top-level
21630function call of the formula. For example, @samp{(2 + 3) * (2 + 3)} will
21631simplify to @samp{(2 + 3)^2}, without simplifying the sub-formulas
21632@samp{2 + 3}. As another example, typing @kbd{V R +} to sum the vector
21633@samp{[1, 2, 3, 4]} produces the formula @samp{reduce(add, [1, 2, 3, 4])}
21634in no-simplify mode. Using @kbd{a v} will evaluate this all the way to
2163510; using @kbd{C-u - a v} will evaluate it only to @samp{1 + 2 + 3 + 4}.
21636(@xref{Reducing and Mapping}.)
21637
21638@tindex evalv
21639@tindex evalvn
21640The @kbd{=} command corresponds to the @code{evalv} function, and
21641the related @kbd{N} command, which is like @kbd{=} but temporarily
21642disables symbolic (@kbd{m s}) mode during the evaluation, corresponds
21643to the @code{evalvn} function. (These commands interpret their prefix
21644arguments differently than @kbd{a v}; @kbd{=} treats the prefix as
21645the number of stack elements to evaluate at once, and @kbd{N} treats
21646it as a temporary different working precision.)
21647
21648The @code{evalvn} function can take an alternate working precision
21649as an optional second argument. This argument can be either an
21650integer, to set the precision absolutely, or a vector containing
21651a single integer, to adjust the precision relative to the current
21652precision. Note that @code{evalvn} with a larger than current
21653precision will do the calculation at this higher precision, but the
21654result will as usual be rounded back down to the current precision
21655afterward. For example, @samp{evalvn(pi - 3.1415)} at a precision
21656of 12 will return @samp{9.265359e-5}; @samp{evalvn(pi - 3.1415, 30)}
21657will return @samp{9.26535897932e-5} (computing a 25-digit result which
21658is then rounded down to 12); and @samp{evalvn(pi - 3.1415, [-2])}
21659will return @samp{9.2654e-5}.
21660
21661@kindex a "
21662@pindex calc-expand-formula
21663The @kbd{a "} (@code{calc-expand-formula}) command expands functions
21664into their defining formulas wherever possible. For example,
21665@samp{deg(x^2)} is changed to @samp{180 x^2 / pi}. Most functions,
21666like @code{sin} and @code{gcd}, are not defined by simple formulas
21667and so are unaffected by this command. One important class of
21668functions which @emph{can} be expanded is the user-defined functions
21669created by the @kbd{Z F} command. @xref{Algebraic Definitions}.
21670Other functions which @kbd{a "} can expand include the probability
21671distribution functions, most of the financial functions, and the
21672hyperbolic and inverse hyperbolic functions. A numeric prefix argument
21673affects @kbd{a "} in the same way as it does @kbd{a v}: A positive
21674argument expands all functions in the formula and then simplifies in
21675various ways; a negative argument expands and simplifies only the
21676top-level function call.
21677
21678@kindex a M
21679@pindex calc-map-equation
21680@tindex mapeq
21681The @kbd{a M} (@code{calc-map-equation}) [@code{mapeq}] command applies
21682a given function or operator to one or more equations. It is analogous
21683to @kbd{V M}, which operates on vectors instead of equations.
21684@pxref{Reducing and Mapping}. For example, @kbd{a M S} changes
21685@samp{x = y+1} to @samp{sin(x) = sin(y+1)}, and @kbd{a M +} with
21686@samp{x = y+1} and @cite{6} on the stack produces @samp{x+6 = y+7}.
21687With two equations on the stack, @kbd{a M +} would add the lefthand
21688sides together and the righthand sides together to get the two
21689respective sides of a new equation.
21690
21691Mapping also works on inequalities. Mapping two similar inequalities
21692produces another inequality of the same type. Mapping an inequality
21693with an equation produces an inequality of the same type. Mapping a
21694@samp{<=} with a @samp{<} or @samp{!=} (not-equal) produces a @samp{<}.
21695If inequalities with opposite direction (e.g., @samp{<} and @samp{>})
21696are mapped, the direction of the second inequality is reversed to
21697match the first: Using @kbd{a M +} on @samp{a < b} and @samp{a > 2}
21698reverses the latter to get @samp{2 < a}, which then allows the
21699combination @samp{a + 2 < b + a}, which the @kbd{a s} command can
21700then simplify to get @samp{2 < b}.
21701
21702Using @kbd{a M *}, @kbd{a M /}, @kbd{a M n}, or @kbd{a M &} to negate
21703or invert an inequality will reverse the direction of the inequality.
21704Other adjustments to inequalities are @emph{not} done automatically;
21705@kbd{a M S} will change @w{@samp{x < y}} to @samp{sin(x) < sin(y)} even
21706though this is not true for all values of the variables.
21707
21708@kindex H a M
21709@tindex mapeqp
21710With the Hyperbolic flag, @kbd{H a M} [@code{mapeqp}] does a plain
21711mapping operation without reversing the direction of any inequalities.
21712Thus, @kbd{H a M &} would change @kbd{x > 2} to @kbd{1/x > 0.5}.
21713(This change is mathematically incorrect, but perhaps you were
21714fixing an inequality which was already incorrect.)
21715
21716@kindex I a M
21717@tindex mapeqr
21718With the Inverse flag, @kbd{I a M} [@code{mapeqr}] always reverses
21719the direction of the inequality. You might use @kbd{I a M C} to
21720change @samp{x < y} to @samp{cos(x) > cos(y)} if you know you are
21721working with small positive angles.
21722
21723@kindex a b
21724@pindex calc-substitute
21725@tindex subst
21726The @kbd{a b} (@code{calc-substitute}) [@code{subst}] command substitutes
21727all occurrences
21728of some variable or sub-expression of an expression with a new
21729sub-expression. For example, substituting @samp{sin(x)} with @samp{cos(y)}
21730in @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces
21731@samp{2 cos(y)^2 + x cos(y) + @w{sin(2 x)}}.
21732Note that this is a purely structural substitution; the lone @samp{x} and
21733the @samp{sin(2 x)} stayed the same because they did not look like
21734@samp{sin(x)}. @xref{Rewrite Rules}, for a more general method for
21735doing substitutions.@refill
21736
21737The @kbd{a b} command normally prompts for two formulas, the old
21738one and the new one. If you enter a blank line for the first
21739prompt, all three arguments are taken from the stack (new, then old,
21740then target expression). If you type an old formula but then enter a
21741blank line for the new one, the new formula is taken from top-of-stack
21742and the target from second-to-top. If you answer both prompts, the
21743target is taken from top-of-stack as usual.
21744
21745Note that @kbd{a b} has no understanding of commutativity or
21746associativity. The pattern @samp{x+y} will not match the formula
21747@samp{y+x}. Also, @samp{y+z} will not match inside the formula @samp{x+y+z}
21748because the @samp{+} operator is left-associative, so the ``deep
21749structure'' of that formula is @samp{(x+y) + z}. Use @kbd{d U}
21750(@code{calc-unformatted-language}) mode to see the true structure of
21751a formula. The rewrite rule mechanism, discussed later, does not have
21752these limitations.
21753
21754As an algebraic function, @code{subst} takes three arguments:
21755Target expression, old, new. Note that @code{subst} is always
21756evaluated immediately, even if its arguments are variables, so if
21757you wish to put a call to @code{subst} onto the stack you must
21758turn the default simplifications off first (with @kbd{m O}).
21759
21760@node Simplifying Formulas, Polynomials, Algebraic Manipulation, Algebra
21761@section Simplifying Formulas
21762
21763@noindent
21764@kindex a s
21765@pindex calc-simplify
21766@tindex simplify
21767The @kbd{a s} (@code{calc-simplify}) [@code{simplify}] command applies
21768various algebraic rules to simplify a formula. This includes rules which
21769are not part of the default simplifications because they may be too slow
21770to apply all the time, or may not be desirable all of the time. For
21771example, non-adjacent terms of sums are combined, as in @samp{a + b + 2 a}
21772to @samp{b + 3 a}, and some formulas like @samp{sin(arcsin(x))} are
21773simplified to @samp{x}.
21774
21775The sections below describe all the various kinds of algebraic
21776simplifications Calc provides in full detail. None of Calc's
21777simplification commands are designed to pull rabbits out of hats;
21778they simply apply certain specific rules to put formulas into
21779less redundant or more pleasing forms. Serious algebra in Calc
21780must be done manually, usually with a combination of selections
21781and rewrite rules. @xref{Rearranging with Selections}.
21782@xref{Rewrite Rules}.
21783
21784@xref{Simplification Modes}, for commands to control what level of
21785simplification occurs automatically. Normally only the ``default
21786simplifications'' occur.
21787
21788@menu
21789* Default Simplifications::
21790* Algebraic Simplifications::
21791* Unsafe Simplifications::
21792* Simplification of Units::
21793@end menu
21794
21795@node Default Simplifications, Algebraic Simplifications, Simplifying Formulas, Simplifying Formulas
21796@subsection Default Simplifications
21797
21798@noindent
21799@cindex Default simplifications
21800This section describes the ``default simplifications,'' those which are
21801normally applied to all results. For example, if you enter the variable
21802@cite{x} on the stack twice and push @kbd{+}, Calc's default
21803simplifications automatically change @cite{x + x} to @cite{2 x}.
21804
21805The @kbd{m O} command turns off the default simplifications, so that
21806@cite{x + x} will remain in this form unless you give an explicit
21807``simplify'' command like @kbd{=} or @kbd{a v}. @xref{Algebraic
21808Manipulation}. The @kbd{m D} command turns the default simplifications
21809back on.
21810
21811The most basic default simplification is the evaluation of functions.
21812For example, @cite{2 + 3} is evaluated to @cite{5}, and @cite{@t{sqrt}(9)}
21813is evaluated to @cite{3}. Evaluation does not occur if the arguments
21814to a function are somehow of the wrong type (@cite{@t{tan}([2,3,4])},
21815range (@cite{@t{tan}(90)}), or number (@cite{@t{tan}(3,5)}), or if the
21816function name is not recognized (@cite{@t{f}(5)}), or if ``symbolic''
21817mode (@pxref{Symbolic Mode}) prevents evaluation (@cite{@t{sqrt}(2)}).
21818
21819Calc simplifies (evaluates) the arguments to a function before it
21820simplifies the function itself. Thus @cite{@t{sqrt}(5+4)} is
21821simplified to @cite{@t{sqrt}(9)} before the @code{sqrt} function
21822itself is applied. There are very few exceptions to this rule:
21823@code{quote}, @code{lambda}, and @code{condition} (the @code{::}
21824operator) do not evaluate their arguments, @code{if} (the @code{? :}
21825operator) does not evaluate all of its arguments, and @code{evalto}
21826does not evaluate its lefthand argument.
21827
21828Most commands apply the default simplifications to all arguments they
21829take from the stack, perform a particular operation, then simplify
21830the result before pushing it back on the stack. In the common special
21831case of regular arithmetic commands like @kbd{+} and @kbd{Q} [@code{sqrt}],
21832the arguments are simply popped from the stack and collected into a
21833suitable function call, which is then simplified (the arguments being
21834simplified first as part of the process, as described above).
21835
21836The default simplifications are too numerous to describe completely
21837here, but this section will describe the ones that apply to the
21838major arithmetic operators. This list will be rather technical in
21839nature, and will probably be interesting to you only if you are
21840a serious user of Calc's algebra facilities.
21841
21842@tex
21843\bigskip
21844@end tex
21845
21846As well as the simplifications described here, if you have stored
21847any rewrite rules in the variable @code{EvalRules} then these rules
21848will also be applied before any built-in default simplifications.
21849@xref{Automatic Rewrites}, for details.
21850
21851@tex
21852\bigskip
21853@end tex
21854
21855And now, on with the default simplifications:
21856
21857Arithmetic operators like @kbd{+} and @kbd{*} always take two
21858arguments in Calc's internal form. Sums and products of three or
21859more terms are arranged by the associative law of algebra into
21860a left-associative form for sums, @cite{((a + b) + c) + d}, and
21861a right-associative form for products, @cite{a * (b * (c * d))}.
21862Formulas like @cite{(a + b) + (c + d)} are rearranged to
21863left-associative form, though this rarely matters since Calc's
21864algebra commands are designed to hide the inner structure of
21865sums and products as much as possible. Sums and products in
21866their proper associative form will be written without parentheses
21867in the examples below.
21868
21869Sums and products are @emph{not} rearranged according to the
21870commutative law (@cite{a + b} to @cite{b + a}) except in a few
21871special cases described below. Some algebra programs always
21872rearrange terms into a canonical order, which enables them to
21873see that @cite{a b + b a} can be simplified to @cite{2 a b}.
21874Calc assumes you have put the terms into the order you want
21875and generally leaves that order alone, with the consequence
21876that formulas like the above will only be simplified if you
21877explicitly give the @kbd{a s} command. @xref{Algebraic
21878Simplifications}.
21879
21880Differences @cite{a - b} are treated like sums @cite{a + (-b)}
21881for purposes of simplification; one of the default simplifications
21882is to rewrite @cite{a + (-b)} or @cite{(-b) + a}, where @cite{-b}
21883represents a ``negative-looking'' term, into @cite{a - b} form.
21884``Negative-looking'' means negative numbers, negated formulas like
21885@cite{-x}, and products or quotients in which either term is
21886negative-looking.
21887
21888Other simplifications involving negation are @cite{-(-x)} to @cite{x};
21889@cite{-(a b)} or @cite{-(a/b)} where either @cite{a} or @cite{b} is
21890negative-looking, simplified by negating that term, or else where
21891@cite{a} or @cite{b} is any number, by negating that number;
21892@cite{-(a + b)} to @cite{-a - b}, and @cite{-(b - a)} to @cite{a - b}.
21893(This, and rewriting @cite{(-b) + a} to @cite{a - b}, are the only
21894cases where the order of terms in a sum is changed by the default
21895simplifications.)
21896
21897The distributive law is used to simplify sums in some cases:
21898@cite{a x + b x} to @cite{(a + b) x}, where @cite{a} represents
21899a number or an implicit 1 or @i{-1} (as in @cite{x} or @cite{-x})
21900and similarly for @cite{b}. Use the @kbd{a c}, @w{@kbd{a f}}, or
21901@kbd{j M} commands to merge sums with non-numeric coefficients
21902using the distributive law.
21903
21904The distributive law is only used for sums of two terms, or
21905for adjacent terms in a larger sum. Thus @cite{a + b + b + c}
21906is simplified to @cite{a + 2 b + c}, but @cite{a + b + c + b}
21907is not simplified. The reason is that comparing all terms of a
21908sum with one another would require time proportional to the
21909square of the number of terms; Calc relegates potentially slow
21910operations like this to commands that have to be invoked
21911explicitly, like @kbd{a s}.
21912
21913Finally, @cite{a + 0} and @cite{0 + a} are simplified to @cite{a}.
21914A consequence of the above rules is that @cite{0 - a} is simplified
21915to @cite{-a}.
21916
21917@tex
21918\bigskip
21919@end tex
21920
21921The products @cite{1 a} and @cite{a 1} are simplified to @cite{a};
21922@cite{(-1) a} and @cite{a (-1)} are simplified to @cite{-a};
21923@cite{0 a} and @cite{a 0} are simplified to @cite{0}, except that
21924in matrix mode where @cite{a} is not provably scalar the result
21925is the generic zero matrix @samp{idn(0)}, and that if @cite{a} is
21926infinite the result is @samp{nan}.
21927
21928Also, @cite{(-a) b} and @cite{a (-b)} are simplified to @cite{-(a b)},
21929where this occurs for negated formulas but not for regular negative
21930numbers.
21931
21932Products are commuted only to move numbers to the front:
21933@cite{a b 2} is commuted to @cite{2 a b}.
21934
21935The product @cite{a (b + c)} is distributed over the sum only if
21936@cite{a} and at least one of @cite{b} and @cite{c} are numbers:
21937@cite{2 (x + 3)} goes to @cite{2 x + 6}. The formula
21938@cite{(-a) (b - c)}, where @cite{-a} is a negative number, is
21939rewritten to @cite{a (c - b)}.
21940
21941The distributive law of products and powers is used for adjacent
21942terms of the product: @cite{x^a x^b} goes to @c{$x^{a+b}$}
21943@cite{x^(a+b)}
21944where @cite{a} is a number, or an implicit 1 (as in @cite{x}),
21945or the implicit one-half of @cite{@t{sqrt}(x)}, and similarly for
21946@cite{b}. The result is written using @samp{sqrt} or @samp{1/sqrt}
21947if the sum of the powers is @cite{1/2} or @cite{-1/2}, respectively.
21948If the sum of the powers is zero, the product is simplified to
21949@cite{1} or to @samp{idn(1)} if matrix mode is enabled.
21950
21951The product of a negative power times anything but another negative
21952power is changed to use division: @c{$x^{-2} y$}
21953@cite{x^(-2) y} goes to @cite{y / x^2} unless matrix mode is
21954in effect and neither @cite{x} nor @cite{y} are scalar (in which
21955case it is considered unsafe to rearrange the order of the terms).
21956
21957Finally, @cite{a (b/c)} is rewritten to @cite{(a b)/c}, and also
21958@cite{(a/b) c} is changed to @cite{(a c)/b} unless in matrix mode.
21959
21960@tex
21961\bigskip
21962@end tex
21963
21964Simplifications for quotients are analogous to those for products.
21965The quotient @cite{0 / x} is simplified to @cite{0}, with the same
21966exceptions that were noted for @cite{0 x}. Likewise, @cite{x / 1}
21967and @cite{x / (-1)} are simplified to @cite{x} and @cite{-x},
21968respectively.
21969
21970The quotient @cite{x / 0} is left unsimplified or changed to an
21971infinite quantity, as directed by the current infinite mode.
21972@xref{Infinite Mode}.
21973
21974The expression @c{$a / b^{-c}$}
21975@cite{a / b^(-c)} is changed to @cite{a b^c},
21976where @cite{-c} is any negative-looking power. Also, @cite{1 / b^c}
21977is changed to @c{$b^{-c}$}
21978@cite{b^(-c)} for any power @cite{c}.
21979
21980Also, @cite{(-a) / b} and @cite{a / (-b)} go to @cite{-(a/b)};
21981@cite{(a/b) / c} goes to @cite{a / (b c)}; and @cite{a / (b/c)}
21982goes to @cite{(a c) / b} unless matrix mode prevents this
21983rearrangement. Similarly, @cite{a / (b:c)} is simplified to
21984@cite{(c:b) a} for any fraction @cite{b:c}.
21985
21986The distributive law is applied to @cite{(a + b) / c} only if
21987@cite{c} and at least one of @cite{a} and @cite{b} are numbers.
21988Quotients of powers and square roots are distributed just as
21989described for multiplication.
21990
21991Quotients of products cancel only in the leading terms of the
21992numerator and denominator. In other words, @cite{a x b / a y b}
21993is cancelled to @cite{x b / y b} but not to @cite{x / y}. Once
21994again this is because full cancellation can be slow; use @kbd{a s}
21995to cancel all terms of the quotient.
21996
21997Quotients of negative-looking values are simplified according
21998to @cite{(-a) / (-b)} to @cite{a / b}, @cite{(-a) / (b - c)}
21999to @cite{a / (c - b)}, and @cite{(a - b) / (-c)} to @cite{(b - a) / c}.
22000
22001@tex
22002\bigskip
22003@end tex
22004
22005The formula @cite{x^0} is simplified to @cite{1}, or to @samp{idn(1)}
22006in matrix mode. The formula @cite{0^x} is simplified to @cite{0}
22007unless @cite{x} is a negative number or complex number, in which
22008case the result is an infinity or an unsimplified formula according
22009to the current infinite mode. Note that @cite{0^0} is an
22010indeterminate form, as evidenced by the fact that the simplifications
22011for @cite{x^0} and @cite{0^x} conflict when @cite{x=0}.
22012
22013Powers of products or quotients @cite{(a b)^c}, @cite{(a/b)^c}
22014are distributed to @cite{a^c b^c}, @cite{a^c / b^c} only if @cite{c}
22015is an integer, or if either @cite{a} or @cite{b} are nonnegative
22016real numbers. Powers of powers @cite{(a^b)^c} are simplified to
22017@c{$a^{b c}$}
22018@cite{a^(b c)} only when @cite{c} is an integer and @cite{b c} also
22019evaluates to an integer. Without these restrictions these simplifications
22020would not be safe because of problems with principal values.
22021(In other words, @c{$((-3)^{1/2})^2$}
22022@cite{((-3)^1:2)^2} is safe to simplify, but
22023@c{$((-3)^2)^{1/2}$}
22024@cite{((-3)^2)^1:2} is not.) @xref{Declarations}, for ways to inform
22025Calc that your variables satisfy these requirements.
22026
22027As a special case of this rule, @cite{@t{sqrt}(x)^n} is simplified to
22028@c{$x^{n/2}$}
22029@cite{x^(n/2)} only for even integers @cite{n}.
22030
22031If @cite{a} is known to be real, @cite{b} is an even integer, and
22032@cite{c} is a half- or quarter-integer, then @cite{(a^b)^c} is
22033simplified to @c{$@t{abs}(a^{b c})$}
22034@cite{@t{abs}(a^(b c))}.
22035
22036Also, @cite{(-a)^b} is simplified to @cite{a^b} if @cite{b} is an
22037even integer, or to @cite{-(a^b)} if @cite{b} is an odd integer,
22038for any negative-looking expression @cite{-a}.
22039
22040Square roots @cite{@t{sqrt}(x)} generally act like one-half powers
22041@c{$x^{1:2}$}
22042@cite{x^1:2} for the purposes of the above-listed simplifications.
22043
22044Also, note that @c{$1 / x^{1:2}$}
22045@cite{1 / x^1:2} is changed to @c{$x^{-1:2}$}
22046@cite{x^(-1:2)},
22047but @cite{1 / @t{sqrt}(x)} is left alone.
22048
22049@tex
22050\bigskip
22051@end tex
22052
22053Generic identity matrices (@pxref{Matrix Mode}) are simplified by the
22054following rules: @cite{@t{idn}(a) + b} to @cite{a + b} if @cite{b}
22055is provably scalar, or expanded out if @cite{b} is a matrix;
22056@cite{@t{idn}(a) + @t{idn}(b)} to @cite{@t{idn}(a + b)};
22057@cite{-@t{idn}(a)} to @cite{@t{idn}(-a)}; @cite{a @t{idn}(b)} to
22058@cite{@t{idn}(a b)} if @cite{a} is provably scalar, or to @cite{a b}
22059if @cite{a} is provably non-scalar; @cite{@t{idn}(a) @t{idn}(b)}
22060to @cite{@t{idn}(a b)}; analogous simplifications for quotients
22061involving @code{idn}; and @cite{@t{idn}(a)^n} to @cite{@t{idn}(a^n)}
22062where @cite{n} is an integer.
22063
22064@tex
22065\bigskip
22066@end tex
22067
22068The @code{floor} function and other integer truncation functions
22069vanish if the argument is provably integer-valued, so that
22070@cite{@t{floor}(@t{round}(x))} simplifies to @cite{@t{round}(x)}.
22071Also, combinations of @code{float}, @code{floor} and its friends,
22072and @code{ffloor} and its friends, are simplified in appropriate
22073ways. @xref{Integer Truncation}.
22074
22075The expression @cite{@t{abs}(-x)} changes to @cite{@t{abs}(x)}.
22076The expression @cite{@t{abs}(@t{abs}(x))} changes to @cite{@t{abs}(x)};
22077in fact, @cite{@t{abs}(x)} changes to @cite{x} or @cite{-x} if @cite{x}
22078is provably nonnegative or nonpositive (@pxref{Declarations}).
22079
22080While most functions do not recognize the variable @code{i} as an
22081imaginary number, the @code{arg} function does handle the two cases
22082@cite{@t{arg}(@t{i})} and @cite{@t{arg}(-@t{i})} just for convenience.
22083
22084The expression @cite{@t{conj}(@t{conj}(x))} simplifies to @cite{x}.
22085Various other expressions involving @code{conj}, @code{re}, and
22086@code{im} are simplified, especially if some of the arguments are
22087provably real or involve the constant @code{i}. For example,
22088@cite{@t{conj}(a + b i)} is changed to @cite{@t{conj}(a) - @t{conj}(b) i},
22089or to @cite{a - b i} if @cite{a} and @cite{b} are known to be real.
22090
22091Functions like @code{sin} and @code{arctan} generally don't have
22092any default simplifications beyond simply evaluating the functions
22093for suitable numeric arguments and infinity. The @kbd{a s} command
22094described in the next section does provide some simplifications for
22095these functions, though.
22096
22097One important simplification that does occur is that @cite{@t{ln}(@t{e})}
22098is simplified to 1, and @cite{@t{ln}(@t{e}^x)} is simplified to @cite{x}
22099for any @cite{x}. This occurs even if you have stored a different
22100value in the Calc variable @samp{e}; but this would be a bad idea
22101in any case if you were also using natural logarithms!
22102
22103Among the logical functions, @t{!}@i{(a} @t{<=} @i{b)} changes to
22104@cite{a > b} and so on. Equations and inequalities where both sides
22105are either negative-looking or zero are simplified by negating both sides
22106and reversing the inequality. While it might seem reasonable to simplify
22107@cite{!!x} to @cite{x}, this would not be valid in general because
22108@cite{!!2} is 1, not 2.
22109
22110Most other Calc functions have few if any default simplifications
22111defined, aside of course from evaluation when the arguments are
22112suitable numbers.
22113
22114@node Algebraic Simplifications, Unsafe Simplifications, Default Simplifications, Simplifying Formulas
22115@subsection Algebraic Simplifications
22116
22117@noindent
22118@cindex Algebraic simplifications
22119The @kbd{a s} command makes simplifications that may be too slow to
22120do all the time, or that may not be desirable all of the time.
22121If you find these simplifications are worthwhile, you can type
22122@kbd{m A} to have Calc apply them automatically.
22123
22124This section describes all simplifications that are performed by
22125the @kbd{a s} command. Note that these occur in addition to the
22126default simplifications; even if the default simplifications have
22127been turned off by an @kbd{m O} command, @kbd{a s} will turn them
22128back on temporarily while it simplifies the formula.
22129
22130There is a variable, @code{AlgSimpRules}, in which you can put rewrites
22131to be applied by @kbd{a s}. Its use is analogous to @code{EvalRules},
22132but without the special restrictions. Basically, the simplifier does
22133@samp{@w{a r} AlgSimpRules} with an infinite repeat count on the whole
22134expression being simplified, then it traverses the expression applying
22135the built-in rules described below. If the result is different from
22136the original expression, the process repeats with the default
22137simplifications (including @code{EvalRules}), then @code{AlgSimpRules},
22138then the built-in simplifications, and so on.
22139
22140@tex
22141\bigskip
22142@end tex
22143
22144Sums are simplified in two ways. Constant terms are commuted to the
22145end of the sum, so that @cite{a + 2 + b} changes to @cite{a + b + 2}.
22146The only exception is that a constant will not be commuted away
22147from the first position of a difference, i.e., @cite{2 - x} is not
22148commuted to @cite{-x + 2}.
22149
22150Also, terms of sums are combined by the distributive law, as in
22151@cite{x + y + 2 x} to @cite{y + 3 x}. This always occurs for
22152adjacent terms, but @kbd{a s} compares all pairs of terms including
22153non-adjacent ones.
22154
22155@tex
22156\bigskip
22157@end tex
22158
22159Products are sorted into a canonical order using the commutative
22160law. For example, @cite{b c a} is commuted to @cite{a b c}.
22161This allows easier comparison of products; for example, the default
22162simplifications will not change @cite{x y + y x} to @cite{2 x y},
22163but @kbd{a s} will; it first rewrites the sum to @cite{x y + x y},
22164and then the default simplifications are able to recognize a sum
22165of identical terms.
22166
22167The canonical ordering used to sort terms of products has the
22168property that real-valued numbers, interval forms and infinities
22169come first, and are sorted into increasing order. The @kbd{V S}
22170command uses the same ordering when sorting a vector.
22171
22172Sorting of terms of products is inhibited when matrix mode is
22173turned on; in this case, Calc will never exchange the order of
22174two terms unless it knows at least one of the terms is a scalar.
22175
22176Products of powers are distributed by comparing all pairs of
22177terms, using the same method that the default simplifications
22178use for adjacent terms of products.
22179
22180Even though sums are not sorted, the commutative law is still
22181taken into account when terms of a product are being compared.
22182Thus @cite{(x + y) (y + x)} will be simplified to @cite{(x + y)^2}.
22183A subtle point is that @cite{(x - y) (y - x)} will @emph{not}
22184be simplified to @cite{-(x - y)^2}; Calc does not notice that
22185one term can be written as a constant times the other, even if
22186that constant is @i{-1}.
22187
22188A fraction times any expression, @cite{(a:b) x}, is changed to
22189a quotient involving integers: @cite{a x / b}. This is not
22190done for floating-point numbers like @cite{0.5}, however. This
22191is one reason why you may find it convenient to turn Fraction mode
22192on while doing algebra; @pxref{Fraction Mode}.
22193
22194@tex
22195\bigskip
22196@end tex
22197
22198Quotients are simplified by comparing all terms in the numerator
22199with all terms in the denominator for possible cancellation using
22200the distributive law. For example, @cite{a x^2 b / c x^3 d} will
22201cancel @cite{x^2} from both sides to get @cite{a b / c x d}.
22202(The terms in the denominator will then be rearranged to @cite{c d x}
22203as described above.) If there is any common integer or fractional
22204factor in the numerator and denominator, it is cancelled out;
22205for example, @cite{(4 x + 6) / 8 x} simplifies to @cite{(2 x + 3) / 4 x}.
22206
22207Non-constant common factors are not found even by @kbd{a s}. To
22208cancel the factor @cite{a} in @cite{(a x + a) / a^2} you could first
22209use @kbd{j M} on the product @cite{a x} to Merge the numerator to
22210@cite{a (1+x)}, which can then be simplified successfully.
22211
22212@tex
22213\bigskip
22214@end tex
22215
22216Integer powers of the variable @code{i} are simplified according
22217to the identity @cite{i^2 = -1}. If you store a new value other
22218than the complex number @cite{(0,1)} in @code{i}, this simplification
22219will no longer occur. This is done by @kbd{a s} instead of by default
22220in case someone (unwisely) uses the name @code{i} for a variable
22221unrelated to complex numbers; it would be unfortunate if Calc
22222quietly and automatically changed this formula for reasons the
22223user might not have been thinking of.
22224
22225Square roots of integer or rational arguments are simplified in
22226several ways. (Note that these will be left unevaluated only in
22227Symbolic mode.) First, square integer or rational factors are
22228pulled out so that @cite{@t{sqrt}(8)} is rewritten as
22229@c{$2\,\t{sqrt}(2)$}
22230@cite{2 sqrt(2)}. Conceptually speaking this implies factoring
22231the argument into primes and moving pairs of primes out of the
22232square root, but for reasons of efficiency Calc only looks for
22233primes up to 29.
22234
22235Square roots in the denominator of a quotient are moved to the
22236numerator: @cite{1 / @t{sqrt}(3)} changes to @cite{@t{sqrt}(3) / 3}.
22237The same effect occurs for the square root of a fraction:
22238@cite{@t{sqrt}(2:3)} changes to @cite{@t{sqrt}(6) / 3}.
22239
22240@tex
22241\bigskip
22242@end tex
22243
22244The @code{%} (modulo) operator is simplified in several ways
22245when the modulus @cite{M} is a positive real number. First, if
22246the argument is of the form @cite{x + n} for some real number
22247@cite{n}, then @cite{n} is itself reduced modulo @cite{M}. For
22248example, @samp{(x - 23) % 10} is simplified to @samp{(x + 7) % 10}.
22249
22250If the argument is multiplied by a constant, and this constant
22251has a common integer divisor with the modulus, then this factor is
22252cancelled out. For example, @samp{12 x % 15} is changed to
22253@samp{3 (4 x % 5)} by factoring out 3. Also, @samp{(12 x + 1) % 15}
22254is changed to @samp{3 ((4 x + 1:3) % 5)}. While these forms may
22255not seem ``simpler,'' they allow Calc to discover useful information
22256about modulo forms in the presence of declarations.
22257
22258If the modulus is 1, then Calc can use @code{int} declarations to
22259evaluate the expression. For example, the idiom @samp{x % 2} is
22260often used to check whether a number is odd or even. As described
22261above, @w{@samp{2 n % 2}} and @samp{(2 n + 1) % 2} are simplified to
22262@samp{2 (n % 1)} and @samp{2 ((n + 1:2) % 1)}, respectively; Calc
22263can simplify these to 0 and 1 (respectively) if @code{n} has been
22264declared to be an integer.
22265
22266@tex
22267\bigskip
22268@end tex
22269
22270Trigonometric functions are simplified in several ways. First,
22271@cite{@t{sin}(@t{arcsin}(x))} is simplified to @cite{x}, and
22272similarly for @code{cos} and @code{tan}. If the argument to
22273@code{sin} is negative-looking, it is simplified to @cite{-@t{sin}(x)},
22274and similarly for @code{cos} and @code{tan}. Finally, certain
22275special values of the argument are recognized;
22276@pxref{Trigonometric and Hyperbolic Functions}.
22277
22278Trigonometric functions of inverses of different trigonometric
22279functions can also be simplified, as in @cite{@t{sin}(@t{arccos}(x))}
22280to @cite{@t{sqrt}(1 - x^2)}.
22281
22282Hyperbolic functions of their inverses and of negative-looking
22283arguments are also handled, as are exponentials of inverse
22284hyperbolic functions.
22285
22286No simplifications for inverse trigonometric and hyperbolic
22287functions are known, except for negative arguments of @code{arcsin},
22288@code{arctan}, @code{arcsinh}, and @code{arctanh}. Note that
22289@cite{@t{arcsin}(@t{sin}(x))} can @emph{not} safely change to
22290@cite{x}, since this only correct within an integer multiple
22291of @c{$2 \pi$}
22292@cite{2 pi} radians or 360 degrees. However,
22293@cite{@t{arcsinh}(@t{sinh}(x))} is simplified to @cite{x} if
22294@cite{x} is known to be real.
22295
22296Several simplifications that apply to logarithms and exponentials
22297are that @cite{@t{exp}(@t{ln}(x))}, @c{$@t{e}^{\ln(x)}$}
22298@cite{e^@t{ln}(x)}, and
22299@c{$10^{{\rm log10}(x)}$}
22300@cite{10^@t{log10}(x)} all reduce to @cite{x}.
22301Also, @cite{@t{ln}(@t{exp}(x))}, etc., can reduce to @cite{x} if
22302@cite{x} is provably real. The form @cite{@t{exp}(x)^y} is simplified
22303to @cite{@t{exp}(x y)}. If @cite{x} is a suitable multiple of @c{$\pi i$}
22304@cite{pi i}
22305(as described above for the trigonometric functions), then @cite{@t{exp}(x)}
22306or @cite{e^x} will be expanded. Finally, @cite{@t{ln}(x)} is simplified
22307to a form involving @code{pi} and @code{i} where @cite{x} is provably
22308negative, positive imaginary, or negative imaginary.
22309
22310The error functions @code{erf} and @code{erfc} are simplified when
22311their arguments are negative-looking or are calls to the @code{conj}
22312function.
22313
22314@tex
22315\bigskip
22316@end tex
22317
22318Equations and inequalities are simplified by cancelling factors
22319of products, quotients, or sums on both sides. Inequalities
22320change sign if a negative multiplicative factor is cancelled.
22321Non-constant multiplicative factors as in @cite{a b = a c} are
22322cancelled from equations only if they are provably nonzero (generally
22323because they were declared so; @pxref{Declarations}). Factors
22324are cancelled from inequalities only if they are nonzero and their
22325sign is known.
22326
22327Simplification also replaces an equation or inequality with
223281 or 0 (``true'' or ``false'') if it can through the use of
22329declarations. If @cite{x} is declared to be an integer greater
22330than 5, then @cite{x < 3}, @cite{x = 3}, and @cite{x = 7.5} are
22331all simplified to 0, but @cite{x > 3} is simplified to 1.
22332By a similar analysis, @cite{abs(x) >= 0} is simplified to 1,
22333as is @cite{x^2 >= 0} if @cite{x} is known to be real.
22334
22335@node Unsafe Simplifications, Simplification of Units, Algebraic Simplifications, Simplifying Formulas
22336@subsection ``Unsafe'' Simplifications
22337
22338@noindent
22339@cindex Unsafe simplifications
22340@cindex Extended simplification
22341@kindex a e
22342@pindex calc-simplify-extended
22343@c @mindex esimpl@idots
22344@tindex esimplify
22345The @kbd{a e} (@code{calc-simplify-extended}) [@code{esimplify}] command
22346is like @kbd{a s}
22347except that it applies some additional simplifications which are not
22348``safe'' in all cases. Use this only if you know the values in your
22349formula lie in the restricted ranges for which these simplifications
22350are valid. The symbolic integrator uses @kbd{a e};
22351one effect of this is that the integrator's results must be used with
22352caution. Where an integral table will often attach conditions like
22353``for positive @cite{a} only,'' Calc (like most other symbolic
22354integration programs) will simply produce an unqualified result.@refill
22355
22356Because @kbd{a e}'s simplifications are unsafe, it is sometimes better
22357to type @kbd{C-u -3 a v}, which does extended simplification only
22358on the top level of the formula without affecting the sub-formulas.
22359In fact, @kbd{C-u -3 j v} allows you to target extended simplification
22360to any specific part of a formula.
22361
22362The variable @code{ExtSimpRules} contains rewrites to be applied by
22363the @kbd{a e} command. These are applied in addition to
22364@code{EvalRules} and @code{AlgSimpRules}. (The @kbd{a r AlgSimpRules}
22365step described above is simply followed by an @kbd{a r ExtSimpRules} step.)
22366
22367Following is a complete list of ``unsafe'' simplifications performed
22368by @kbd{a e}.
22369
22370@tex
22371\bigskip
22372@end tex
22373
22374Inverse trigonometric or hyperbolic functions, called with their
22375corresponding non-inverse functions as arguments, are simplified
22376by @kbd{a e}. For example, @cite{@t{arcsin}(@t{sin}(x))} changes
22377to @cite{x}. Also, @cite{@t{arcsin}(@t{cos}(x))} and
22378@cite{@t{arccos}(@t{sin}(x))} both change to @cite{@t{pi}/2 - x}.
22379These simplifications are unsafe because they are valid only for
22380values of @cite{x} in a certain range; outside that range, values
22381are folded down to the 360-degree range that the inverse trigonometric
22382functions always produce.
22383
22384Powers of powers @cite{(x^a)^b} are simplified to @c{$x^{a b}$}
22385@cite{x^(a b)}
22386for all @cite{a} and @cite{b}. These results will be valid only
22387in a restricted range of @cite{x}; for example, in @c{$(x^2)^{1:2}$}
22388@cite{(x^2)^1:2}
22389the powers cancel to get @cite{x}, which is valid for positive values
22390of @cite{x} but not for negative or complex values.
22391
22392Similarly, @cite{@t{sqrt}(x^a)} and @cite{@t{sqrt}(x)^a} are both
22393simplified (possibly unsafely) to @c{$x^{a/2}$}
22394@cite{x^(a/2)}.
22395
22396Forms like @cite{@t{sqrt}(1 - @t{sin}(x)^2)} are simplified to, e.g.,
22397@cite{@t{cos}(x)}. Calc has identities of this sort for @code{sin},
22398@code{cos}, @code{tan}, @code{sinh}, and @code{cosh}.
22399
22400Arguments of square roots are partially factored to look for
22401squared terms that can be extracted. For example,
22402@cite{@t{sqrt}(a^2 b^3 + a^3 b^2)} simplifies to @cite{a b @t{sqrt}(a+b)}.
22403
22404The simplifications of @cite{@t{ln}(@t{exp}(x))}, @cite{@t{ln}(@t{e}^x)},
22405and @cite{@t{log10}(10^x)} to @cite{x} are also unsafe because
22406of problems with principal values (although these simplifications
22407are safe if @cite{x} is known to be real).
22408
22409Common factors are cancelled from products on both sides of an
22410equation, even if those factors may be zero: @cite{a x / b x}
22411to @cite{a / b}. Such factors are never cancelled from
22412inequalities: Even @kbd{a e} is not bold enough to reduce
22413@cite{a x < b x} to @cite{a < b} (or @cite{a > b}, depending
22414on whether you believe @cite{x} is positive or negative).
22415The @kbd{a M /} command can be used to divide a factor out of
22416both sides of an inequality.
22417
22418@node Simplification of Units, , Unsafe Simplifications, Simplifying Formulas
22419@subsection Simplification of Units
22420
22421@noindent
22422The simplifications described in this section are applied by the
22423@kbd{u s} (@code{calc-simplify-units}) command. These are in addition
22424to the regular @kbd{a s} (but not @kbd{a e}) simplifications described
22425earlier. @xref{Basic Operations on Units}.
22426
22427The variable @code{UnitSimpRules} contains rewrites to be applied by
22428the @kbd{u s} command. These are applied in addition to @code{EvalRules}
22429and @code{AlgSimpRules}.
22430
22431Scalar mode is automatically put into effect when simplifying units.
22432@xref{Matrix Mode}.
22433
22434Sums @cite{a + b} involving units are simplified by extracting the
22435units of @cite{a} as if by the @kbd{u x} command (call the result
22436@cite{u_a}), then simplifying the expression @cite{b / u_a}
22437using @kbd{u b} and @kbd{u s}. If the result has units then the sum
22438is inconsistent and is left alone. Otherwise, it is rewritten
22439in terms of the units @cite{u_a}.
22440
22441If units auto-ranging mode is enabled, products or quotients in
22442which the first argument is a number which is out of range for the
22443leading unit are modified accordingly.
22444
22445When cancelling and combining units in products and quotients,
22446Calc accounts for unit names that differ only in the prefix letter.
22447For example, @samp{2 km m} is simplified to @samp{2000 m^2}.
22448However, compatible but different units like @code{ft} and @code{in}
22449are not combined in this way.
22450
22451Quotients @cite{a / b} are simplified in three additional ways. First,
22452if @cite{b} is a number or a product beginning with a number, Calc
22453computes the reciprocal of this number and moves it to the numerator.
22454
22455Second, for each pair of unit names from the numerator and denominator
22456of a quotient, if the units are compatible (e.g., they are both
22457units of area) then they are replaced by the ratio between those
22458units. For example, in @samp{3 s in N / kg cm} the units
22459@samp{in / cm} will be replaced by @cite{2.54}.
22460
22461Third, if the units in the quotient exactly cancel out, so that
22462a @kbd{u b} command on the quotient would produce a dimensionless
22463number for an answer, then the quotient simplifies to that number.
22464
22465For powers and square roots, the ``unsafe'' simplifications
22466@cite{(a b)^c} to @cite{a^c b^c}, @cite{(a/b)^c} to @cite{a^c / b^c},
22467and @cite{(a^b)^c} to @c{$a^{b c}$}
22468@cite{a^(b c)} are done if the powers are
22469real numbers. (These are safe in the context of units because
22470all numbers involved can reasonably be assumed to be real.)
22471
22472Also, if a unit name is raised to a fractional power, and the
22473base units in that unit name all occur to powers which are a
22474multiple of the denominator of the power, then the unit name
22475is expanded out into its base units, which can then be simplified
22476according to the previous paragraph. For example, @samp{acre^1.5}
22477is simplified by noting that @cite{1.5 = 3:2}, that @samp{acre}
22478is defined in terms of @samp{m^2}, and that the 2 in the power of
22479@code{m} is a multiple of 2 in @cite{3:2}. Thus, @code{acre^1.5} is
22480replaced by approximately @c{$(4046 m^2)^{1.5}$}
22481@cite{(4046 m^2)^1.5}, which is then
22482changed to @c{$4046^{1.5} \, (m^2)^{1.5}$}
22483@cite{4046^1.5 (m^2)^1.5}, then to @cite{257440 m^3}.
22484
22485The functions @code{float}, @code{frac}, @code{clean}, @code{abs},
22486as well as @code{floor} and the other integer truncation functions,
22487applied to unit names or products or quotients involving units, are
22488simplified. For example, @samp{round(1.6 in)} is changed to
22489@samp{round(1.6) round(in)}; the lefthand term evaluates to 2,
22490and the righthand term simplifies to @code{in}.
22491
22492The functions @code{sin}, @code{cos}, and @code{tan} with arguments
22493that have angular units like @code{rad} or @code{arcmin} are
22494simplified by converting to base units (radians), then evaluating
22495with the angular mode temporarily set to radians.
22496
22497@node Polynomials, Calculus, Simplifying Formulas, Algebra
22498@section Polynomials
22499
22500A @dfn{polynomial} is a sum of terms which are coefficients times
22501various powers of a ``base'' variable. For example, @cite{2 x^2 + 3 x - 4}
22502is a polynomial in @cite{x}. Some formulas can be considered
22503polynomials in several different variables: @cite{1 + 2 x + 3 y + 4 x y^2}
22504is a polynomial in both @cite{x} and @cite{y}. Polynomial coefficients
22505are often numbers, but they may in general be any formulas not
22506involving the base variable.
22507
22508@kindex a f
22509@pindex calc-factor
22510@tindex factor
22511The @kbd{a f} (@code{calc-factor}) [@code{factor}] command factors a
22512polynomial into a product of terms. For example, the polynomial
22513@cite{x^3 + 2 x^2 + x} is factored into @samp{x*(x+1)^2}. As another
22514example, @cite{a c + b d + b c + a d} is factored into the product
22515@cite{(a + b) (c + d)}.
22516
22517Calc currently has three algorithms for factoring. Formulas which are
22518linear in several variables, such as the second example above, are
22519merged according to the distributive law. Formulas which are
22520polynomials in a single variable, with constant integer or fractional
22521coefficients, are factored into irreducible linear and/or quadratic
22522terms. The first example above factors into three linear terms
22523(@cite{x}, @cite{x+1}, and @cite{x+1} again). Finally, formulas
22524which do not fit the above criteria are handled by the algebraic
22525rewrite mechanism.
22526
22527Calc's polynomial factorization algorithm works by using the general
22528root-finding command (@w{@kbd{a P}}) to solve for the roots of the
22529polynomial. It then looks for roots which are rational numbers
22530or complex-conjugate pairs, and converts these into linear and
22531quadratic terms, respectively. Because it uses floating-point
22532arithmetic, it may be unable to find terms that involve large
22533integers (whose number of digits approaches the current precision).
22534Also, irreducible factors of degree higher than quadratic are not
22535found, and polynomials in more than one variable are not treated.
22536(A more robust factorization algorithm may be included in a future
22537version of Calc.)
22538
22539@vindex FactorRules
22540@c @starindex
22541@tindex thecoefs
22542@c @starindex
22543@c @mindex @idots
22544@tindex thefactors
22545The rewrite-based factorization method uses rules stored in the variable
22546@code{FactorRules}. @xref{Rewrite Rules}, for a discussion of the
22547operation of rewrite rules. The default @code{FactorRules} are able
22548to factor quadratic forms symbolically into two linear terms,
22549@cite{(a x + b) (c x + d)}. You can edit these rules to include other
22550cases if you wish. To use the rules, Calc builds the formula
22551@samp{thecoefs(x, [a, b, c, ...])} where @code{x} is the polynomial
22552base variable and @code{a}, @code{b}, etc., are polynomial coefficients
22553(which may be numbers or formulas). The constant term is written first,
22554i.e., in the @code{a} position. When the rules complete, they should have
22555changed the formula into the form @samp{thefactors(x, [f1, f2, f3, ...])}
22556where each @code{fi} should be a factored term, e.g., @samp{x - ai}.
22557Calc then multiplies these terms together to get the complete
22558factored form of the polynomial. If the rules do not change the
22559@code{thecoefs} call to a @code{thefactors} call, @kbd{a f} leaves the
22560polynomial alone on the assumption that it is unfactorable. (Note that
22561the function names @code{thecoefs} and @code{thefactors} are used only
22562as placeholders; there are no actual Calc functions by those names.)
22563
22564@kindex H a f
22565@tindex factors
22566The @kbd{H a f} [@code{factors}] command also factors a polynomial,
22567but it returns a list of factors instead of an expression which is the
22568product of the factors. Each factor is represented by a sub-vector
22569of the factor, and the power with which it appears. For example,
22570@cite{x^5 + x^4 - 33 x^3 + 63 x^2} factors to @cite{(x + 7) x^2 (x - 3)^2}
22571in @kbd{a f}, or to @cite{[ [x, 2], [x+7, 1], [x-3, 2] ]} in @kbd{H a f}.
22572If there is an overall numeric factor, it always comes first in the list.
22573The functions @code{factor} and @code{factors} allow a second argument
22574when written in algebraic form; @samp{factor(x,v)} factors @cite{x} with
22575respect to the specific variable @cite{v}. The default is to factor with
22576respect to all the variables that appear in @cite{x}.
22577
22578@kindex a c
22579@pindex calc-collect
22580@tindex collect
22581The @kbd{a c} (@code{calc-collect}) [@code{collect}] command rearranges a
22582formula as a
22583polynomial in a given variable, ordered in decreasing powers of that
22584variable. For example, given @cite{1 + 2 x + 3 y + 4 x y^2} on
22585the stack, @kbd{a c x} would produce @cite{(2 + 4 y^2) x + (1 + 3 y)},
22586and @kbd{a c y} would produce @cite{(4 x) y^2 + 3 y + (1 + 2 x)}.
22587The polynomial will be expanded out using the distributive law as
22588necessary: Collecting @cite{x} in @cite{(x - 1)^3} produces
22589@cite{x^3 - 3 x^2 + 3 x - 1}. Terms not involving @cite{x} will
22590not be expanded.
22591
22592The ``variable'' you specify at the prompt can actually be any
22593expression: @kbd{a c ln(x+1)} will collect together all terms multiplied
22594by @samp{ln(x+1)} or integer powers thereof. If @samp{x} also appears
22595in the formula in a context other than @samp{ln(x+1)}, @kbd{a c} will
22596treat those occurrences as unrelated to @samp{ln(x+1)}, i.e., as constants.
22597
22598@kindex a x
22599@pindex calc-expand
22600@tindex expand
22601The @kbd{a x} (@code{calc-expand}) [@code{expand}] command expands an
22602expression by applying the distributive law everywhere. It applies to
22603products, quotients, and powers involving sums. By default, it fully
22604distributes all parts of the expression. With a numeric prefix argument,
22605the distributive law is applied only the specified number of times, then
22606the partially expanded expression is left on the stack.
22607
22608The @kbd{a x} and @kbd{j D} commands are somewhat redundant. Use
22609@kbd{a x} if you want to expand all products of sums in your formula.
22610Use @kbd{j D} if you want to expand a particular specified term of
22611the formula. There is an exactly analogous correspondence between
22612@kbd{a f} and @kbd{j M}. (The @kbd{j D} and @kbd{j M} commands
22613also know many other kinds of expansions, such as
22614@samp{exp(a + b) = exp(a) exp(b)}, which @kbd{a x} and @kbd{a f}
22615do not do.)
22616
22617Calc's automatic simplifications will sometimes reverse a partial
22618expansion. For example, the first step in expanding @cite{(x+1)^3} is
22619to write @cite{(x+1) (x+1)^2}. If @kbd{a x} stops there and tries
22620to put this formula onto the stack, though, Calc will automatically
22621simplify it back to @cite{(x+1)^3} form. The solution is to turn
22622simplification off first (@pxref{Simplification Modes}), or to run
22623@kbd{a x} without a numeric prefix argument so that it expands all
22624the way in one step.
22625
22626@kindex a a
22627@pindex calc-apart
22628@tindex apart
22629The @kbd{a a} (@code{calc-apart}) [@code{apart}] command expands a
22630rational function by partial fractions. A rational function is the
22631quotient of two polynomials; @code{apart} pulls this apart into a
22632sum of rational functions with simple denominators. In algebraic
22633notation, the @code{apart} function allows a second argument that
22634specifies which variable to use as the ``base''; by default, Calc
22635chooses the base variable automatically.
22636
22637@kindex a n
22638@pindex calc-normalize-rat
22639@tindex nrat
22640The @kbd{a n} (@code{calc-normalize-rat}) [@code{nrat}] command
22641attempts to arrange a formula into a quotient of two polynomials.
22642For example, given @cite{1 + (a + b/c) / d}, the result would be
22643@cite{(b + a c + c d) / c d}. The quotient is reduced, so that
22644@kbd{a n} will simplify @cite{(x^2 + 2x + 1) / (x^2 - 1)} by dividing
22645out the common factor @cite{x + 1}, yielding @cite{(x + 1) / (x - 1)}.
22646
22647@kindex a \
22648@pindex calc-poly-div
22649@tindex pdiv
22650The @kbd{a \} (@code{calc-poly-div}) [@code{pdiv}] command divides
22651two polynomials @cite{u} and @cite{v}, yielding a new polynomial
22652@cite{q}. If several variables occur in the inputs, the inputs are
22653considered multivariate polynomials. (Calc divides by the variable
22654with the largest power in @cite{u} first, or, in the case of equal
22655powers, chooses the variables in alphabetical order.) For example,
22656dividing @cite{x^2 + 3 x + 2} by @cite{x + 2} yields @cite{x + 1}.
22657The remainder from the division, if any, is reported at the bottom
22658of the screen and is also placed in the Trail along with the quotient.
22659
22660Using @code{pdiv} in algebraic notation, you can specify the particular
22661variable to be used as the base: `@t{pdiv(}@i{a}@t{,}@i{b}@t{,}@i{x}@t{)}'.
22662If @code{pdiv} is given only two arguments (as is always the case with
22663the @kbd{a \} command), then it does a multivariate division as outlined
22664above.
22665
22666@kindex a %
22667@pindex calc-poly-rem
22668@tindex prem
22669The @kbd{a %} (@code{calc-poly-rem}) [@code{prem}] command divides
22670two polynomials and keeps the remainder @cite{r}. The quotient
22671@cite{q} is discarded. For any formulas @cite{a} and @cite{b}, the
22672results of @kbd{a \} and @kbd{a %} satisfy @cite{a = q b + r}.
22673(This is analogous to plain @kbd{\} and @kbd{%}, which compute the
22674integer quotient and remainder from dividing two numbers.)
22675
22676@kindex a /
22677@kindex H a /
22678@pindex calc-poly-div-rem
22679@tindex pdivrem
22680@tindex pdivide
22681The @kbd{a /} (@code{calc-poly-div-rem}) [@code{pdivrem}] command
22682divides two polynomials and reports both the quotient and the
22683remainder as a vector @cite{[q, r]}. The @kbd{H a /} [@code{pdivide}]
22684command divides two polynomials and constructs the formula
22685@cite{q + r/b} on the stack. (Naturally if the remainder is zero,
22686this will immediately simplify to @cite{q}.)
22687
22688@kindex a g
22689@pindex calc-poly-gcd
22690@tindex pgcd
22691The @kbd{a g} (@code{calc-poly-gcd}) [@code{pgcd}] command computes
22692the greatest common divisor of two polynomials. (The GCD actually
22693is unique only to within a constant multiplier; Calc attempts to
22694choose a GCD which will be unsurprising.) For example, the @kbd{a n}
22695command uses @kbd{a g} to take the GCD of the numerator and denominator
22696of a quotient, then divides each by the result using @kbd{a \}. (The
22697definition of GCD ensures that this division can take place without
22698leaving a remainder.)
22699
22700While the polynomials used in operations like @kbd{a /} and @kbd{a g}
22701often have integer coefficients, this is not required. Calc can also
22702deal with polynomials over the rationals or floating-point reals.
22703Polynomials with modulo-form coefficients are also useful in many
22704applications; if you enter @samp{(x^2 + 3 x - 1) mod 5}, Calc
22705automatically transforms this into a polynomial over the field of
22706integers mod 5: @samp{(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)}.
22707
22708Congratulations and thanks go to Ove Ewerlid
22709(@code{ewerlid@@mizar.DoCS.UU.SE}), who contributed many of the
22710polynomial routines used in the above commands.
22711
22712@xref{Decomposing Polynomials}, for several useful functions for
22713extracting the individual coefficients of a polynomial.
22714
22715@node Calculus, Solving Equations, Polynomials, Algebra
22716@section Calculus
22717
22718@noindent
22719The following calculus commands do not automatically simplify their
22720inputs or outputs using @code{calc-simplify}. You may find it helps
22721to do this by hand by typing @kbd{a s} or @kbd{a e}. It may also help
22722to use @kbd{a x} and/or @kbd{a c} to arrange a result in the most
22723readable way.
22724
22725@menu
22726* Differentiation::
22727* Integration::
22728* Customizing the Integrator::
22729* Numerical Integration::
22730* Taylor Series::
22731@end menu
22732
22733@node Differentiation, Integration, Calculus, Calculus
22734@subsection Differentiation
22735
22736@noindent
22737@kindex a d
22738@kindex H a d
22739@pindex calc-derivative
22740@tindex deriv
22741@tindex tderiv
22742The @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes
22743the derivative of the expression on the top of the stack with respect to
22744some variable, which it will prompt you to enter. Normally, variables
22745in the formula other than the specified differentiation variable are
22746considered constant, i.e., @samp{deriv(y,x)} is reduced to zero. With
22747the Hyperbolic flag, the @code{tderiv} (total derivative) operation is used
22748instead, in which derivatives of variables are not reduced to zero
22749unless those variables are known to be ``constant,'' i.e., independent
22750of any other variables. (The built-in special variables like @code{pi}
22751are considered constant, as are variables that have been declared
22752@code{const}; @pxref{Declarations}.)
22753
22754With a numeric prefix argument @var{n}, this command computes the
22755@var{n}th derivative.
22756
22757When working with trigonometric functions, it is best to switch to
22758radians mode first (with @w{@kbd{m r}}). The derivative of @samp{sin(x)}
22759in degrees is @samp{(pi/180) cos(x)}, probably not the expected
22760answer!
22761
22762If you use the @code{deriv} function directly in an algebraic formula,
22763you can write @samp{deriv(f,x,x0)} which represents the derivative
22764of @cite{f} with respect to @cite{x}, evaluated at the point @c{$x=x_0$}
22765@cite{x=x0}.
22766
22767If the formula being differentiated contains functions which Calc does
22768not know, the derivatives of those functions are produced by adding
22769primes (apostrophe characters). For example, @samp{deriv(f(2x), x)}
22770produces @samp{2 f'(2 x)}, where the function @code{f'} represents the
22771derivative of @code{f}.
22772
22773For functions you have defined with the @kbd{Z F} command, Calc expands
22774the functions according to their defining formulas unless you have
22775also defined @code{f'} suitably. For example, suppose we define
22776@samp{sinc(x) = sin(x)/x} using @kbd{Z F}. If we then differentiate
22777the formula @samp{sinc(2 x)}, the formula will be expanded to
22778@samp{sin(2 x) / (2 x)} and differentiated. However, if we also
22779define @samp{sinc'(x) = dsinc(x)}, say, then Calc will write the
22780result as @samp{2 dsinc(2 x)}. @xref{Algebraic Definitions}.
22781
22782For multi-argument functions @samp{f(x,y,z)}, the derivative with respect
22783to the first argument is written @samp{f'(x,y,z)}; derivatives with
22784respect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}.
22785Various higher-order derivatives can be formed in the obvious way, e.g.,
22786@samp{f'@var{}'(x)} (the second derivative of @code{f}) or
22787@samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each
22788argument once).@refill
22789
22790@node Integration, Customizing the Integrator, Differentiation, Calculus
22791@subsection Integration
22792
22793@noindent
22794@kindex a i
22795@pindex calc-integral
22796@tindex integ
22797The @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the
22798indefinite integral of the expression on the top of the stack with
22799respect to a variable. The integrator is not guaranteed to work for
22800all integrable functions, but it is able to integrate several large
22801classes of formulas. In particular, any polynomial or rational function
22802(a polynomial divided by a polynomial) is acceptable. (Rational functions
22803don't have to be in explicit quotient form, however; @c{$x/(1+x^{-2})$}
22804@cite{x/(1+x^-2)}
22805is not strictly a quotient of polynomials, but it is equivalent to
22806@cite{x^3/(x^2+1)}, which is.) Also, square roots of terms involving
22807@cite{x} and @cite{x^2} may appear in rational functions being
22808integrated. Finally, rational functions involving trigonometric or
22809hyperbolic functions can be integrated.
22810
22811@ifinfo
22812If you use the @code{integ} function directly in an algebraic formula,
22813you can also write @samp{integ(f,x,v)} which expresses the resulting
22814indefinite integral in terms of variable @code{v} instead of @code{x}.
22815With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
22816integral from @code{a} to @code{b}.
22817@end ifinfo
22818@tex
22819If you use the @code{integ} function directly in an algebraic formula,
22820you can also write @samp{integ(f,x,v)} which expresses the resulting
22821indefinite integral in terms of variable @code{v} instead of @code{x}.
22822With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
22823integral $\int_a^b f(x) \, dx$.
22824@end tex
22825
22826Please note that the current implementation of Calc's integrator sometimes
22827produces results that are significantly more complex than they need to
22828be. For example, the integral Calc finds for @c{$1/(x+\sqrt{x^2+1})$}
22829@cite{1/(x+sqrt(x^2+1))}
22830is several times more complicated than the answer Mathematica
22831returns for the same input, although the two forms are numerically
22832equivalent. Also, any indefinite integral should be considered to have
22833an arbitrary constant of integration added to it, although Calc does not
22834write an explicit constant of integration in its result. For example,
22835Calc's solution for @c{$1/(1+\tan x)$}
22836@cite{1/(1+tan(x))} differs from the solution given
22837in the @emph{CRC Math Tables} by a constant factor of @c{$\pi i / 2$}
22838@cite{pi i / 2},
22839due to a different choice of constant of integration.
22840
22841The Calculator remembers all the integrals it has done. If conditions
22842change in a way that would invalidate the old integrals, say, a switch
22843from degrees to radians mode, then they will be thrown out. If you
22844suspect this is not happening when it should, use the
22845@code{calc-flush-caches} command; @pxref{Caches}.
22846
22847@vindex IntegLimit
22848Calc normally will pursue integration by substitution or integration by
22849parts up to 3 nested times before abandoning an approach as fruitless.
22850If the integrator is taking too long, you can lower this limit by storing
22851a number (like 2) in the variable @code{IntegLimit}. (The @kbd{s I}
22852command is a convenient way to edit @code{IntegLimit}.) If this variable
22853has no stored value or does not contain a nonnegative integer, a limit
22854of 3 is used. The lower this limit is, the greater the chance that Calc
22855will be unable to integrate a function it could otherwise handle. Raising
22856this limit allows the Calculator to solve more integrals, though the time
22857it takes may grow exponentially. You can monitor the integrator's actions
22858by creating an Emacs buffer called @code{*Trace*}. If such a buffer
22859exists, the @kbd{a i} command will write a log of its actions there.
22860
22861If you want to manipulate integrals in a purely symbolic way, you can
22862set the integration nesting limit to 0 to prevent all but fast
22863table-lookup solutions of integrals. You might then wish to define
22864rewrite rules for integration by parts, various kinds of substitutions,
22865and so on. @xref{Rewrite Rules}.
22866
22867@node Customizing the Integrator, Numerical Integration, Integration, Calculus
22868@subsection Customizing the Integrator
22869
22870@noindent
22871@vindex IntegRules
22872Calc has two built-in rewrite rules called @code{IntegRules} and
22873@code{IntegAfterRules} which you can edit to define new integration
22874methods. @xref{Rewrite Rules}. At each step of the integration process,
22875Calc wraps the current integrand in a call to the fictitious function
22876@samp{integtry(@var{expr},@var{var})}, where @var{expr} is the
22877integrand and @var{var} is the integration variable. If your rules
22878rewrite this to be a plain formula (not a call to @code{integtry}), then
22879Calc will use this formula as the integral of @var{expr}. For example,
22880the rule @samp{integtry(mysin(x),x) := -mycos(x)} would define a rule to
22881integrate a function @code{mysin} that acts like the sine function.
22882Then, putting @samp{4 mysin(2y+1)} on the stack and typing @kbd{a i y}
22883will produce the integral @samp{-2 mycos(2y+1)}. Note that Calc has
22884automatically made various transformations on the integral to allow it
22885to use your rule; integral tables generally give rules for
22886@samp{mysin(a x + b)}, but you don't need to use this much generality
22887in your @code{IntegRules}.
22888
22889@cindex Exponential integral Ei(x)
22890@c @starindex
22891@tindex Ei
22892As a more serious example, the expression @samp{exp(x)/x} cannot be
22893integrated in terms of the standard functions, so the ``exponential
22894integral'' function @c{${\rm Ei}(x)$}
22895@cite{Ei(x)} was invented to describe it.
22896We can get Calc to do this integral in terms of a made-up @code{Ei}
22897function by adding the rule @samp{[integtry(exp(x)/x, x) := Ei(x)]}
22898to @code{IntegRules}. Now entering @samp{exp(2x)/x} on the stack
22899and typing @kbd{a i x} yields @samp{Ei(2 x)}. This new rule will
22900work with Calc's various built-in integration methods (such as
22901integration by substitution) to solve a variety of other problems
22902involving @code{Ei}: For example, now Calc will also be able to
22903integrate @samp{exp(exp(x))} and @samp{ln(ln(x))} (to get @samp{Ei(exp(x))}
22904and @samp{x ln(ln(x)) - Ei(ln(x))}, respectively).
22905
22906Your rule may do further integration by calling @code{integ}. For
22907example, @samp{integtry(twice(u),x) := twice(integ(u))} allows Calc
22908to integrate @samp{twice(sin(x))} to get @samp{twice(-cos(x))}.
22909Note that @code{integ} was called with only one argument. This notation
22910is allowed only within @code{IntegRules}; it means ``integrate this
22911with respect to the same integration variable.'' If Calc is unable
22912to integrate @code{u}, the integration that invoked @code{IntegRules}
22913also fails. Thus integrating @samp{twice(f(x))} fails, returning the
22914unevaluated integral @samp{integ(twice(f(x)), x)}. It is still legal
22915to call @code{integ} with two or more arguments, however; in this case,
22916if @code{u} is not integrable, @code{twice} itself will still be
22917integrated: If the above rule is changed to @samp{... := twice(integ(u,x))},
22918then integrating @samp{twice(f(x))} will yield @samp{twice(integ(f(x),x))}.
22919
22920If a rule instead produces the formula @samp{integsubst(@var{sexpr},
22921@var{svar})}, either replacing the top-level @code{integtry} call or
22922nested anywhere inside the expression, then Calc will apply the
22923substitution @samp{@var{u} = @var{sexpr}(@var{svar})} to try to
22924integrate the original @var{expr}. For example, the rule
22925@samp{sqrt(a) := integsubst(sqrt(x),x)} says that if Calc ever finds
22926a square root in the integrand, it should attempt the substitution
22927@samp{u = sqrt(x)}. (This particular rule is unnecessary because
22928Calc always tries ``obvious'' substitutions where @var{sexpr} actually
22929appears in the integrand.) The variable @var{svar} may be the same
22930as the @var{var} that appeared in the call to @code{integtry}, but
22931it need not be.
22932
22933When integrating according to an @code{integsubst}, Calc uses the
22934equation solver to find the inverse of @var{sexpr} (if the integrand
22935refers to @var{var} anywhere except in subexpressions that exactly
22936match @var{sexpr}). It uses the differentiator to find the derivative
22937of @var{sexpr} and/or its inverse (it has two methods that use one
22938derivative or the other). You can also specify these items by adding
22939extra arguments to the @code{integsubst} your rules construct; the
22940general form is @samp{integsubst(@var{sexpr}, @var{svar}, @var{sinv},
22941@var{sprime})}, where @var{sinv} is the inverse of @var{sexpr} (still
22942written as a function of @var{svar}), and @var{sprime} is the
22943derivative of @var{sexpr} with respect to @var{svar}. If you don't
22944specify these things, and Calc is not able to work them out on its
22945own with the information it knows, then your substitution rule will
22946work only in very specific, simple cases.
22947
22948Calc applies @code{IntegRules} as if by @kbd{C-u 1 a r IntegRules};
22949in other words, Calc stops rewriting as soon as any rule in your rule
22950set succeeds. (If it weren't for this, the @samp{integsubst(sqrt(x),x)}
22951example above would keep on adding layers of @code{integsubst} calls
22952forever!)
22953
22954@vindex IntegSimpRules
22955Another set of rules, stored in @code{IntegSimpRules}, are applied
22956every time the integrator uses @kbd{a s} to simplify an intermediate
22957result. For example, putting the rule @samp{twice(x) := 2 x} into
22958@code{IntegSimpRules} would tell Calc to convert the @code{twice}
22959function into a form it knows whenever integration is attempted.
22960
22961One more way to influence the integrator is to define a function with
22962the @kbd{Z F} command (@pxref{Algebraic Definitions}). Calc's
22963integrator automatically expands such functions according to their
22964defining formulas, even if you originally asked for the function to
22965be left unevaluated for symbolic arguments. (Certain other Calc
22966systems, such as the differentiator and the equation solver, also
22967do this.)
22968
22969@vindex IntegAfterRules
22970Sometimes Calc is able to find a solution to your integral, but it
22971expresses the result in a way that is unnecessarily complicated. If
22972this happens, you can either use @code{integsubst} as described
22973above to try to hint at a more direct path to the desired result, or
22974you can use @code{IntegAfterRules}. This is an extra rule set that
22975runs after the main integrator returns its result; basically, Calc does
22976an @kbd{a r IntegAfterRules} on the result before showing it to you.
22977(It also does an @kbd{a s}, without @code{IntegSimpRules}, after that
22978to further simplify the result.) For example, Calc's integrator
22979sometimes produces expressions of the form @samp{ln(1+x) - ln(1-x)};
22980the default @code{IntegAfterRules} rewrite this into the more readable
22981form @samp{2 arctanh(x)}. Note that, unlike @code{IntegRules},
22982@code{IntegSimpRules} and @code{IntegAfterRules} are applied any number
22983of times until no further changes are possible. Rewriting by
22984@code{IntegAfterRules} occurs only after the main integrator has
22985finished, not at every step as for @code{IntegRules} and
22986@code{IntegSimpRules}.
22987
22988@node Numerical Integration, Taylor Series, Customizing the Integrator, Calculus
22989@subsection Numerical Integration
22990
22991@noindent
22992@kindex a I
22993@pindex calc-num-integral
22994@tindex ninteg
22995If you want a purely numerical answer to an integration problem, you can
22996use the @kbd{a I} (@code{calc-num-integral}) [@code{ninteg}] command. This
22997command prompts for an integration variable, a lower limit, and an
22998upper limit. Except for the integration variable, all other variables
22999that appear in the integrand formula must have stored values. (A stored
23000value, if any, for the integration variable itself is ignored.)
23001
23002Numerical integration works by evaluating your formula at many points in
23003the specified interval. Calc uses an ``open Romberg'' method; this means
23004that it does not evaluate the formula actually at the endpoints (so that
23005it is safe to integrate @samp{sin(x)/x} from zero, for example). Also,
23006the Romberg method works especially well when the function being
23007integrated is fairly smooth. If the function is not smooth, Calc will
23008have to evaluate it at quite a few points before it can accurately
23009determine the value of the integral.
23010
23011Integration is much faster when the current precision is small. It is
23012best to set the precision to the smallest acceptable number of digits
23013before you use @kbd{a I}. If Calc appears to be taking too long, press
23014@kbd{C-g} to halt it and try a lower precision. If Calc still appears
23015to need hundreds of evaluations, check to make sure your function is
23016well-behaved in the specified interval.
23017
23018It is possible for the lower integration limit to be @samp{-inf} (minus
23019infinity). Likewise, the upper limit may be plus infinity. Calc
23020internally transforms the integral into an equivalent one with finite
23021limits. However, integration to or across singularities is not supported:
23022The integral of @samp{1/sqrt(x)} from 0 to 1 exists (it can be found
23023by Calc's symbolic integrator, for example), but @kbd{a I} will fail
23024because the integrand goes to infinity at one of the endpoints.
23025
23026@node Taylor Series, , Numerical Integration, Calculus
23027@subsection Taylor Series
23028
23029@noindent
23030@kindex a t
23031@pindex calc-taylor
23032@tindex taylor
23033The @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a
23034power series expansion or Taylor series of a function. You specify the
23035variable and the desired number of terms. You may give an expression of
23036the form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} instead
23037of just a variable to produce a Taylor expansion about the point @var{a}.
23038You may specify the number of terms with a numeric prefix argument;
23039otherwise the command will prompt you for the number of terms. Note that
23040many series expansions have coefficients of zero for some terms, so you
23041may appear to get fewer terms than you asked for.@refill
23042
23043If the @kbd{a i} command is unable to find a symbolic integral for a
23044function, you can get an approximation by integrating the function's
23045Taylor series.
23046
23047@node Solving Equations, Numerical Solutions, Calculus, Algebra
23048@section Solving Equations
23049
23050@noindent
23051@kindex a S
23052@pindex calc-solve-for
23053@tindex solve
23054@cindex Equations, solving
23055@cindex Solving equations
23056The @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges
23057an equation to solve for a specific variable. An equation is an
23058expression of the form @cite{L = R}. For example, the command @kbd{a S x}
23059will rearrange @cite{y = 3x + 6} to the form, @cite{x = y/3 - 2}. If the
23060input is not an equation, it is treated like an equation of the
23061form @cite{X = 0}.
23062
23063This command also works for inequalities, as in @cite{y < 3x + 6}.
23064Some inequalities cannot be solved where the analogous equation could
23065be; for example, solving @c{$a < b \, c$}
23066@cite{a < b c} for @cite{b} is impossible
23067without knowing the sign of @cite{c}. In this case, @kbd{a S} will
23068produce the result @c{$b \mathbin{\hbox{\code{!=}}} a/c$}
23069@cite{b != a/c} (using the not-equal-to operator)
23070to signify that the direction of the inequality is now unknown. The
23071inequality @c{$a \le b \, c$}
23072@cite{a <= b c} is not even partially solved.
23073@xref{Declarations}, for a way to tell Calc that the signs of the
23074variables in a formula are in fact known.
23075
23076Two useful commands for working with the result of @kbd{a S} are
23077@kbd{a .} (@pxref{Logical Operations}), which converts @cite{x = y/3 - 2}
23078to @cite{y/3 - 2}, and @kbd{s l} (@pxref{Let Command}) which evaluates
23079another formula with @cite{x} set equal to @cite{y/3 - 2}.
23080
23081@menu
23082* Multiple Solutions::
23083* Solving Systems of Equations::
23084* Decomposing Polynomials::
23085@end menu
23086
23087@node Multiple Solutions, Solving Systems of Equations, Solving Equations, Solving Equations
23088@subsection Multiple Solutions
23089
23090@noindent
23091@kindex H a S
23092@tindex fsolve
23093Some equations have more than one solution. The Hyperbolic flag
23094(@code{H a S}) [@code{fsolve}] tells the solver to report the fully
23095general family of solutions. It will invent variables @code{n1},
23096@code{n2}, @dots{}, which represent independent arbitrary integers, and
23097@code{s1}, @code{s2}, @dots{}, which represent independent arbitrary
23098signs (either @i{+1} or @i{-1}). If you don't use the Hyperbolic
23099flag, Calc will use zero in place of all arbitrary integers, and plus
23100one in place of all arbitrary signs. Note that variables like @code{n1}
23101and @code{s1} are not given any special interpretation in Calc except by
23102the equation solver itself. As usual, you can use the @w{@kbd{s l}}
23103(@code{calc-let}) command to obtain solutions for various actual values
23104of these variables.
23105
23106For example, @kbd{' x^2 = y @key{RET} H a S x @key{RET}} solves to
23107get @samp{x = s1 sqrt(y)}, indicating that the two solutions to the
23108equation are @samp{sqrt(y)} and @samp{-sqrt(y)}. Another way to
23109think about it is that the square-root operation is really a
23110two-valued function; since every Calc function must return a
23111single result, @code{sqrt} chooses to return the positive result.
23112Then @kbd{H a S} doctors this result using @code{s1} to indicate
23113the full set of possible values of the mathematical square-root.
23114
23115There is a similar phenomenon going the other direction: Suppose
23116we solve @samp{sqrt(y) = x} for @code{y}. Calc squares both sides
23117to get @samp{y = x^2}. This is correct, except that it introduces
23118some dubious solutions. Consider solving @samp{sqrt(y) = -3}:
23119Calc will report @cite{y = 9} as a valid solution, which is true
23120in the mathematical sense of square-root, but false (there is no
23121solution) for the actual Calc positive-valued @code{sqrt}. This
23122happens for both @kbd{a S} and @kbd{H a S}.
23123
23124@cindex @code{GenCount} variable
23125@vindex GenCount
23126@c @starindex
23127@tindex an
23128@c @starindex
23129@tindex as
23130If you store a positive integer in the Calc variable @code{GenCount},
23131then Calc will generate formulas of the form @samp{as(@var{n})} for
23132arbitrary signs, and @samp{an(@var{n})} for arbitrary integers,
23133where @var{n} represents successive values taken by incrementing
23134@code{GenCount} by one. While the normal arbitrary sign and
23135integer symbols start over at @code{s1} and @code{n1} with each
23136new Calc command, the @code{GenCount} approach will give each
23137arbitrary value a name that is unique throughout the entire Calc
23138session. Also, the arbitrary values are function calls instead
23139of variables, which is advantageous in some cases. For example,
23140you can make a rewrite rule that recognizes all arbitrary signs
23141using a pattern like @samp{as(n)}. The @kbd{s l} command only works
23142on variables, but you can use the @kbd{a b} (@code{calc-substitute})
23143command to substitute actual values for function calls like @samp{as(3)}.
23144
23145The @kbd{s G} (@code{calc-edit-GenCount}) command is a convenient
23146way to create or edit this variable. Press @kbd{M-# M-#} to finish.
23147
23148If you have not stored a value in @code{GenCount}, or if the value
23149in that variable is not a positive integer, the regular
23150@code{s1}/@code{n1} notation is used.
23151
23152@kindex I a S
23153@kindex H I a S
23154@tindex finv
23155@tindex ffinv
23156With the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression
23157on top of the stack as a function of the specified variable and solves
23158to find the inverse function, written in terms of the same variable.
23159For example, @kbd{I a S x} inverts @cite{2x + 6} to @cite{x/2 - 3}.
23160You can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a
23161fully general inverse, as described above.
23162
23163@kindex a P
23164@pindex calc-poly-roots
23165@tindex roots
23166Some equations, specifically polynomials, have a known, finite number
23167of solutions. The @kbd{a P} (@code{calc-poly-roots}) [@code{roots}]
23168command uses @kbd{H a S} to solve an equation in general form, then, for
23169all arbitrary-sign variables like @code{s1}, and all arbitrary-integer
23170variables like @code{n1} for which @code{n1} only usefully varies over
23171a finite range, it expands these variables out to all their possible
23172values. The results are collected into a vector, which is returned.
23173For example, @samp{roots(x^4 = 1, x)} returns the four solutions
23174@samp{[1, -1, (0, 1), (0, -1)]}. Generally an @var{n}th degree
23175polynomial will always have @var{n} roots on the complex plane.
23176(If you have given a @code{real} declaration for the solution
23177variable, then only the real-valued solutions, if any, will be
23178reported; @pxref{Declarations}.)
23179
23180Note that because @kbd{a P} uses @kbd{H a S}, it is able to deliver
23181symbolic solutions if the polynomial has symbolic coefficients. Also
23182note that Calc's solver is not able to get exact symbolic solutions
23183to all polynomials. Polynomials containing powers up to @cite{x^4}
23184can always be solved exactly; polynomials of higher degree sometimes
23185can be: @cite{x^6 + x^3 + 1} is converted to @cite{(x^3)^2 + (x^3) + 1},
23186which can be solved for @cite{x^3} using the quadratic equation, and then
23187for @cite{x} by taking cube roots. But in many cases, like
23188@cite{x^6 + x + 1}, Calc does not know how to rewrite the polynomial
23189into a form it can solve. The @kbd{a P} command can still deliver a
23190list of numerical roots, however, provided that symbolic mode (@kbd{m s})
23191is not turned on. (If you work with symbolic mode on, recall that the
23192@kbd{N} (@code{calc-eval-num}) key is a handy way to reevaluate the
23193formula on the stack with symbolic mode temporarily off.) Naturally,
23194@kbd{a P} can only provide numerical roots if the polynomial coefficents
23195are all numbers (real or complex).
23196
23197@node Solving Systems of Equations, Decomposing Polynomials, Multiple Solutions, Solving Equations
23198@subsection Solving Systems of Equations
23199
23200@noindent
23201@cindex Systems of equations, symbolic
23202You can also use the commands described above to solve systems of
23203simultaneous equations. Just create a vector of equations, then
23204specify a vector of variables for which to solve. (You can omit
23205the surrounding brackets when entering the vector of variables
23206at the prompt.)
23207
23208For example, putting @samp{[x + y = a, x - y = b]} on the stack
23209and typing @kbd{a S x,y @key{RET}} produces the vector of solutions
23210@samp{[x = a - (a-b)/2, y = (a-b)/2]}. The result vector will
23211have the same length as the variables vector, and the variables
23212will be listed in the same order there. Note that the solutions
23213are not always simplified as far as possible; the solution for
23214@cite{x} here could be improved by an application of the @kbd{a n}
23215command.
23216
23217Calc's algorithm works by trying to eliminate one variable at a
23218time by solving one of the equations for that variable and then
23219substituting into the other equations. Calc will try all the
23220possibilities, but you can speed things up by noting that Calc
23221first tries to eliminate the first variable with the first
23222equation, then the second variable with the second equation,
23223and so on. It also helps to put the simpler (e.g., more linear)
23224equations toward the front of the list. Calc's algorithm will
23225solve any system of linear equations, and also many kinds of
23226nonlinear systems.
23227
23228@c @starindex
23229@tindex elim
23230Normally there will be as many variables as equations. If you
23231give fewer variables than equations (an ``over-determined'' system
23232of equations), Calc will find a partial solution. For example,
23233typing @kbd{a S y @key{RET}} with the above system of equations
23234would produce @samp{[y = a - x]}. There are now several ways to
23235express this solution in terms of the original variables; Calc uses
23236the first one that it finds. You can control the choice by adding
23237variable specifiers of the form @samp{elim(@var{v})} to the
23238variables list. This says that @var{v} should be eliminated from
23239the equations; the variable will not appear at all in the solution.
23240For example, typing @kbd{a S y,elim(x)} would yield
23241@samp{[y = a - (b+a)/2]}.
23242
23243If the variables list contains only @code{elim} specifiers,
23244Calc simply eliminates those variables from the equations
23245and then returns the resulting set of equations. For example,
23246@kbd{a S elim(x)} produces @samp{[a - 2 y = b]}. Every variable
23247eliminated will reduce the number of equations in the system
23248by one.
23249
23250Again, @kbd{a S} gives you one solution to the system of
23251equations. If there are several solutions, you can use @kbd{H a S}
23252to get a general family of solutions, or, if there is a finite
23253number of solutions, you can use @kbd{a P} to get a list. (In
23254the latter case, the result will take the form of a matrix where
23255the rows are different solutions and the columns correspond to the
23256variables you requested.)
23257
23258Another way to deal with certain kinds of overdetermined systems of
23259equations is the @kbd{a F} command, which does least-squares fitting
23260to satisfy the equations. @xref{Curve Fitting}.
23261
23262@node Decomposing Polynomials, , Solving Systems of Equations, Solving Equations
23263@subsection Decomposing Polynomials
23264
23265@noindent
23266@c @starindex
23267@tindex poly
23268The @code{poly} function takes a polynomial and a variable as
23269arguments, and returns a vector of polynomial coefficients (constant
23270coefficient first). For example, @samp{poly(x^3 + 2 x, x)} returns
23271@cite{[0, 2, 0, 1]}. If the input is not a polynomial in @cite{x},
23272the call to @code{poly} is left in symbolic form. If the input does
23273not involve the variable @cite{x}, the input is returned in a list
23274of length one, representing a polynomial with only a constant
23275coefficient. The call @samp{poly(x, x)} returns the vector @cite{[0, 1]}.
23276The last element of the returned vector is guaranteed to be nonzero;
23277note that @samp{poly(0, x)} returns the empty vector @cite{[]}.
23278Note also that @cite{x} may actually be any formula; for example,
23279@samp{poly(sin(x)^2 - sin(x) + 3, sin(x))} returns @cite{[3, -1, 1]}.
23280
23281@cindex Coefficients of polynomial
23282@cindex Degree of polynomial
23283To get the @cite{x^k} coefficient of polynomial @cite{p}, use
23284@samp{poly(p, x)_(k+1)}. To get the degree of polynomial @cite{p},
23285use @samp{vlen(poly(p, x)) - 1}. For example, @samp{poly((x+1)^4, x)}
23286returns @samp{[1, 4, 6, 4, 1]}, so @samp{poly((x+1)^4, x)_(2+1)}
23287gives the @cite{x^2} coefficient of this polynomial, 6.
23288
23289@c @starindex
23290@tindex gpoly
23291One important feature of the solver is its ability to recognize
23292formulas which are ``essentially'' polynomials. This ability is
23293made available to the user through the @code{gpoly} function, which
23294is used just like @code{poly}: @samp{gpoly(@var{expr}, @var{var})}.
23295If @var{expr} is a polynomial in some term which includes @var{var}, then
23296this function will return a vector @samp{[@var{x}, @var{c}, @var{a}]}
23297where @var{x} is the term that depends on @var{var}, @var{c} is a
23298vector of polynomial coefficients (like the one returned by @code{poly}),
23299and @var{a} is a multiplier which is usually 1. Basically,
23300@samp{@var{expr} = @var{a}*(@var{c}_1 + @var{c}_2 @var{x} +
23301@var{c}_3 @var{x}^2 + ...)}. The last element of @var{c} is
23302guaranteed to be non-zero, and @var{c} will not equal @samp{[1]}
23303(i.e., the trivial decomposition @var{expr} = @var{x} is not
23304considered a polynomial). One side effect is that @samp{gpoly(x, x)}
23305and @samp{gpoly(6, x)}, both of which might be expected to recognize
23306their arguments as polynomials, will not because the decomposition
23307is considered trivial.
23308
23309For example, @samp{gpoly((x-2)^2, x)} returns @samp{[x, [4, -4, 1], 1]},
23310since the expanded form of this polynomial is @cite{4 - 4 x + x^2}.
23311
23312The term @var{x} may itself be a polynomial in @var{var}. This is
23313done to reduce the size of the @var{c} vector. For example,
23314@samp{gpoly(x^4 + x^2 - 1, x)} returns @samp{[x^2, [-1, 1, 1], 1]},
23315since a quadratic polynomial in @cite{x^2} is easier to solve than
23316a quartic polynomial in @cite{x}.
23317
23318A few more examples of the kinds of polynomials @code{gpoly} can
23319discover:
23320
23321@smallexample
23322sin(x) - 1 [sin(x), [-1, 1], 1]
23323x + 1/x - 1 [x, [1, -1, 1], 1/x]
23324x + 1/x [x^2, [1, 1], 1/x]
23325x^3 + 2 x [x^2, [2, 1], x]
23326x + x^2:3 + sqrt(x) [x^1:6, [1, 1, 0, 1], x^1:2]
23327x^(2a) + 2 x^a + 5 [x^a, [5, 2, 1], 1]
23328(exp(-x) + exp(x)) / 2 [e^(2 x), [0.5, 0.5], e^-x]
23329@end smallexample
23330
23331The @code{poly} and @code{gpoly} functions accept a third integer argument
23332which specifies the largest degree of polynomial that is acceptable.
23333If this is @cite{n}, then only @var{c} vectors of length @cite{n+1}
23334or less will be returned. Otherwise, the @code{poly} or @code{gpoly}
23335call will remain in symbolic form. For example, the equation solver
23336can handle quartics and smaller polynomials, so it calls
23337@samp{gpoly(@var{expr}, @var{var}, 4)} to discover whether @var{expr}
23338can be treated by its linear, quadratic, cubic, or quartic formulas.
23339
23340@c @starindex
23341@tindex pdeg
23342The @code{pdeg} function computes the degree of a polynomial;
23343@samp{pdeg(p,x)} is the highest power of @code{x} that appears in
23344@code{p}. This is the same as @samp{vlen(poly(p,x))-1}, but is
23345much more efficient. If @code{p} is constant with respect to @code{x},
23346then @samp{pdeg(p,x) = 0}. If @code{p} is not a polynomial in @code{x}
23347(e.g., @samp{pdeg(2 cos(x), x)}, the function remains unevaluated.
23348It is possible to omit the second argument @code{x}, in which case
23349@samp{pdeg(p)} returns the highest total degree of any term of the
23350polynomial, counting all variables that appear in @code{p}. Note
23351that @code{pdeg(c) = pdeg(c,x) = 0} for any nonzero constant @code{c};
23352the degree of the constant zero is considered to be @code{-inf}
23353(minus infinity).
23354
23355@c @starindex
23356@tindex plead
23357The @code{plead} function finds the leading term of a polynomial.
23358Thus @samp{plead(p,x)} is equivalent to @samp{poly(p,x)_vlen(poly(p,x))},
23359though again more efficient. In particular, @samp{plead((2x+1)^10, x)}
23360returns 1024 without expanding out the list of coefficients. The
23361value of @code{plead(p,x)} will be zero only if @cite{p = 0}.
23362
23363@c @starindex
23364@tindex pcont
23365The @code{pcont} function finds the @dfn{content} of a polynomial. This
23366is the greatest common divisor of all the coefficients of the polynomial.
23367With two arguments, @code{pcont(p,x)} effectively uses @samp{poly(p,x)}
23368to get a list of coefficients, then uses @code{pgcd} (the polynomial
23369GCD function) to combine these into an answer. For example,
23370@samp{pcont(4 x y^2 + 6 x^2 y, x)} is @samp{2 y}. The content is
23371basically the ``biggest'' polynomial that can be divided into @code{p}
23372exactly. The sign of the content is the same as the sign of the leading
23373coefficient.
23374
23375With only one argument, @samp{pcont(p)} computes the numerical
23376content of the polynomial, i.e., the @code{gcd} of the numerical
23377coefficients of all the terms in the formula. Note that @code{gcd}
23378is defined on rational numbers as well as integers; it computes
23379the @code{gcd} of the numerators and the @code{lcm} of the
23380denominators. Thus @samp{pcont(4:3 x y^2 + 6 x^2 y)} returns 2:3.
23381Dividing the polynomial by this number will clear all the
23382denominators, as well as dividing by any common content in the
23383numerators. The numerical content of a polynomial is negative only
23384if all the coefficients in the polynomial are negative.
23385
23386@c @starindex
23387@tindex pprim
23388The @code{pprim} function finds the @dfn{primitive part} of a
23389polynomial, which is simply the polynomial divided (using @code{pdiv}
23390if necessary) by its content. If the input polynomial has rational
23391coefficients, the result will have integer coefficients in simplest
23392terms.
23393
23394@node Numerical Solutions, Curve Fitting, Solving Equations, Algebra
23395@section Numerical Solutions
23396
23397@noindent
23398Not all equations can be solved symbolically. The commands in this
23399section use numerical algorithms that can find a solution to a specific
23400instance of an equation to any desired accuracy. Note that the
23401numerical commands are slower than their algebraic cousins; it is a
23402good idea to try @kbd{a S} before resorting to these commands.
23403
23404(@xref{Curve Fitting}, for some other, more specialized, operations
23405on numerical data.)
23406
23407@menu
23408* Root Finding::
23409* Minimization::
23410* Numerical Systems of Equations::
23411@end menu
23412
23413@node Root Finding, Minimization, Numerical Solutions, Numerical Solutions
23414@subsection Root Finding
23415
23416@noindent
23417@kindex a R
23418@pindex calc-find-root
23419@tindex root
23420@cindex Newton's method
23421@cindex Roots of equations
23422@cindex Numerical root-finding
23423The @kbd{a R} (@code{calc-find-root}) [@code{root}] command finds a
23424numerical solution (or @dfn{root}) of an equation. (This command treats
23425inequalities the same as equations. If the input is any other kind
23426of formula, it is interpreted as an equation of the form @cite{X = 0}.)
23427
23428The @kbd{a R} command requires an initial guess on the top of the
23429stack, and a formula in the second-to-top position. It prompts for a
23430solution variable, which must appear in the formula. All other variables
23431that appear in the formula must have assigned values, i.e., when
23432a value is assigned to the solution variable and the formula is
23433evaluated with @kbd{=}, it should evaluate to a number. Any assigned
23434value for the solution variable itself is ignored and unaffected by
23435this command.
23436
23437When the command completes, the initial guess is replaced on the stack
23438by a vector of two numbers: The value of the solution variable that
23439solves the equation, and the difference between the lefthand and
23440righthand sides of the equation at that value. Ordinarily, the second
23441number will be zero or very nearly zero. (Note that Calc uses a
23442slightly higher precision while finding the root, and thus the second
23443number may be slightly different from the value you would compute from
23444the equation yourself.)
23445
23446The @kbd{v h} (@code{calc-head}) command is a handy way to extract
23447the first element of the result vector, discarding the error term.
23448
23449The initial guess can be a real number, in which case Calc searches
23450for a real solution near that number, or a complex number, in which
23451case Calc searches the whole complex plane near that number for a
23452solution, or it can be an interval form which restricts the search
23453to real numbers inside that interval.
23454
23455Calc tries to use @kbd{a d} to take the derivative of the equation.
23456If this succeeds, it uses Newton's method. If the equation is not
23457differentiable Calc uses a bisection method. (If Newton's method
23458appears to be going astray, Calc switches over to bisection if it
23459can, or otherwise gives up. In this case it may help to try again
23460with a slightly different initial guess.) If the initial guess is a
23461complex number, the function must be differentiable.
23462
23463If the formula (or the difference between the sides of an equation)
23464is negative at one end of the interval you specify and positive at
23465the other end, the root finder is guaranteed to find a root.
23466Otherwise, Calc subdivides the interval into small parts looking for
23467positive and negative values to bracket the root. When your guess is
23468an interval, Calc will not look outside that interval for a root.
23469
23470@kindex H a R
23471@tindex wroot
23472The @kbd{H a R} [@code{wroot}] command is similar to @kbd{a R}, except
23473that if the initial guess is an interval for which the function has
23474the same sign at both ends, then rather than subdividing the interval
23475Calc attempts to widen it to enclose a root. Use this mode if
23476you are not sure if the function has a root in your interval.
23477
23478If the function is not differentiable, and you give a simple number
23479instead of an interval as your initial guess, Calc uses this widening
23480process even if you did not type the Hyperbolic flag. (If the function
23481@emph{is} differentiable, Calc uses Newton's method which does not
23482require a bounding interval in order to work.)
23483
23484If Calc leaves the @code{root} or @code{wroot} function in symbolic
23485form on the stack, it will normally display an explanation for why
23486no root was found. If you miss this explanation, press @kbd{w}
23487(@code{calc-why}) to get it back.
23488
23489@node Minimization, Numerical Systems of Equations, Root Finding, Numerical Solutions
23490@subsection Minimization
23491
23492@noindent
23493@kindex a N
23494@kindex H a N
23495@kindex a X
23496@kindex H a X
23497@pindex calc-find-minimum
23498@pindex calc-find-maximum
23499@tindex minimize
23500@tindex maximize
23501@cindex Minimization, numerical
23502The @kbd{a N} (@code{calc-find-minimum}) [@code{minimize}] command
23503finds a minimum value for a formula. It is very similar in operation
23504to @kbd{a R} (@code{calc-find-root}): You give the formula and an initial
23505guess on the stack, and are prompted for the name of a variable. The guess
23506may be either a number near the desired minimum, or an interval enclosing
23507the desired minimum. The function returns a vector containing the
23508value of the the variable which minimizes the formula's value, along
23509with the minimum value itself.
23510
23511Note that this command looks for a @emph{local} minimum. Many functions
23512have more than one minimum; some, like @c{$x \sin x$}
23513@cite{x sin(x)}, have infinitely
23514many. In fact, there is no easy way to define the ``global'' minimum
23515of @c{$x \sin x$}
23516@cite{x sin(x)} but Calc can still locate any particular local minimum
23517for you. Calc basically goes downhill from the initial guess until it
23518finds a point at which the function's value is greater both to the left
23519and to the right. Calc does not use derivatives when minimizing a function.
23520
23521If your initial guess is an interval and it looks like the minimum
23522occurs at one or the other endpoint of the interval, Calc will return
23523that endpoint only if that endpoint is closed; thus, minimizing @cite{17 x}
23524over @cite{[2..3]} will return @cite{[2, 38]}, but minimizing over
23525@cite{(2..3]} would report no minimum found. In general, you should
23526use closed intervals to find literally the minimum value in that
23527range of @cite{x}, or open intervals to find the local minimum, if
23528any, that happens to lie in that range.
23529
23530Most functions are smooth and flat near their minimum values. Because
23531of this flatness, if the current precision is, say, 12 digits, the
23532variable can only be determined meaningfully to about six digits. Thus
23533you should set the precision to twice as many digits as you need in your
23534answer.
23535
23536@c @mindex wmin@idots
23537@tindex wminimize
23538@c @mindex wmax@idots
23539@tindex wmaximize
23540The @kbd{H a N} [@code{wminimize}] command, analogously to @kbd{H a R},
23541expands the guess interval to enclose a minimum rather than requiring
23542that the minimum lie inside the interval you supply.
23543
23544The @kbd{a X} (@code{calc-find-maximum}) [@code{maximize}] and
23545@kbd{H a X} [@code{wmaximize}] commands effectively minimize the
23546negative of the formula you supply.
23547
23548The formula must evaluate to a real number at all points inside the
23549interval (or near the initial guess if the guess is a number). If
23550the initial guess is a complex number the variable will be minimized
23551over the complex numbers; if it is real or an interval it will
23552be minimized over the reals.
23553
23554@node Numerical Systems of Equations, , Minimization, Numerical Solutions
23555@subsection Systems of Equations
23556
23557@noindent
23558@cindex Systems of equations, numerical
23559The @kbd{a R} command can also solve systems of equations. In this
23560case, the equation should instead be a vector of equations, the
23561guess should instead be a vector of numbers (intervals are not
23562supported), and the variable should be a vector of variables. You
23563can omit the brackets while entering the list of variables. Each
23564equation must be differentiable by each variable for this mode to
23565work. The result will be a vector of two vectors: The variable
23566values that solved the system of equations, and the differences
23567between the sides of the equations with those variable values.
23568There must be the same number of equations as variables. Since
23569only plain numbers are allowed as guesses, the Hyperbolic flag has
23570no effect when solving a system of equations.
23571
23572It is also possible to minimize over many variables with @kbd{a N}
23573(or maximize with @kbd{a X}). Once again the variable name should
23574be replaced by a vector of variables, and the initial guess should
23575be an equal-sized vector of initial guesses. But, unlike the case of
23576multidimensional @kbd{a R}, the formula being minimized should
23577still be a single formula, @emph{not} a vector. Beware that
23578multidimensional minimization is currently @emph{very} slow.
23579
23580@node Curve Fitting, Summations, Numerical Solutions, Algebra
23581@section Curve Fitting
23582
23583@noindent
23584The @kbd{a F} command fits a set of data to a @dfn{model formula},
23585such as @cite{y = m x + b} where @cite{m} and @cite{b} are parameters
23586to be determined. For a typical set of measured data there will be
23587no single @cite{m} and @cite{b} that exactly fit the data; in this
23588case, Calc chooses values of the parameters that provide the closest
23589possible fit.
23590
23591@menu
23592* Linear Fits::
23593* Polynomial and Multilinear Fits::
23594* Error Estimates for Fits::
23595* Standard Nonlinear Models::
23596* Curve Fitting Details::
23597* Interpolation::
23598@end menu
23599
23600@node Linear Fits, Polynomial and Multilinear Fits, Curve Fitting, Curve Fitting
23601@subsection Linear Fits
23602
23603@noindent
23604@kindex a F
23605@pindex calc-curve-fit
23606@tindex fit
23607@cindex Linear regression
23608@cindex Least-squares fits
23609The @kbd{a F} (@code{calc-curve-fit}) [@code{fit}] command attempts
23610to fit a set of data (@cite{x} and @cite{y} vectors of numbers) to a
23611straight line, polynomial, or other function of @cite{x}. For the
23612moment we will consider only the case of fitting to a line, and we
23613will ignore the issue of whether or not the model was in fact a good
23614fit for the data.
23615
23616In a standard linear least-squares fit, we have a set of @cite{(x,y)}
23617data points that we wish to fit to the model @cite{y = m x + b}
23618by adjusting the parameters @cite{m} and @cite{b} to make the @cite{y}
23619values calculated from the formula be as close as possible to the actual
23620@cite{y} values in the data set. (In a polynomial fit, the model is
23621instead, say, @cite{y = a x^3 + b x^2 + c x + d}. In a multilinear fit,
23622we have data points of the form @cite{(x_1,x_2,x_3,y)} and our model is
23623@cite{y = a x_1 + b x_2 + c x_3 + d}. These will be discussed later.)
23624
23625In the model formula, variables like @cite{x} and @cite{x_2} are called
23626the @dfn{independent variables}, and @cite{y} is the @dfn{dependent
23627variable}. Variables like @cite{m}, @cite{a}, and @cite{b} are called
23628the @dfn{parameters} of the model.
23629
23630The @kbd{a F} command takes the data set to be fitted from the stack.
23631By default, it expects the data in the form of a matrix. For example,
23632for a linear or polynomial fit, this would be a @c{$2\times N$}
23633@asis{2xN} matrix where
23634the first row is a list of @cite{x} values and the second row has the
23635corresponding @cite{y} values. For the multilinear fit shown above,
23636the matrix would have four rows (@cite{x_1}, @cite{x_2}, @cite{x_3}, and
23637@cite{y}, respectively).
23638
23639If you happen to have an @c{$N\times2$}
23640@asis{Nx2} matrix instead of a @c{$2\times N$}
23641@asis{2xN} matrix,
23642just press @kbd{v t} first to transpose the matrix.
23643
23644After you type @kbd{a F}, Calc prompts you to select a model. For a
23645linear fit, press the digit @kbd{1}.
23646
23647Calc then prompts for you to name the variables. By default it chooses
23648high letters like @cite{x} and @cite{y} for independent variables and
23649low letters like @cite{a} and @cite{b} for parameters. (The dependent
23650variable doesn't need a name.) The two kinds of variables are separated
23651by a semicolon. Since you generally care more about the names of the
23652independent variables than of the parameters, Calc also allows you to
23653name only those and let the parameters use default names.
23654
23655For example, suppose the data matrix
23656
23657@ifinfo
23658@group
23659@example
23660[ [ 1, 2, 3, 4, 5 ]
23661 [ 5, 7, 9, 11, 13 ] ]
23662@end example
23663@end group
23664@end ifinfo
23665@tex
23666\turnoffactive
23667\turnoffactive
23668\beforedisplay
23669$$ \pmatrix{ 1 & 2 & 3 & 4 & 5 \cr
23670 5 & 7 & 9 & 11 & 13 }
23671$$
23672\afterdisplay
23673@end tex
23674
23675@noindent
23676is on the stack and we wish to do a simple linear fit. Type
23677@kbd{a F}, then @kbd{1} for the model, then @kbd{RET} to use
23678the default names. The result will be the formula @cite{3 + 2 x}
23679on the stack. Calc has created the model expression @kbd{a + b x},
23680then found the optimal values of @cite{a} and @cite{b} to fit the
23681data. (In this case, it was able to find an exact fit.) Calc then
23682substituted those values for @cite{a} and @cite{b} in the model
23683formula.
23684
23685The @kbd{a F} command puts two entries in the trail. One is, as
23686always, a copy of the result that went to the stack; the other is
23687a vector of the actual parameter values, written as equations:
23688@cite{[a = 3, b = 2]}, in case you'd rather read them in a list
23689than pick them out of the formula. (You can type @kbd{t y}
23690to move this vector to the stack; @pxref{Trail Commands}.)
23691
23692Specifying a different independent variable name will affect the
23693resulting formula: @kbd{a F 1 k RET} produces @kbd{3 + 2 k}.
23694Changing the parameter names (say, @kbd{a F 1 k;b,m RET}) will affect
23695the equations that go into the trail.
23696
23697@tex
23698\bigskip
23699@end tex
23700
23701To see what happens when the fit is not exact, we could change
23702the number 13 in the data matrix to 14 and try the fit again.
23703The result is:
23704
23705@example
237062.6 + 2.2 x
23707@end example
23708
23709Evaluating this formula, say with @kbd{v x 5 RET TAB V M $ RET}, shows
23710a reasonably close match to the y-values in the data.
23711
23712@example
23713[4.8, 7., 9.2, 11.4, 13.6]
23714@end example
23715
23716Since there is no line which passes through all the @i{N} data points,
23717Calc has chosen a line that best approximates the data points using
23718the method of least squares. The idea is to define the @dfn{chi-square}
23719error measure
23720
23721@ifinfo
23722@example
23723chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
23724@end example
23725@end ifinfo
23726@tex
23727\turnoffactive
23728\beforedisplay
23729$$ \chi^2 = \sum_{i=1}^N (y_i - (a + b x_i))^2 $$
23730\afterdisplay
23731@end tex
23732
23733@noindent
23734which is clearly zero if @cite{a + b x} exactly fits all data points,
23735and increases as various @cite{a + b x_i} values fail to match the
23736corresponding @cite{y_i} values. There are several reasons why the
23737summand is squared, one of them being to ensure that @c{$\chi^2 \ge 0$}
23738@cite{chi^2 >= 0}.
23739Least-squares fitting simply chooses the values of @cite{a} and @cite{b}
23740for which the error @c{$\chi^2$}
23741@cite{chi^2} is as small as possible.
23742
23743Other kinds of models do the same thing but with a different model
23744formula in place of @cite{a + b x_i}.
23745
23746@tex
23747\bigskip
23748@end tex
23749
23750A numeric prefix argument causes the @kbd{a F} command to take the
23751data in some other form than one big matrix. A positive argument @i{N}
23752will take @i{N} items from the stack, corresponding to the @i{N} rows
23753of a data matrix. In the linear case, @i{N} must be 2 since there
23754is always one independent variable and one dependent variable.
23755
23756A prefix of zero or plain @kbd{C-u} is a compromise; Calc takes two
23757items from the stack, an @i{N}-row matrix of @cite{x} values, and a
23758vector of @cite{y} values. If there is only one independent variable,
23759the @cite{x} values can be either a one-row matrix or a plain vector,
23760in which case the @kbd{C-u} prefix is the same as a @w{@kbd{C-u 2}} prefix.
23761
23762@node Polynomial and Multilinear Fits, Error Estimates for Fits, Linear Fits, Curve Fitting
23763@subsection Polynomial and Multilinear Fits
23764
23765@noindent
23766To fit the data to higher-order polynomials, just type one of the
23767digits @kbd{2} through @kbd{9} when prompted for a model. For example,
23768we could fit the original data matrix from the previous section
23769(with 13, not 14) to a parabola instead of a line by typing
23770@kbd{a F 2 RET}.
23771
23772@example
237732.00000000001 x - 1.5e-12 x^2 + 2.99999999999
23774@end example
23775
23776Note that since the constant and linear terms are enough to fit the
23777data exactly, it's no surprise that Calc chose a tiny contribution
23778for @cite{x^2}. (The fact that it's not exactly zero is due only
23779to roundoff error. Since our data are exact integers, we could get
23780an exact answer by typing @kbd{m f} first to get fraction mode.
23781Then the @cite{x^2} term would vanish altogether. Usually, though,
23782the data being fitted will be approximate floats so fraction mode
23783won't help.)
23784
23785Doing the @kbd{a F 2} fit on the data set with 14 instead of 13
23786gives a much larger @cite{x^2} contribution, as Calc bends the
23787line slightly to improve the fit.
23788
23789@example
237900.142857142855 x^2 + 1.34285714287 x + 3.59999999998
23791@end example
23792
23793An important result from the theory of polynomial fitting is that it
23794is always possible to fit @i{N} data points exactly using a polynomial
23795of degree @i{N-1}, sometimes called an @dfn{interpolating polynomial}.
23796Using the modified (14) data matrix, a model number of 4 gives
23797a polynomial that exactly matches all five data points:
23798
23799@example
238000.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
23801@end example
23802
23803The actual coefficients we get with a precision of 12, like
23804@cite{0.0416666663588}, clearly suffer from loss of precision.
23805It is a good idea to increase the working precision to several
23806digits beyond what you need when you do a fitting operation.
23807Or, if your data are exact, use fraction mode to get exact
23808results.
23809
23810You can type @kbd{i} instead of a digit at the model prompt to fit
23811the data exactly to a polynomial. This just counts the number of
23812columns of the data matrix to choose the degree of the polynomial
23813automatically.
23814
23815Fitting data ``exactly'' to high-degree polynomials is not always
23816a good idea, though. High-degree polynomials have a tendency to
23817wiggle uncontrollably in between the fitting data points. Also,
23818if the exact-fit polynomial is going to be used to interpolate or
23819extrapolate the data, it is numerically better to use the @kbd{a p}
23820command described below. @xref{Interpolation}.
23821
23822@tex
23823\bigskip
23824@end tex
23825
23826Another generalization of the linear model is to assume the
23827@cite{y} values are a sum of linear contributions from several
23828@cite{x} values. This is a @dfn{multilinear} fit, and it is also
23829selected by the @kbd{1} digit key. (Calc decides whether the fit
23830is linear or multilinear by counting the rows in the data matrix.)
23831
23832Given the data matrix,
23833
23834@group
23835@example
23836[ [ 1, 2, 3, 4, 5 ]
23837 [ 7, 2, 3, 5, 2 ]
23838 [ 14.5, 15, 18.5, 22.5, 24 ] ]
23839@end example
23840@end group
23841
23842@noindent
23843the command @kbd{a F 1 RET} will call the first row @cite{x} and the
23844second row @cite{y}, and will fit the values in the third row to the
23845model @cite{a + b x + c y}.
23846
23847@example
238488. + 3. x + 0.5 y
23849@end example
23850
23851Calc can do multilinear fits with any number of independent variables
23852(i.e., with any number of data rows).
23853
23854@tex
23855\bigskip
23856@end tex
23857
23858Yet another variation is @dfn{homogeneous} linear models, in which
23859the constant term is known to be zero. In the linear case, this
23860means the model formula is simply @cite{a x}; in the multilinear
23861case, the model might be @cite{a x + b y + c z}; and in the polynomial
23862case, the model could be @cite{a x + b x^2 + c x^3}. You can get
23863a homogeneous linear or multilinear model by pressing the letter
23864@kbd{h} followed by a regular model key, like @kbd{1} or @kbd{2}.
23865
23866It is certainly possible to have other constrained linear models,
23867like @cite{2.3 + a x} or @cite{a - 4 x}. While there is no single
23868key to select models like these, a later section shows how to enter
23869any desired model by hand. In the first case, for example, you
23870would enter @kbd{a F ' 2.3 + a x}.
23871
23872Another class of models that will work but must be entered by hand
23873are multinomial fits, e.g., @cite{a + b x + c y + d x^2 + e y^2 + f x y}.
23874
23875@node Error Estimates for Fits, Standard Nonlinear Models, Polynomial and Multilinear Fits, Curve Fitting
23876@subsection Error Estimates for Fits
23877
23878@noindent
23879@kindex H a F
23880@tindex efit
23881With the Hyperbolic flag, @kbd{H a F} [@code{efit}] performs the same
23882fitting operation as @kbd{a F}, but reports the coefficients as error
23883forms instead of plain numbers. Fitting our two data matrices (first
23884with 13, then with 14) to a line with @kbd{H a F} gives the results,
23885
23886@example
238873. + 2. x
238882.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
23889@end example
23890
23891In the first case the estimated errors are zero because the linear
23892fit is perfect. In the second case, the errors are nonzero but
23893moderately small, because the data are still very close to linear.
23894
23895It is also possible for the @emph{input} to a fitting operation to
23896contain error forms. The data values must either all include errors
23897or all be plain numbers. Error forms can go anywhere but generally
23898go on the numbers in the last row of the data matrix. If the last
23899row contains error forms
23900`@i{y_i}@w{ @t{+/-} }@c{$\sigma_i$}
23901@i{sigma_i}', then the @c{$\chi^2$}
23902@cite{chi^2}
23903statistic is now,
23904
23905@ifinfo
23906@example
23907chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
23908@end example
23909@end ifinfo
23910@tex
23911\turnoffactive
23912\beforedisplay
23913$$ \chi^2 = \sum_{i=1}^N \left(y_i - (a + b x_i) \over \sigma_i\right)^2 $$
23914\afterdisplay
23915@end tex
23916
23917@noindent
23918so that data points with larger error estimates contribute less to
23919the fitting operation.
23920
23921If there are error forms on other rows of the data matrix, all the
23922errors for a given data point are combined; the square root of the
23923sum of the squares of the errors forms the @c{$\sigma_i$}
23924@cite{sigma_i} used for
23925the data point.
23926
23927Both @kbd{a F} and @kbd{H a F} can accept error forms in the input
23928matrix, although if you are concerned about error analysis you will
23929probably use @kbd{H a F} so that the output also contains error
23930estimates.
23931
23932If the input contains error forms but all the @c{$\sigma_i$}
23933@cite{sigma_i} values are
23934the same, it is easy to see that the resulting fitted model will be
23935the same as if the input did not have error forms at all (@c{$\chi^2$}
23936@cite{chi^2}
23937is simply scaled uniformly by @c{$1 / \sigma^2$}
23938@cite{1 / sigma^2}, which doesn't affect
23939where it has a minimum). But there @emph{will} be a difference
23940in the estimated errors of the coefficients reported by @kbd{H a F}.
23941
23942Consult any text on statistical modelling of data for a discussion
23943of where these error estimates come from and how they should be
23944interpreted.
23945
23946@tex
23947\bigskip
23948@end tex
23949
23950@kindex I a F
23951@tindex xfit
23952With the Inverse flag, @kbd{I a F} [@code{xfit}] produces even more
23953information. The result is a vector of six items:
23954
23955@enumerate
23956@item
23957The model formula with error forms for its coefficients or
23958parameters. This is the result that @kbd{H a F} would have
23959produced.
23960
23961@item
23962A vector of ``raw'' parameter values for the model. These are the
23963polynomial coefficients or other parameters as plain numbers, in the
23964same order as the parameters appeared in the final prompt of the
23965@kbd{I a F} command. For polynomials of degree @cite{d}, this vector
23966will have length @cite{M = d+1} with the constant term first.
23967
23968@item
23969The covariance matrix @cite{C} computed from the fit. This is
23970an @i{M}x@i{M} symmetric matrix; the diagonal elements
23971@c{$C_{jj}$}
23972@cite{C_j_j} are the variances @c{$\sigma_j^2$}
23973@cite{sigma_j^2} of the parameters.
23974The other elements are covariances @c{$\sigma_{ij}^2$}
23975@cite{sigma_i_j^2} that describe the
23976correlation between pairs of parameters. (A related set of
23977numbers, the @dfn{linear correlation coefficients} @c{$r_{ij}$}
23978@cite{r_i_j},
23979are defined as @c{$\sigma_{ij}^2 / \sigma_i \, \sigma_j$}
23980@cite{sigma_i_j^2 / sigma_i sigma_j}.)
23981
23982@item
23983A vector of @cite{M} ``parameter filter'' functions whose
23984meanings are described below. If no filters are necessary this
23985will instead be an empty vector; this is always the case for the
23986polynomial and multilinear fits described so far.
23987
23988@item
23989The value of @c{$\chi^2$}
23990@cite{chi^2} for the fit, calculated by the formulas
23991shown above. This gives a measure of the quality of the fit;
23992statisticians consider @c{$\chi^2 \approx N - M$}
23993@cite{chi^2 = N - M} to indicate a moderately good fit
23994(where again @cite{N} is the number of data points and @cite{M}
23995is the number of parameters).
23996
23997@item
23998A measure of goodness of fit expressed as a probability @cite{Q}.
23999This is computed from the @code{utpc} probability distribution
24000function using @c{$\chi^2$}
24001@cite{chi^2} with @cite{N - M} degrees of freedom. A
24002value of 0.5 implies a good fit; some texts recommend that often
24003@cite{Q = 0.1} or even 0.001 can signify an acceptable fit. In
24004particular, @c{$\chi^2$}
24005@cite{chi^2} statistics assume the errors in your inputs
24006follow a normal (Gaussian) distribution; if they don't, you may
24007have to accept smaller values of @cite{Q}.
24008
24009The @cite{Q} value is computed only if the input included error
24010estimates. Otherwise, Calc will report the symbol @code{nan}
24011for @cite{Q}. The reason is that in this case the @c{$\chi^2$}
24012@cite{chi^2}
24013value has effectively been used to estimate the original errors
24014in the input, and thus there is no redundant information left
24015over to use for a confidence test.
24016@end enumerate
24017
24018@node Standard Nonlinear Models, Curve Fitting Details, Error Estimates for Fits, Curve Fitting
24019@subsection Standard Nonlinear Models
24020
24021@noindent
24022The @kbd{a F} command also accepts other kinds of models besides
24023lines and polynomials. Some common models have quick single-key
24024abbreviations; others must be entered by hand as algebraic formulas.
24025
24026Here is a complete list of the standard models recognized by @kbd{a F}:
24027
24028@table @kbd
24029@item 1
24030Linear or multilinear. @i{a + b x + c y + d z}.
24031@item 2-9
24032Polynomials. @i{a + b x + c x^2 + d x^3}.
24033@item e
24034Exponential. @i{a} @t{exp}@i{(b x)} @t{exp}@i{(c y)}.
24035@item E
24036Base-10 exponential. @i{a} @t{10^}@i{(b x)} @t{10^}@i{(c y)}.
24037@item x
24038Exponential (alternate notation). @t{exp}@i{(a + b x + c y)}.
24039@item X
24040Base-10 exponential (alternate). @t{10^}@i{(a + b x + c y)}.
24041@item l
24042Logarithmic. @i{a + b} @t{ln}@i{(x) + c} @t{ln}@i{(y)}.
24043@item L
24044Base-10 logarithmic. @i{a + b} @t{log10}@i{(x) + c} @t{log10}@i{(y)}.
24045@item ^
24046General exponential. @i{a b^x c^y}.
24047@item p
24048Power law. @i{a x^b y^c}.
24049@item q
24050Quadratic. @i{a + b (x-c)^2 + d (x-e)^2}.
24051@item g
24052Gaussian. @c{${a \over b \sqrt{2 \pi}} \exp\left( -{1 \over 2} \left( x - c \over b \right)^2 \right)$}
24053@i{(a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)}.
24054@end table
24055
24056All of these models are used in the usual way; just press the appropriate
24057letter at the model prompt, and choose variable names if you wish. The
24058result will be a formula as shown in the above table, with the best-fit
24059values of the parameters substituted. (You may find it easier to read
24060the parameter values from the vector that is placed in the trail.)
24061
24062All models except Gaussian and polynomials can generalize as shown to any
24063number of independent variables. Also, all the built-in models have an
24064additive or multiplicative parameter shown as @cite{a} in the above table
24065which can be replaced by zero or one, as appropriate, by typing @kbd{h}
24066before the model key.
24067
24068Note that many of these models are essentially equivalent, but express
24069the parameters slightly differently. For example, @cite{a b^x} and
24070the other two exponential models are all algebraic rearrangements of
24071each other. Also, the ``quadratic'' model is just a degree-2 polynomial
24072with the parameters expressed differently. Use whichever form best
24073matches the problem.
24074
24075The HP-28/48 calculators support four different models for curve
24076fitting, called @code{LIN}, @code{LOG}, @code{EXP}, and @code{PWR}.
24077These correspond to Calc models @samp{a + b x}, @samp{a + b ln(x)},
24078@samp{a exp(b x)}, and @samp{a x^b}, respectively. In each case,
24079@cite{a} is what the HP-48 identifies as the ``intercept,'' and
24080@cite{b} is what it calls the ``slope.''
24081
24082@tex
24083\bigskip
24084@end tex
24085
24086If the model you want doesn't appear on this list, press @kbd{'}
24087(the apostrophe key) at the model prompt to enter any algebraic
24088formula, such as @kbd{m x - b}, as the model. (Not all models
24089will work, though---see the next section for details.)
24090
24091The model can also be an equation like @cite{y = m x + b}.
24092In this case, Calc thinks of all the rows of the data matrix on
24093equal terms; this model effectively has two parameters
24094(@cite{m} and @cite{b}) and two independent variables (@cite{x}
24095and @cite{y}), with no ``dependent'' variables. Model equations
24096do not need to take this @cite{y =} form. For example, the
24097implicit line equation @cite{a x + b y = 1} works fine as a
24098model.
24099
24100When you enter a model, Calc makes an alphabetical list of all
24101the variables that appear in the model. These are used for the
24102default parameters, independent variables, and dependent variable
24103(in that order). If you enter a plain formula (not an equation),
24104Calc assumes the dependent variable does not appear in the formula
24105and thus does not need a name.
24106
24107For example, if the model formula has the variables @cite{a,mu,sigma,t,x},
24108and the data matrix has three rows (meaning two independent variables),
24109Calc will use @cite{a,mu,sigma} as the default parameters, and the
24110data rows will be named @cite{t} and @cite{x}, respectively. If you
24111enter an equation instead of a plain formula, Calc will use @cite{a,mu}
24112as the parameters, and @cite{sigma,t,x} as the three independent
24113variables.
24114
24115You can, of course, override these choices by entering something
24116different at the prompt. If you leave some variables out of the list,
24117those variables must have stored values and those stored values will
24118be used as constants in the model. (Stored values for the parameters
24119and independent variables are ignored by the @kbd{a F} command.)
24120If you list only independent variables, all the remaining variables
24121in the model formula will become parameters.
24122
24123If there are @kbd{$} signs in the model you type, they will stand
24124for parameters and all other variables (in alphabetical order)
24125will be independent. Use @kbd{$} for one parameter, @kbd{$$} for
24126another, and so on. Thus @kbd{$ x + $$} is another way to describe
24127a linear model.
24128
24129If you type a @kbd{$} instead of @kbd{'} at the model prompt itself,
24130Calc will take the model formula from the stack. (The data must then
24131appear at the second stack level.) The same conventions are used to
24132choose which variables in the formula are independent by default and
24133which are parameters.
24134
24135Models taken from the stack can also be expressed as vectors of
24136two or three elements, @cite{[@var{model}, @var{vars}]} or
24137@cite{[@var{model}, @var{vars}, @var{params}]}. Each of @var{vars}
24138and @var{params} may be either a variable or a vector of variables.
24139(If @var{params} is omitted, all variables in @var{model} except
24140those listed as @var{vars} are parameters.)@refill
24141
24142When you enter a model manually with @kbd{'}, Calc puts a 3-vector
24143describing the model in the trail so you can get it back if you wish.
24144
24145@tex
24146\bigskip
24147@end tex
24148
24149@vindex Model1
24150@vindex Model2
24151Finally, you can store a model in one of the Calc variables
24152@code{Model1} or @code{Model2}, then use this model by typing
24153@kbd{a F u} or @kbd{a F U} (respectively). The value stored in
24154the variable can be any of the formats that @kbd{a F $} would
24155accept for a model on the stack.
24156
24157@tex
24158\bigskip
24159@end tex
24160
24161Calc uses the principal values of inverse functions like @code{ln}
24162and @code{arcsin} when doing fits. For example, when you enter
24163the model @samp{y = sin(a t + b)} Calc actually uses the easier
24164form @samp{arcsin(y) = a t + b}. The @code{arcsin} function always
24165returns results in the range from @i{-90} to 90 degrees (or the
24166equivalent range in radians). Suppose you had data that you
24167believed to represent roughly three oscillations of a sine wave,
24168so that the argument of the sine might go from zero to @c{$3\times360$}
24169@i{3*360} degrees.
24170The above model would appear to be a good way to determine the
24171true frequency and phase of the sine wave, but in practice it
24172would fail utterly. The righthand side of the actual model
24173@samp{arcsin(y) = a t + b} will grow smoothly with @cite{t}, but
24174the lefthand side will bounce back and forth between @i{-90} and 90.
24175No values of @cite{a} and @cite{b} can make the two sides match,
24176even approximately.
24177
24178There is no good solution to this problem at present. You could
24179restrict your data to small enough ranges so that the above problem
24180doesn't occur (i.e., not straddling any peaks in the sine wave).
24181Or, in this case, you could use a totally different method such as
24182Fourier analysis, which is beyond the scope of the @kbd{a F} command.
24183(Unfortunately, Calc does not currently have any facilities for
24184taking Fourier and related transforms.)
24185
24186@node Curve Fitting Details, Interpolation, Standard Nonlinear Models, Curve Fitting
24187@subsection Curve Fitting Details
24188
24189@noindent
24190Calc's internal least-squares fitter can only handle multilinear
24191models. More precisely, it can handle any model of the form
24192@cite{a f(x,y,z) + b g(x,y,z) + c h(x,y,z)}, where @cite{a,b,c}
24193are the parameters and @cite{x,y,z} are the independent variables
24194(of course there can be any number of each, not just three).
24195
24196In a simple multilinear or polynomial fit, it is easy to see how
24197to convert the model into this form. For example, if the model
24198is @cite{a + b x + c x^2}, then @cite{f(x) = 1}, @cite{g(x) = x},
24199and @cite{h(x) = x^2} are suitable functions.
24200
24201For other models, Calc uses a variety of algebraic manipulations
24202to try to put the problem into the form
24203
24204@smallexample
24205Y(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)
24206@end smallexample
24207
24208@noindent
24209where @cite{Y,A,B,C,F,G,H} are arbitrary functions. It computes
24210@cite{Y}, @cite{F}, @cite{G}, and @cite{H} for all the data points,
24211does a standard linear fit to find the values of @cite{A}, @cite{B},
24212and @cite{C}, then uses the equation solver to solve for @cite{a,b,c}
24213in terms of @cite{A,B,C}.
24214
24215A remarkable number of models can be cast into this general form.
24216We'll look at two examples here to see how it works. The power-law
24217model @cite{y = a x^b} with two independent variables and two parameters
24218can be rewritten as follows:
24219
24220@example
24221y = a x^b
24222y = a exp(b ln(x))
24223y = exp(ln(a) + b ln(x))
24224ln(y) = ln(a) + b ln(x)
24225@end example
24226
24227@noindent
24228which matches the desired form with @c{$Y = \ln(y)$}
24229@cite{Y = ln(y)}, @c{$A = \ln(a)$}
24230@cite{A = ln(a)},
24231@cite{F = 1}, @cite{B = b}, and @c{$G = \ln(x)$}
24232@cite{G = ln(x)}. Calc thus computes
24233the logarithms of your @cite{y} and @cite{x} values, does a linear fit
24234for @cite{A} and @cite{B}, then solves to get @c{$a = \exp(A)$}
24235@cite{a = exp(A)} and
24236@cite{b = B}.
24237
24238Another interesting example is the ``quadratic'' model, which can
24239be handled by expanding according to the distributive law.
24240
24241@example
24242y = a + b*(x - c)^2
24243y = a + b c^2 - 2 b c x + b x^2
24244@end example
24245
24246@noindent
24247which matches with @cite{Y = y}, @cite{A = a + b c^2}, @cite{F = 1},
24248@cite{B = -2 b c}, @cite{G = x} (the @i{-2} factor could just as easily
24249have been put into @cite{G} instead of @cite{B}), @cite{C = b}, and
24250@cite{H = x^2}.
24251
24252The Gaussian model looks quite complicated, but a closer examination
24253shows that it's actually similar to the quadratic model but with an
24254exponential that can be brought to the top and moved into @cite{Y}.
24255
24256An example of a model that cannot be put into general linear
24257form is a Gaussian with a constant background added on, i.e.,
24258@cite{d} + the regular Gaussian formula. If you have a model like
24259this, your best bet is to replace enough of your parameters with
24260constants to make the model linearizable, then adjust the constants
24261manually by doing a series of fits. You can compare the fits by
24262graphing them, by examining the goodness-of-fit measures returned by
24263@kbd{I a F}, or by some other method suitable to your application.
24264Note that some models can be linearized in several ways. The
24265Gaussian-plus-@i{d} model can be linearized by setting @cite{d}
24266(the background) to a constant, or by setting @cite{b} (the standard
24267deviation) and @cite{c} (the mean) to constants.
24268
24269To fit a model with constants substituted for some parameters, just
24270store suitable values in those parameter variables, then omit them
24271from the list of parameters when you answer the variables prompt.
24272
24273@tex
24274\bigskip
24275@end tex
24276
24277A last desperate step would be to use the general-purpose
24278@code{minimize} function rather than @code{fit}. After all, both
24279functions solve the problem of minimizing an expression (the @c{$\chi^2$}
24280@cite{chi^2}
24281sum) by adjusting certain parameters in the expression. The @kbd{a F}
24282command is able to use a vastly more efficient algorithm due to its
24283special knowledge about linear chi-square sums, but the @kbd{a N}
24284command can do the same thing by brute force.
24285
24286A compromise would be to pick out a few parameters without which the
24287fit is linearizable, and use @code{minimize} on a call to @code{fit}
24288which efficiently takes care of the rest of the parameters. The thing
24289to be minimized would be the value of @c{$\chi^2$}
24290@cite{chi^2} returned as
24291the fifth result of the @code{xfit} function:
24292
24293@smallexample
24294minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
24295@end smallexample
24296
24297@noindent
24298where @code{gaus} represents the Gaussian model with background,
24299@code{data} represents the data matrix, and @code{guess} represents
24300the initial guess for @cite{d} that @code{minimize} requires.
24301This operation will only be, shall we say, extraordinarily slow
24302rather than astronomically slow (as would be the case if @code{minimize}
24303were used by itself to solve the problem).
24304
24305@tex
24306\bigskip
24307@end tex
24308
24309The @kbd{I a F} [@code{xfit}] command is somewhat trickier when
24310nonlinear models are used. The second item in the result is the
24311vector of ``raw'' parameters @cite{A}, @cite{B}, @cite{C}. The
24312covariance matrix is written in terms of those raw parameters.
24313The fifth item is a vector of @dfn{filter} expressions. This
24314is the empty vector @samp{[]} if the raw parameters were the same
24315as the requested parameters, i.e., if @cite{A = a}, @cite{B = b},
24316and so on (which is always true if the model is already linear
24317in the parameters as written, e.g., for polynomial fits). If the
24318parameters had to be rearranged, the fifth item is instead a vector
24319of one formula per parameter in the original model. The raw
24320parameters are expressed in these ``filter'' formulas as
24321@samp{fitdummy(1)} for @cite{A}, @samp{fitdummy(2)} for @cite{B},
24322and so on.
24323
24324When Calc needs to modify the model to return the result, it replaces
24325@samp{fitdummy(1)} in all the filters with the first item in the raw
24326parameters list, and so on for the other raw parameters, then
24327evaluates the resulting filter formulas to get the actual parameter
24328values to be substituted into the original model. In the case of
24329@kbd{H a F} and @kbd{I a F} where the parameters must be error forms,
24330Calc uses the square roots of the diagonal entries of the covariance
24331matrix as error values for the raw parameters, then lets Calc's
24332standard error-form arithmetic take it from there.
24333
24334If you use @kbd{I a F} with a nonlinear model, be sure to remember
24335that the covariance matrix is in terms of the raw parameters,
24336@emph{not} the actual requested parameters. It's up to you to
24337figure out how to interpret the covariances in the presence of
24338nontrivial filter functions.
24339
24340Things are also complicated when the input contains error forms.
24341Suppose there are three independent and dependent variables, @cite{x},
24342@cite{y}, and @cite{z}, one or more of which are error forms in the
24343data. Calc combines all the error values by taking the square root
24344of the sum of the squares of the errors. It then changes @cite{x}
24345and @cite{y} to be plain numbers, and makes @cite{z} into an error
24346form with this combined error. The @cite{Y(x,y,z)} part of the
24347linearized model is evaluated, and the result should be an error
24348form. The error part of that result is used for @c{$\sigma_i$}
24349@cite{sigma_i} for
24350the data point. If for some reason @cite{Y(x,y,z)} does not return
24351an error form, the combined error from @cite{z} is used directly
24352for @c{$\sigma_i$}
24353@cite{sigma_i}. Finally, @cite{z} is also stripped of its error
24354for use in computing @cite{F(x,y,z)}, @cite{G(x,y,z)} and so on;
24355the righthand side of the linearized model is computed in regular
24356arithmetic with no error forms.
24357
24358(While these rules may seem complicated, they are designed to do
24359the most reasonable thing in the typical case that @cite{Y(x,y,z)}
24360depends only on the dependent variable @cite{z}, and in fact is
24361often simply equal to @cite{z}. For common cases like polynomials
24362and multilinear models, the combined error is simply used as the
24363@c{$\sigma$}
24364@cite{sigma} for the data point with no further ado.)
24365
24366@tex
24367\bigskip
24368@end tex
24369
24370@vindex FitRules
24371It may be the case that the model you wish to use is linearizable,
24372but Calc's built-in rules are unable to figure it out. Calc uses
24373its algebraic rewrite mechanism to linearize a model. The rewrite
24374rules are kept in the variable @code{FitRules}. You can edit this
24375variable using the @kbd{s e FitRules} command; in fact, there is
24376a special @kbd{s F} command just for editing @code{FitRules}.
24377@xref{Operations on Variables}.
24378
24379@xref{Rewrite Rules}, for a discussion of rewrite rules.
24380
24381@c @starindex
24382@tindex fitvar
24383@c @starindex
24384@c @mindex @idots
24385@tindex fitparam
24386@c @starindex
24387@c @mindex @null
24388@tindex fitmodel
24389@c @starindex
24390@c @mindex @null
24391@tindex fitsystem
24392@c @starindex
24393@c @mindex @null
24394@tindex fitdummy
24395Calc uses @code{FitRules} as follows. First, it converts the model
24396to an equation if necessary and encloses the model equation in a
24397call to the function @code{fitmodel} (which is not actually a defined
24398function in Calc; it is only used as a placeholder by the rewrite rules).
24399Parameter variables are renamed to function calls @samp{fitparam(1)},
24400@samp{fitparam(2)}, and so on, and independent variables are renamed
24401to @samp{fitvar(1)}, @samp{fitvar(2)}, etc. The dependent variable
24402is the highest-numbered @code{fitvar}. For example, the power law
24403model @cite{a x^b} is converted to @cite{y = a x^b}, then to
24404
24405@group
24406@smallexample
24407fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
24408@end smallexample
24409@end group
24410
24411Calc then applies the rewrites as if by @samp{C-u 0 a r FitRules}.
24412(The zero prefix means that rewriting should continue until no further
24413changes are possible.)
24414
24415When rewriting is complete, the @code{fitmodel} call should have
24416been replaced by a @code{fitsystem} call that looks like this:
24417
24418@example
24419fitsystem(@var{Y}, @var{FGH}, @var{abc})
24420@end example
24421
24422@noindent
24423where @var{Y} is a formula that describes the function @cite{Y(x,y,z)},
24424@var{FGH} is the vector of formulas @cite{[F(x,y,z), G(x,y,z), H(x,y,z)]},
24425and @var{abc} is the vector of parameter filters which refer to the
24426raw parameters as @samp{fitdummy(1)} for @cite{A}, @samp{fitdummy(2)}
24427for @cite{B}, etc. While the number of raw parameters (the length of
24428the @var{FGH} vector) is usually the same as the number of original
24429parameters (the length of the @var{abc} vector), this is not required.
24430
24431The power law model eventually boils down to
24432
24433@group
24434@smallexample
24435fitsystem(ln(fitvar(2)),
24436 [1, ln(fitvar(1))],
24437 [exp(fitdummy(1)), fitdummy(2)])
24438@end smallexample
24439@end group
24440
24441The actual implementation of @code{FitRules} is complicated; it
24442proceeds in four phases. First, common rearrangements are done
24443to try to bring linear terms together and to isolate functions like
24444@code{exp} and @code{ln} either all the way ``out'' (so that they
24445can be put into @var{Y}) or all the way ``in'' (so that they can
24446be put into @var{abc} or @var{FGH}). In particular, all
24447non-constant powers are converted to logs-and-exponentials form,
24448and the distributive law is used to expand products of sums.
24449Quotients are rewritten to use the @samp{fitinv} function, where
24450@samp{fitinv(x)} represents @cite{1/x} while the @code{FitRules}
24451are operating. (The use of @code{fitinv} makes recognition of
24452linear-looking forms easier.) If you modify @code{FitRules}, you
24453will probably only need to modify the rules for this phase.
24454
24455Phase two, whose rules can actually also apply during phases one
24456and three, first rewrites @code{fitmodel} to a two-argument
24457form @samp{fitmodel(@var{Y}, @var{model})}, where @var{Y} is
24458initially zero and @var{model} has been changed from @cite{a=b}
24459to @cite{a-b} form. It then tries to peel off invertible functions
24460from the outside of @var{model} and put them into @var{Y} instead,
24461calling the equation solver to invert the functions. Finally, when
24462this is no longer possible, the @code{fitmodel} is changed to a
24463four-argument @code{fitsystem}, where the fourth argument is
24464@var{model} and the @var{FGH} and @var{abc} vectors are initially
24465empty. (The last vector is really @var{ABC}, corresponding to
24466raw parameters, for now.)
24467
24468Phase three converts a sum of items in the @var{model} to a sum
24469of @samp{fitpart(@var{a}, @var{b}, @var{c})} terms which represent
24470terms @samp{@var{a}*@var{b}*@var{c}} of the sum, where @var{a}
24471is all factors that do not involve any variables, @var{b} is all
24472factors that involve only parameters, and @var{c} is the factors
24473that involve only independent variables. (If this decomposition
24474is not possible, the rule set will not complete and Calc will
24475complain that the model is too complex.) Then @code{fitpart}s
24476with equal @var{b} or @var{c} components are merged back together
24477using the distributive law in order to minimize the number of
24478raw parameters needed.
24479
24480Phase four moves the @code{fitpart} terms into the @var{FGH} and
24481@var{ABC} vectors. Also, some of the algebraic expansions that
24482were done in phase 1 are undone now to make the formulas more
24483computationally efficient. Finally, it calls the solver one more
24484time to convert the @var{ABC} vector to an @var{abc} vector, and
24485removes the fourth @var{model} argument (which by now will be zero)
24486to obtain the three-argument @code{fitsystem} that the linear
24487least-squares solver wants to see.
24488
24489@c @starindex
24490@c @mindex hasfit@idots
24491@tindex hasfitparams
24492@c @starindex
24493@c @mindex @null
24494@tindex hasfitvars
24495Two functions which are useful in connection with @code{FitRules}
24496are @samp{hasfitparams(x)} and @samp{hasfitvars(x)}, which check
24497whether @cite{x} refers to any parameters or independent variables,
24498respectively. Specifically, these functions return ``true'' if the
24499argument contains any @code{fitparam} (or @code{fitvar}) function
24500calls, and ``false'' otherwise. (Recall that ``true'' means a
24501nonzero number, and ``false'' means zero. The actual nonzero number
24502returned is the largest @var{n} from all the @samp{fitparam(@var{n})}s
24503or @samp{fitvar(@var{n})}s, respectively, that appear in the formula.)
24504
24505@tex
24506\bigskip
24507@end tex
24508
24509The @code{fit} function in algebraic notation normally takes four
24510arguments, @samp{fit(@var{model}, @var{vars}, @var{params}, @var{data})},
24511where @var{model} is the model formula as it would be typed after
24512@kbd{a F '}, @var{vars} is the independent variable or a vector of
24513independent variables, @var{params} likewise gives the parameter(s),
24514and @var{data} is the data matrix. Note that the length of @var{vars}
24515must be equal to the number of rows in @var{data} if @var{model} is
24516an equation, or one less than the number of rows if @var{model} is
24517a plain formula. (Actually, a name for the dependent variable is
24518allowed but will be ignored in the plain-formula case.)
24519
24520If @var{params} is omitted, the parameters are all variables in
24521@var{model} except those that appear in @var{vars}. If @var{vars}
24522is also omitted, Calc sorts all the variables that appear in
24523@var{model} alphabetically and uses the higher ones for @var{vars}
24524and the lower ones for @var{params}.
24525
24526Alternatively, @samp{fit(@var{modelvec}, @var{data})} is allowed
24527where @var{modelvec} is a 2- or 3-vector describing the model
24528and variables, as discussed previously.
24529
24530If Calc is unable to do the fit, the @code{fit} function is left
24531in symbolic form, ordinarily with an explanatory message. The
24532message will be ``Model expression is too complex'' if the
24533linearizer was unable to put the model into the required form.
24534
24535The @code{efit} (corresponding to @kbd{H a F}) and @code{xfit}
24536(for @kbd{I a F}) functions are completely analogous.
24537
24538@node Interpolation, , Curve Fitting Details, Curve Fitting
24539@subsection Polynomial Interpolation
24540
24541@kindex a p
24542@pindex calc-poly-interp
24543@tindex polint
24544The @kbd{a p} (@code{calc-poly-interp}) [@code{polint}] command does
24545a polynomial interpolation at a particular @cite{x} value. It takes
24546two arguments from the stack: A data matrix of the sort used by
24547@kbd{a F}, and a single number which represents the desired @cite{x}
24548value. Calc effectively does an exact polynomial fit as if by @kbd{a F i},
24549then substitutes the @cite{x} value into the result in order to get an
24550approximate @cite{y} value based on the fit. (Calc does not actually
24551use @kbd{a F i}, however; it uses a direct method which is both more
24552efficient and more numerically stable.)
24553
24554The result of @kbd{a p} is actually a vector of two values: The @cite{y}
24555value approximation, and an error measure @cite{dy} that reflects Calc's
24556estimation of the probable error of the approximation at that value of
24557@cite{x}. If the input @cite{x} is equal to any of the @cite{x} values
24558in the data matrix, the output @cite{y} will be the corresponding @cite{y}
24559value from the matrix, and the output @cite{dy} will be exactly zero.
24560
24561A prefix argument of 2 causes @kbd{a p} to take separate x- and
24562y-vectors from the stack instead of one data matrix.
24563
24564If @cite{x} is a vector of numbers, @kbd{a p} will return a matrix of
24565interpolated results for each of those @cite{x} values. (The matrix will
24566have two columns, the @cite{y} values and the @cite{dy} values.)
24567If @cite{x} is a formula instead of a number, the @code{polint} function
24568remains in symbolic form; use the @kbd{a "} command to expand it out to
24569a formula that describes the fit in symbolic terms.
24570
24571In all cases, the @kbd{a p} command leaves the data vectors or matrix
24572on the stack. Only the @cite{x} value is replaced by the result.
24573
24574@kindex H a p
24575@tindex ratint
24576The @kbd{H a p} [@code{ratint}] command does a rational function
24577interpolation. It is used exactly like @kbd{a p}, except that it
24578uses as its model the quotient of two polynomials. If there are
24579@cite{N} data points, the numerator and denominator polynomials will
24580each have degree @cite{N/2} (if @cite{N} is odd, the denominator will
24581have degree one higher than the numerator).
24582
24583Rational approximations have the advantage that they can accurately
24584describe functions that have poles (points at which the function's value
24585goes to infinity, so that the denominator polynomial of the approximation
24586goes to zero). If @cite{x} corresponds to a pole of the fitted rational
24587function, then the result will be a division by zero. If Infinite mode
24588is enabled, the result will be @samp{[uinf, uinf]}.
24589
24590There is no way to get the actual coefficients of the rational function
24591used by @kbd{H a p}. (The algorithm never generates these coefficients
24592explicitly, and quotients of polynomials are beyond @w{@kbd{a F}}'s
24593capabilities to fit.)
24594
24595@node Summations, Logical Operations, Curve Fitting, Algebra
24596@section Summations
24597
24598@noindent
24599@cindex Summation of a series
24600@kindex a +
24601@pindex calc-summation
24602@tindex sum
24603The @kbd{a +} (@code{calc-summation}) [@code{sum}] command computes
24604the sum of a formula over a certain range of index values. The formula
24605is taken from the top of the stack; the command prompts for the
24606name of the summation index variable, the lower limit of the
24607sum (any formula), and the upper limit of the sum. If you
24608enter a blank line at any of these prompts, that prompt and
24609any later ones are answered by reading additional elements from
24610the stack. Thus, @kbd{' k^2 RET ' k RET 1 RET 5 RET a + RET}
24611produces the result 55.
24612@tex
24613\turnoffactive
24614$$ \sum_{k=1}^5 k^2 = 55 $$
24615@end tex
24616
24617The choice of index variable is arbitrary, but it's best not to
24618use a variable with a stored value. In particular, while
24619@code{i} is often a favorite index variable, it should be avoided
24620in Calc because @code{i} has the imaginary constant @cite{(0, 1)}
24621as a value. If you pressed @kbd{=} on a sum over @code{i}, it would
24622be changed to a nonsensical sum over the ``variable'' @cite{(0, 1)}!
24623If you really want to use @code{i} as an index variable, use
24624@w{@kbd{s u i RET}} first to ``unstore'' this variable.
24625(@xref{Storing Variables}.)
24626
24627A numeric prefix argument steps the index by that amount rather
24628than by one. Thus @kbd{' a_k RET C-u -2 a + k RET 10 RET 0 RET}
24629yields @samp{a_10 + a_8 + a_6 + a_4 + a_2 + a_0}. A prefix
24630argument of plain @kbd{C-u} causes @kbd{a +} to prompt for the
24631step value, in which case you can enter any formula or enter
24632a blank line to take the step value from the stack. With the
24633@kbd{C-u} prefix, @kbd{a +} can take up to five arguments from
24634the stack: The formula, the variable, the lower limit, the
24635upper limit, and (at the top of the stack), the step value.
24636
24637Calc knows how to do certain sums in closed form. For example,
24638@samp{sum(6 k^2, k, 1, n) = @w{2 n^3} + 3 n^2 + n}. In particular,
24639this is possible if the formula being summed is polynomial or
24640exponential in the index variable. Sums of logarithms are
24641transformed into logarithms of products. Sums of trigonometric
24642and hyperbolic functions are transformed to sums of exponentials
24643and then done in closed form. Also, of course, sums in which the
24644lower and upper limits are both numbers can always be evaluated
24645just by grinding them out, although Calc will use closed forms
24646whenever it can for the sake of efficiency.
24647
24648The notation for sums in algebraic formulas is
24649@samp{sum(@var{expr}, @var{var}, @var{low}, @var{high}, @var{step})}.
24650If @var{step} is omitted, it defaults to one. If @var{high} is
24651omitted, @var{low} is actually the upper limit and the lower limit
24652is one. If @var{low} is also omitted, the limits are @samp{-inf}
24653and @samp{inf}, respectively.
24654
24655Infinite sums can sometimes be evaluated: @samp{sum(.5^k, k, 1, inf)}
24656returns @cite{1}. This is done by evaluating the sum in closed
24657form (to @samp{1. - 0.5^n} in this case), then evaluating this
24658formula with @code{n} set to @code{inf}. Calc's usual rules
24659for ``infinite'' arithmetic can find the answer from there. If
24660infinite arithmetic yields a @samp{nan}, or if the sum cannot be
24661solved in closed form, Calc leaves the @code{sum} function in
24662symbolic form. @xref{Infinities}.
24663
24664As a special feature, if the limits are infinite (or omitted, as
24665described above) but the formula includes vectors subscripted by
24666expressions that involve the iteration variable, Calc narrows
24667the limits to include only the range of integers which result in
24668legal subscripts for the vector. For example, the sum
24669@samp{sum(k [a,b,c,d,e,f,g]_(2k),k)} evaluates to @samp{b + 2 d + 3 f}.
24670
24671The limits of a sum do not need to be integers. For example,
24672@samp{sum(a_k, k, 0, 2 n, n)} produces @samp{a_0 + a_n + a_(2 n)}.
24673Calc computes the number of iterations using the formula
24674@samp{1 + (@var{high} - @var{low}) / @var{step}}, which must,
24675after simplification as if by @kbd{a s}, evaluate to an integer.
24676
24677If the number of iterations according to the above formula does
24678not come out to an integer, the sum is illegal and will be left
24679in symbolic form. However, closed forms are still supplied, and
24680you are on your honor not to misuse the resulting formulas by
24681substituting mismatched bounds into them. For example,
24682@samp{sum(k, k, 1, 10, 2)} is invalid, but Calc will go ahead and
24683evaluate the closed form solution for the limits 1 and 10 to get
24684the rather dubious answer, 29.25.
24685
24686If the lower limit is greater than the upper limit (assuming a
24687positive step size), the result is generally zero. However,
24688Calc only guarantees a zero result when the upper limit is
24689exactly one step less than the lower limit, i.e., if the number
24690of iterations is @i{-1}. Thus @samp{sum(f(k), k, n, n-1)} is zero
24691but the sum from @samp{n} to @samp{n-2} may report a nonzero value
24692if Calc used a closed form solution.
24693
24694Calc's logical predicates like @cite{a < b} return 1 for ``true''
24695and 0 for ``false.'' @xref{Logical Operations}. This can be
24696used to advantage for building conditional sums. For example,
24697@samp{sum(prime(k)*k^2, k, 1, 20)} is the sum of the squares of all
24698prime numbers from 1 to 20; the @code{prime} predicate returns 1 if
24699its argument is prime and 0 otherwise. You can read this expression
24700as ``the sum of @cite{k^2}, where @cite{k} is prime.'' Indeed,
24701@samp{sum(prime(k)*k^2, k)} would represent the sum of @emph{all} primes
24702squared, since the limits default to plus and minus infinity, but
24703there are no such sums that Calc's built-in rules can do in
24704closed form.
24705
24706As another example, @samp{sum((k != k_0) * f(k), k, 1, n)} is the
24707sum of @cite{f(k)} for all @cite{k} from 1 to @cite{n}, excluding
24708one value @cite{k_0}. Slightly more tricky is the summand
24709@samp{(k != k_0) / (k - k_0)}, which is an attempt to describe
24710the sum of all @cite{1/(k-k_0)} except at @cite{k = k_0}, where
24711this would be a division by zero. But at @cite{k = k_0}, this
24712formula works out to the indeterminate form @cite{0 / 0}, which
24713Calc will not assume is zero. Better would be to use
24714@samp{(k != k_0) ? 1/(k-k_0) : 0}; the @samp{? :} operator does
24715an ``if-then-else'' test: This expression says, ``if @c{$k \ne k_0$}
24716@cite{k != k_0},
24717then @cite{1/(k-k_0)}, else zero.'' Now the formula @cite{1/(k-k_0)}
24718will not even be evaluated by Calc when @cite{k = k_0}.
24719
24720@cindex Alternating sums
24721@kindex a -
24722@pindex calc-alt-summation
24723@tindex asum
24724The @kbd{a -} (@code{calc-alt-summation}) [@code{asum}] command
24725computes an alternating sum. Successive terms of the sequence
24726are given alternating signs, with the first term (corresponding
24727to the lower index value) being positive. Alternating sums
24728are converted to normal sums with an extra term of the form
24729@samp{(-1)^(k-@var{low})}. This formula is adjusted appropriately
24730if the step value is other than one. For example, the Taylor
24731series for the sine function is @samp{asum(x^k / k!, k, 1, inf, 2)}.
24732(Calc cannot evaluate this infinite series, but it can approximate
24733it if you replace @code{inf} with any particular odd number.)
24734Calc converts this series to a regular sum with a step of one,
24735namely @samp{sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)}.
24736
24737@cindex Product of a sequence
24738@kindex a *
24739@pindex calc-product
24740@tindex prod
24741The @kbd{a *} (@code{calc-product}) [@code{prod}] command is
24742the analogous way to take a product of many terms. Calc also knows
24743some closed forms for products, such as @samp{prod(k, k, 1, n) = n!}.
24744Conditional products can be written @samp{prod(k^prime(k), k, 1, n)}
24745or @samp{prod(prime(k) ? k : 1, k, 1, n)}.
24746
24747@kindex a T
24748@pindex calc-tabulate
24749@tindex table
24750The @kbd{a T} (@code{calc-tabulate}) [@code{table}] command
24751evaluates a formula at a series of iterated index values, just
24752like @code{sum} and @code{prod}, but its result is simply a
24753vector of the results. For example, @samp{table(a_i, i, 1, 7, 2)}
24754produces @samp{[a_1, a_3, a_5, a_7]}.
24755
24756@node Logical Operations, Rewrite Rules, Summations, Algebra
24757@section Logical Operations
24758
24759@noindent
24760The following commands and algebraic functions return true/false values,
24761where 1 represents ``true'' and 0 represents ``false.'' In cases where
24762a truth value is required (such as for the condition part of a rewrite
24763rule, or as the condition for a @w{@kbd{Z [ Z ]}} control structure), any
24764nonzero value is accepted to mean ``true.'' (Specifically, anything
24765for which @code{dnonzero} returns 1 is ``true,'' and anything for
24766which @code{dnonzero} returns 0 or cannot decide is assumed ``false.''
24767Note that this means that @w{@kbd{Z [ Z ]}} will execute the ``then''
24768portion if its condition is provably true, but it will execute the
24769``else'' portion for any condition like @cite{a = b} that is not
24770provably true, even if it might be true. Algebraic functions that
24771have conditions as arguments, like @code{? :} and @code{&&}, remain
24772unevaluated if the condition is neither provably true nor provably
24773false. @xref{Declarations}.)
24774
24775@kindex a =
24776@pindex calc-equal-to
24777@tindex eq
24778@tindex =
24779@tindex ==
24780The @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function
24781(which can also be written @samp{a = b} or @samp{a == b} in an algebraic
24782formula) is true if @cite{a} and @cite{b} are equal, either because they
24783are identical expressions, or because they are numbers which are
24784numerically equal. (Thus the integer 1 is considered equal to the float
247851.0.) If the equality of @cite{a} and @cite{b} cannot be determined,
24786the comparison is left in symbolic form. Note that as a command, this
24787operation pops two values from the stack and pushes back either a 1 or
24788a 0, or a formula @samp{a = b} if the values' equality cannot be determined.
24789
24790Many Calc commands use @samp{=} formulas to represent @dfn{equations}.
24791For example, the @kbd{a S} (@code{calc-solve-for}) command rearranges
24792an equation to solve for a given variable. The @kbd{a M}
24793(@code{calc-map-equation}) command can be used to apply any
24794function to both sides of an equation; for example, @kbd{2 a M *}
24795multiplies both sides of the equation by two. Note that just
24796@kbd{2 *} would not do the same thing; it would produce the formula
24797@samp{2 (a = b)} which represents 2 if the equality is true or
24798zero if not.
24799
24800The @code{eq} function with more than two arguments (e.g., @kbd{C-u 3 a =}
24801or @samp{a = b = c}) tests if all of its arguments are equal. In
24802algebraic notation, the @samp{=} operator is unusual in that it is
24803neither left- nor right-associative: @samp{a = b = c} is not the
24804same as @samp{(a = b) = c} or @samp{a = (b = c)} (which each compare
24805one variable with the 1 or 0 that results from comparing two other
24806variables).
24807
24808@kindex a #
24809@pindex calc-not-equal-to
24810@tindex neq
24811@tindex !=
24812The @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or
24813@samp{a != b} function, is true if @cite{a} and @cite{b} are not equal.
24814This also works with more than two arguments; @samp{a != b != c != d}
24815tests that all four of @cite{a}, @cite{b}, @cite{c}, and @cite{d} are
24816distinct numbers.
24817
24818@kindex a <
24819@tindex lt
24820@c @mindex @idots
24821@kindex a >
24822@c @mindex @null
24823@kindex a [
24824@c @mindex @null
24825@kindex a ]
24826@pindex calc-less-than
24827@pindex calc-greater-than
24828@pindex calc-less-equal
24829@pindex calc-greater-equal
24830@c @mindex @null
24831@tindex gt
24832@c @mindex @null
24833@tindex leq
24834@c @mindex @null
24835@tindex geq
24836@c @mindex @null
24837@tindex <
24838@c @mindex @null
24839@tindex >
24840@c @mindex @null
24841@tindex <=
24842@c @mindex @null
24843@tindex >=
24844The @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}]
24845operation is true if @cite{a} is less than @cite{b}. Similar functions
24846are @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}],
24847@kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and
24848@kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}].
24849
24850While the inequality functions like @code{lt} do not accept more
24851than two arguments, the syntax @w{@samp{a <= b < c}} is translated to an
24852equivalent expression involving intervals: @samp{b in [a .. c)}.
24853(See the description of @code{in} below.) All four combinations
24854of @samp{<} and @samp{<=} are allowed, or any of the four combinations
24855of @samp{>} and @samp{>=}. Four-argument constructions like
24856@samp{a < b < c < d}, and mixtures like @w{@samp{a < b = c}} that
24857involve both equalities and inequalities, are not allowed.
24858
24859@kindex a .
24860@pindex calc-remove-equal
24861@tindex rmeq
24862The @kbd{a .} (@code{calc-remove-equal}) [@code{rmeq}] command extracts
24863the righthand side of the equation or inequality on the top of the
24864stack. It also works elementwise on vectors. For example, if
24865@samp{[x = 2.34, y = z / 2]} is on the stack, then @kbd{a .} produces
24866@samp{[2.34, z / 2]}. As a special case, if the righthand side is a
24867variable and the lefthand side is a number (as in @samp{2.34 = x}), then
24868Calc keeps the lefthand side instead. Finally, this command works with
24869assignments @samp{x := 2.34} as well as equations, always taking the
24870the righthand side, and for @samp{=>} (evaluates-to) operators, always
24871taking the lefthand side.
24872
24873@kindex a &
24874@pindex calc-logical-and
24875@tindex land
24876@tindex &&
24877The @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}]
24878function is true if both of its arguments are true, i.e., are
24879non-zero numbers. In this case, the result will be either @cite{a} or
24880@cite{b}, chosen arbitrarily. If either argument is zero, the result is
24881zero. Otherwise, the formula is left in symbolic form.
24882
24883@kindex a |
24884@pindex calc-logical-or
24885@tindex lor
24886@tindex ||
24887The @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}]
24888function is true if either or both of its arguments are true (nonzero).
24889The result is whichever argument was nonzero, choosing arbitrarily if both
24890are nonzero. If both @cite{a} and @cite{b} are zero, the result is
24891zero.
24892
24893@kindex a !
24894@pindex calc-logical-not
24895@tindex lnot
24896@tindex !
24897The @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{!@: a}]
24898function is true if @cite{a} is false (zero), or false if @cite{a} is
24899true (nonzero). It is left in symbolic form if @cite{a} is not a
24900number.
24901
24902@kindex a :
24903@pindex calc-logical-if
24904@tindex if
24905@c @mindex ? :
24906@tindex ?
24907@c @mindex @null
24908@tindex :
24909@cindex Arguments, not evaluated
24910The @kbd{a :} (@code{calc-logical-if}) [@samp{if(a,b,c)} or @samp{a ? b :@: c}]
24911function is equal to either @cite{b} or @cite{c} if @cite{a} is a nonzero
24912number or zero, respectively. If @cite{a} is not a number, the test is
24913left in symbolic form and neither @cite{b} nor @cite{c} is evaluated in
24914any way. In algebraic formulas, this is one of the few Calc functions
24915whose arguments are not automatically evaluated when the function itself
24916is evaluated. The others are @code{lambda}, @code{quote}, and
24917@code{condition}.
24918
24919One minor surprise to watch out for is that the formula @samp{a?3:4}
24920will not work because the @samp{3:4} is parsed as a fraction instead of
24921as three separate symbols. Type something like @samp{a ? 3 : 4} or
24922@samp{a?(3):4} instead.
24923
24924As a special case, if @cite{a} evaluates to a vector, then both @cite{b}
24925and @cite{c} are evaluated; the result is a vector of the same length
24926as @cite{a} whose elements are chosen from corresponding elements of
24927@cite{b} and @cite{c} according to whether each element of @cite{a}
24928is zero or nonzero. Each of @cite{b} and @cite{c} must be either a
24929vector of the same length as @cite{a}, or a non-vector which is matched
24930with all elements of @cite{a}.
24931
24932@kindex a @{
24933@pindex calc-in-set
24934@tindex in
24935The @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if
24936the number @cite{a} is in the set of numbers represented by @cite{b}.
24937If @cite{b} is an interval form, @cite{a} must be one of the values
24938encompassed by the interval. If @cite{b} is a vector, @cite{a} must be
24939equal to one of the elements of the vector. (If any vector elements are
24940intervals, @cite{a} must be in any of the intervals.) If @cite{b} is a
24941plain number, @cite{a} must be numerically equal to @cite{b}.
24942@xref{Set Operations}, for a group of commands that manipulate sets
24943of this sort.
24944
24945@c @starindex
24946@tindex typeof
24947The @samp{typeof(a)} function produces an integer or variable which
24948characterizes @cite{a}. If @cite{a} is a number, vector, or variable,
24949the result will be one of the following numbers:
24950
24951@example
24952 1 Integer
24953 2 Fraction
24954 3 Floating-point number
24955 4 HMS form
24956 5 Rectangular complex number
24957 6 Polar complex number
24958 7 Error form
24959 8 Interval form
24960 9 Modulo form
2496110 Date-only form
2496211 Date/time form
2496312 Infinity (inf, uinf, or nan)
24964100 Variable
24965101 Vector (but not a matrix)
24966102 Matrix
24967@end example
24968
24969Otherwise, @cite{a} is a formula, and the result is a variable which
24970represents the name of the top-level function call.
24971
24972@c @starindex
24973@tindex integer
24974@c @starindex
24975@tindex real
24976@c @starindex
24977@tindex constant
24978The @samp{integer(a)} function returns true if @cite{a} is an integer.
24979The @samp{real(a)} function
24980is true if @cite{a} is a real number, either integer, fraction, or
24981float. The @samp{constant(a)} function returns true if @cite{a} is
24982any of the objects for which @code{typeof} would produce an integer
24983code result except for variables, and provided that the components of
24984an object like a vector or error form are themselves constant.
24985Note that infinities do not satisfy any of these tests, nor do
24986special constants like @code{pi} and @code{e}.@refill
24987
24988@xref{Declarations}, for a set of similar functions that recognize
24989formulas as well as actual numbers. For example, @samp{dint(floor(x))}
24990is true because @samp{floor(x)} is provably integer-valued, but
24991@samp{integer(floor(x))} does not because @samp{floor(x)} is not
24992literally an integer constant.
24993
24994@c @starindex
24995@tindex refers
24996The @samp{refers(a,b)} function is true if the variable (or sub-expression)
24997@cite{b} appears in @cite{a}, or false otherwise. Unlike the other
24998tests described here, this function returns a definite ``no'' answer
24999even if its arguments are still in symbolic form. The only case where
25000@code{refers} will be left unevaluated is if @cite{a} is a plain
25001variable (different from @cite{b}).
25002
25003@c @starindex
25004@tindex negative
25005The @samp{negative(a)} function returns true if @cite{a} ``looks'' negative,
25006because it is a negative number, because it is of the form @cite{-x},
25007or because it is a product or quotient with a term that looks negative.
25008This is most useful in rewrite rules. Beware that @samp{negative(a)}
25009evaluates to 1 or 0 for @emph{any} argument @cite{a}, so it can only
25010be stored in a formula if the default simplifications are turned off
25011first with @kbd{m O} (or if it appears in an unevaluated context such
25012as a rewrite rule condition).
25013
25014@c @starindex
25015@tindex variable
25016The @samp{variable(a)} function is true if @cite{a} is a variable,
25017or false if not. If @cite{a} is a function call, this test is left
25018in symbolic form. Built-in variables like @code{pi} and @code{inf}
25019are considered variables like any others by this test.
25020
25021@c @starindex
25022@tindex nonvar
25023The @samp{nonvar(a)} function is true if @cite{a} is a non-variable.
25024If its argument is a variable it is left unsimplified; it never
25025actually returns zero. However, since Calc's condition-testing
25026commands consider ``false'' anything not provably true, this is
25027often good enough.
25028
25029@c @starindex
25030@tindex lin
25031@c @starindex
25032@tindex linnt
25033@c @starindex
25034@tindex islin
25035@c @starindex
25036@tindex islinnt
25037@cindex Linearity testing
25038The functions @code{lin}, @code{linnt}, @code{islin}, and @code{islinnt}
25039check if an expression is ``linear,'' i.e., can be written in the form
25040@cite{a + b x} for some constants @cite{a} and @cite{b}, and some
25041variable or subformula @cite{x}. The function @samp{islin(f,x)} checks
25042if formula @cite{f} is linear in @cite{x}, returning 1 if so. For
25043example, @samp{islin(x,x)}, @samp{islin(-x,x)}, @samp{islin(3,x)}, and
25044@samp{islin(x y / 3 - 2, x)} all return 1. The @samp{lin(f,x)} function
25045is similar, except that instead of returning 1 it returns the vector
25046@cite{[a, b, x]}. For the above examples, this vector would be
25047@cite{[0, 1, x]}, @cite{[0, -1, x]}, @cite{[3, 0, x]}, and
25048@cite{[-2, y/3, x]}, respectively. Both @code{lin} and @code{islin}
25049generally remain unevaluated for expressions which are not linear,
25050e.g., @samp{lin(2 x^2, x)} and @samp{lin(sin(x), x)}. The second
25051argument can also be a formula; @samp{islin(2 + 3 sin(x), sin(x))}
25052returns true.
25053
25054The @code{linnt} and @code{islinnt} functions perform a similar check,
25055but require a ``non-trivial'' linear form, which means that the
25056@cite{b} coefficient must be non-zero. For example, @samp{lin(2,x)}
25057returns @cite{[2, 0, x]} and @samp{lin(y,x)} returns @cite{[y, 0, x]},
25058but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
25059(in other words, these formulas are considered to be only ``trivially''
25060linear in @cite{x}).
25061
25062All four linearity-testing functions allow you to omit the second
25063argument, in which case the input may be linear in any non-constant
25064formula. Here, the @cite{a=0}, @cite{b=1} case is also considered
25065trivial, and only constant values for @cite{a} and @cite{b} are
25066recognized. Thus, @samp{lin(2 x y)} returns @cite{[0, 2, x y]},
25067@samp{lin(2 - x y)} returns @cite{[2, -1, x y]}, and @samp{lin(x y)}
25068returns @cite{[0, 1, x y]}. The @code{linnt} function would allow the
25069first two cases but not the third. Also, neither @code{lin} nor
25070@code{linnt} accept plain constants as linear in the one-argument
25071case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
25072
25073@c @starindex
25074@tindex istrue
25075The @samp{istrue(a)} function returns 1 if @cite{a} is a nonzero
25076number or provably nonzero formula, or 0 if @cite{a} is anything else.
25077Calls to @code{istrue} can only be manipulated if @kbd{m O} mode is
25078used to make sure they are not evaluated prematurely. (Note that
25079declarations are used when deciding whether a formula is true;
25080@code{istrue} returns 1 when @code{dnonzero} would return 1, and
25081it returns 0 when @code{dnonzero} would return 0 or leave itself
25082in symbolic form.)
25083
25084@node Rewrite Rules, , Logical Operations, Algebra
25085@section Rewrite Rules
25086
25087@noindent
25088@cindex Rewrite rules
25089@cindex Transformations
25090@cindex Pattern matching
25091@kindex a r
25092@pindex calc-rewrite
25093@tindex rewrite
25094The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
25095substitutions in a formula according to a specified pattern or patterns
25096known as @dfn{rewrite rules}. Whereas @kbd{a b} (@code{calc-substitute})
25097matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
25098matches only the @code{sin} function applied to the variable @code{x},
25099rewrite rules match general kinds of formulas; rewriting using the rule
25100@samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
25101it with @code{cos} of that same argument. The only significance of the
25102name @code{x} is that the same name is used on both sides of the rule.
25103
25104Rewrite rules rearrange formulas already in Calc's memory.
25105@xref{Syntax Tables}, to read about @dfn{syntax rules}, which are
25106similar to algebraic rewrite rules but operate when new algebraic
25107entries are being parsed, converting strings of characters into
25108Calc formulas.
25109
25110@menu
25111* Entering Rewrite Rules::
25112* Basic Rewrite Rules::
25113* Conditional Rewrite Rules::
25114* Algebraic Properties of Rewrite Rules::
25115* Other Features of Rewrite Rules::
25116* Composing Patterns in Rewrite Rules::
25117* Nested Formulas with Rewrite Rules::
25118* Multi-Phase Rewrite Rules::
25119* Selections with Rewrite Rules::
25120* Matching Commands::
25121* Automatic Rewrites::
25122* Debugging Rewrites::
25123* Examples of Rewrite Rules::
25124@end menu
25125
25126@node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
25127@subsection Entering Rewrite Rules
25128
25129@noindent
25130Rewrite rules normally use the ``assignment'' operator
25131@samp{@var{old} := @var{new}}.
25132This operator is equivalent to the function call @samp{assign(old, new)}.
25133The @code{assign} function is undefined by itself in Calc, so an
25134assignment formula such as a rewrite rule will be left alone by ordinary
25135Calc commands. But certain commands, like the rewrite system, interpret
25136assignments in special ways.@refill
25137
25138For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
25139every occurrence of the sine of something, squared, with one minus the
25140square of the cosine of that same thing. All by itself as a formula
25141on the stack it does nothing, but when given to the @kbd{a r} command
25142it turns that command into a sine-squared-to-cosine-squared converter.
25143
25144To specify a set of rules to be applied all at once, make a vector of
25145rules.
25146
25147When @kbd{a r} prompts you to enter the rewrite rules, you can answer
25148in several ways:
25149
25150@enumerate
25151@item
25152With a rule: @kbd{f(x) := g(x) RET}.
25153@item
25154With a vector of rules: @kbd{[f1(x) := g1(x), f2(x) := g2(x)] RET}.
25155(You can omit the enclosing square brackets if you wish.)
25156@item
25157With the name of a variable that contains the rule or rules vector:
25158@kbd{myrules RET}.
25159@item
25160With any formula except a rule, a vector, or a variable name; this
25161will be interpreted as the @var{old} half of a rewrite rule,
25162and you will be prompted a second time for the @var{new} half:
25163@kbd{f(x) @key{RET} g(x) @key{RET}}.
25164@item
25165With a blank line, in which case the rule, rules vector, or variable
25166will be taken from the top of the stack (and the formula to be
25167rewritten will come from the second-to-top position).
25168@end enumerate
25169
25170If you enter the rules directly (as opposed to using rules stored
25171in a variable), those rules will be put into the Trail so that you
25172can retrieve them later. @xref{Trail Commands}.
25173
25174It is most convenient to store rules you use often in a variable and
25175invoke them by giving the variable name. The @kbd{s e}
25176(@code{calc-edit-variable}) command is an easy way to create or edit a
25177rule set stored in a variable. You may also wish to use @kbd{s p}
25178(@code{calc-permanent-variable}) to save your rules permanently;
25179@pxref{Operations on Variables}.@refill
25180
25181Rewrite rules are compiled into a special internal form for faster
25182matching. If you enter a rule set directly it must be recompiled
25183every time. If you store the rules in a variable and refer to them
25184through that variable, they will be compiled once and saved away
25185along with the variable for later reference. This is another good
25186reason to store your rules in a variable.
25187
25188Calc also accepts an obsolete notation for rules, as vectors
25189@samp{[@var{old}, @var{new}]}. But because it is easily confused with a
25190vector of two rules, the use of this notation is no longer recommended.
25191
25192@node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
25193@subsection Basic Rewrite Rules
25194
25195@noindent
25196To match a particular formula @cite{x} with a particular rewrite rule
25197@samp{@var{old} := @var{new}}, Calc compares the structure of @cite{x} with
25198the structure of @var{old}. Variables that appear in @var{old} are
25199treated as @dfn{meta-variables}; the corresponding positions in @cite{x}
25200may contain any sub-formulas. For example, the pattern @samp{f(x,y)}
25201would match the expression @samp{f(12, a+1)} with the meta-variable
25202@samp{x} corresponding to 12 and with @samp{y} corresponding to
25203@samp{a+1}. However, this pattern would not match @samp{f(12)} or
25204@samp{g(12, a+1)}, since there is no assignment of the meta-variables
25205that will make the pattern match these expressions. Notice that if
25206the pattern is a single meta-variable, it will match any expression.
25207
25208If a given meta-variable appears more than once in @var{old}, the
25209corresponding sub-formulas of @cite{x} must be identical. Thus
25210the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
25211@samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(a+b, b+a)}.
25212(@xref{Conditional Rewrite Rules}, for a way to match the latter.)
25213
25214Things other than variables must match exactly between the pattern
25215and the target formula. To match a particular variable exactly, use
25216the pseudo-function @samp{quote(v)} in the pattern. For example, the
25217pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
25218@samp{sin(a)+y}.
25219
25220The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
25221@samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
25222literally. Thus the pattern @samp{sin(d + e + f)} acts exactly like
25223@samp{sin(d + quote(e) + f)}.
25224
25225If the @var{old} pattern is found to match a given formula, that
25226formula is replaced by @var{new}, where any occurrences in @var{new}
25227of meta-variables from the pattern are replaced with the sub-formulas
25228that they matched. Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
25229to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
25230
25231The normal @kbd{a r} command applies rewrite rules over and over
25232throughout the target formula until no further changes are possible
25233(up to a limit of 100 times). Use @kbd{C-u 1 a r} to make only one
25234change at a time.
25235
25236@node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
25237@subsection Conditional Rewrite Rules
25238
25239@noindent
25240A rewrite rule can also be @dfn{conditional}, written in the form
25241@samp{@var{old} := @var{new} :: @var{cond}}. (There is also the obsolete
25242form @samp{[@var{old}, @var{new}, @var{cond}]}.) If a @var{cond} part
25243is present in the
25244rule, this is an additional condition that must be satisfied before
25245the rule is accepted. Once @var{old} has been successfully matched
25246to the target expression, @var{cond} is evaluated (with all the
25247meta-variables substituted for the values they matched) and simplified
25248with @kbd{a s} (@code{calc-simplify}). If the result is a nonzero
25249number or any other object known to be nonzero (@pxref{Declarations}),
25250the rule is accepted. If the result is zero or if it is a symbolic
25251formula that is not known to be nonzero, the rule is rejected.
25252@xref{Logical Operations}, for a number of functions that return
252531 or 0 according to the results of various tests.@refill
25254
25255For example, the formula @samp{n > 0} simplifies to 1 or 0 if @cite{n}
25256is replaced by a positive or nonpositive number, respectively (or if
25257@cite{n} has been declared to be positive or nonpositive). Thus,
25258the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
25259@samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
25260(assuming no outstanding declarations for @cite{a}). In the case of
25261@samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
25262the case of @samp{f(12, a+1)}, the condition merely cannot be shown
25263to be satisfied, but that is enough to reject the rule.
25264
25265While Calc will use declarations to reason about variables in the
25266formula being rewritten, declarations do not apply to meta-variables.
25267For example, the rule @samp{f(a) := g(a+1)} will match for any values
25268of @samp{a}, such as complex numbers, vectors, or formulas, even if
25269@samp{a} has been declared to be real or scalar. If you want the
25270meta-variable @samp{a} to match only literal real numbers, use
25271@samp{f(a) := g(a+1) :: real(a)}. If you want @samp{a} to match only
25272reals and formulas which are provably real, use @samp{dreal(a)} as
25273the condition.
25274
25275The @samp{::} operator is a shorthand for the @code{condition}
25276function; @samp{@var{old} := @var{new} :: @var{cond}} is equivalent to
25277the formula @samp{condition(assign(@var{old}, @var{new}), @var{cond})}.
25278
25279If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
25280or @samp{... :: c1 && c2 && c3}. The two are entirely equivalent.
25281
25282It is also possible to embed conditions inside the pattern:
25283@samp{f(x :: x>0, y) := g(y+x, x)}. This is purely a notational
25284convenience, though; where a condition appears in a rule has no
25285effect on when it is tested. The rewrite-rule compiler automatically
25286decides when it is best to test each condition while a rule is being
25287matched.
25288
25289Certain conditions are handled as special cases by the rewrite rule
25290system and are tested very efficiently: Where @cite{x} is any
25291meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
25292@samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @cite{y}
25293is either a constant or another meta-variable and @samp{>=} may be
25294replaced by any of the six relational operators, and @samp{x % a = b}
25295where @cite{a} and @cite{b} are constants. Other conditions, like
25296@samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
25297since Calc must bring the whole evaluator and simplifier into play.
25298
25299An interesting property of @samp{::} is that neither of its arguments
25300will be touched by Calc's default simplifications. This is important
25301because conditions often are expressions that cannot safely be
25302evaluated early. For example, the @code{typeof} function never
25303remains in symbolic form; entering @samp{typeof(a)} will put the
25304number 100 (the type code for variables like @samp{a}) on the stack.
25305But putting the condition @samp{... :: typeof(a) = 6} on the stack
25306is safe since @samp{::} prevents the @code{typeof} from being
25307evaluated until the condition is actually used by the rewrite system.
25308
25309Since @samp{::} protects its lefthand side, too, you can use a dummy
25310condition to protect a rule that must itself not evaluate early.
25311For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
25312the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
25313where the meta-variable-ness of @code{f} on the righthand side has been
25314lost. But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
25315the condition @samp{1} is always true (nonzero) so it has no effect on
25316the functioning of the rule. (The rewrite compiler will ensure that
25317it doesn't even impact the speed of matching the rule.)
25318
25319@node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
25320@subsection Algebraic Properties of Rewrite Rules
25321
25322@noindent
25323The rewrite mechanism understands the algebraic properties of functions
25324like @samp{+} and @samp{*}. In particular, pattern matching takes
25325the associativity and commutativity of the following functions into
25326account:
25327
25328@smallexample
25329+ - * = != && || and or xor vint vunion vxor gcd lcm max min beta
25330@end smallexample
25331
25332For example, the rewrite rule:
25333
25334@example
25335a x + b x := (a + b) x
25336@end example
25337
25338@noindent
25339will match formulas of the form,
25340
25341@example
25342a x + b x, x a + x b, a x + x b, x a + b x
25343@end example
25344
25345Rewrites also understand the relationship between the @samp{+} and @samp{-}
25346operators. The above rewrite rule will also match the formulas,
25347
25348@example
25349a x - b x, x a - x b, a x - x b, x a - b x
25350@end example
25351
25352@noindent
25353by matching @samp{b} in the pattern to @samp{-b} from the formula.
25354
25355Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
25356pattern will check all pairs of terms for possible matches. The rewrite
25357will take whichever suitable pair it discovers first.
25358
25359In general, a pattern using an associative operator like @samp{a + b}
25360will try @i{2 n} different ways to match a sum of @i{n} terms
25361like @samp{x + y + z - w}. First, @samp{a} is matched against each
25362of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
25363being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
25364If none of these succeed, then @samp{b} is matched against each of the
25365four terms with @samp{a} matching the remainder. Half-and-half matches,
25366like @samp{(x + y) + (z - w)}, are not tried.
25367
25368Note that @samp{*} is not commutative when applied to matrices, but
25369rewrite rules pretend that it is. If you type @kbd{m v} to enable
25370matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
25371literally, ignoring its usual commutativity property. (In the
25372current implementation, the associativity also vanishes---it is as
25373if the pattern had been enclosed in a @code{plain} marker; see below.)
25374If you are applying rewrites to formulas with matrices, it's best to
25375enable matrix mode first to prevent algebraically incorrect rewrites
25376from occurring.
25377
25378The pattern @samp{-x} will actually match any expression. For example,
25379the rule
25380
25381@example
25382f(-x) := -f(x)
25383@end example
25384
25385@noindent
25386will rewrite @samp{f(a)} to @samp{-f(-a)}. To avoid this, either use
25387a @code{plain} marker as described below, or add a @samp{negative(x)}
25388condition. The @code{negative} function is true if its argument
25389``looks'' negative, for example, because it is a negative number or
25390because it is a formula like @samp{-x}. The new rule using this
25391condition is:
25392
25393@example
25394f(x) := -f(-x) :: negative(x) @r{or, equivalently,}
25395f(-x) := -f(x) :: negative(-x)
25396@end example
25397
25398In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
25399by matching @samp{y} to @samp{-b}.
25400
25401The pattern @samp{a b} will also match the formula @samp{x/y} if
25402@samp{y} is a number. Thus the rule @samp{a x + @w{b x} := (a+b) x}
25403will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
25404@samp{(a + 1:2) x}, depending on the current fraction mode).
25405
25406Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
25407@samp{^}. For example, the pattern @samp{f(a b)} will not match
25408@samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
25409though conceivably these patterns could match with @samp{a = b = x}.
25410Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
25411constant, even though it could be considered to match with @samp{a = x}
25412and @samp{b = 1/y}. The reasons are partly for efficiency, and partly
25413because while few mathematical operations are substantively different
25414for addition and subtraction, often it is preferable to treat the cases
25415of multiplication, division, and integer powers separately.
25416
25417Even more subtle is the rule set
25418
25419@example
25420[ f(a) + f(b) := f(a + b), -f(a) := f(-a) ]
25421@end example
25422
25423@noindent
25424attempting to match @samp{f(x) - f(y)}. You might think that Calc
25425will view this subtraction as @samp{f(x) + (-f(y))} and then apply
25426the above two rules in turn, but actually this will not work because
25427Calc only does this when considering rules for @samp{+} (like the
25428first rule in this set). So it will see first that @samp{f(x) + (-f(y))}
25429does not match @samp{f(a) + f(b)} for any assignments of the
25430meta-variables, and then it will see that @samp{f(x) - f(y)} does
25431not match @samp{-f(a)} for any assignment of @samp{a}. Because Calc
25432tries only one rule at a time, it will not be able to rewrite
25433@samp{f(x) - f(y)} with this rule set. An explicit @samp{f(a) - f(b)}
25434rule will have to be added.
25435
25436Another thing patterns will @emph{not} do is break up complex numbers.
25437The pattern @samp{myconj(a + @w{b i)} := a - b i} will work for formulas
25438involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
25439it will not match actual complex numbers like @samp{(3, -4)}. A version
25440of the above rule for complex numbers would be
25441
25442@example
25443myconj(a) := re(a) - im(a) (0,1) :: im(a) != 0
25444@end example
25445
25446@noindent
25447(Because the @code{re} and @code{im} functions understand the properties
25448of the special constant @samp{i}, this rule will also work for
25449@samp{3 - 4 i}. In fact, this particular rule would probably be better
25450without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
25451righthand side of the rule will still give the correct answer for the
25452conjugate of a real number.)
25453
25454It is also possible to specify optional arguments in patterns. The rule
25455
25456@example
25457opt(a) x + opt(b) (x^opt(c) + opt(d)) := f(a, b, c, d)
25458@end example
25459
25460@noindent
25461will match the formula
25462
25463@example
254645 (x^2 - 4) + 3 x
25465@end example
25466
25467@noindent
25468in a fairly straightforward manner, but it will also match reduced
25469formulas like
25470
25471@example
25472x + x^2, 2(x + 1) - x, x + x
25473@end example
25474
25475@noindent
25476producing, respectively,
25477
25478@example
25479f(1, 1, 2, 0), f(-1, 2, 1, 1), f(1, 1, 1, 0)
25480@end example
25481
25482(The latter two formulas can be entered only if default simplifications
25483have been turned off with @kbd{m O}.)
25484
25485The default value for a term of a sum is zero. The default value
25486for a part of a product, for a power, or for the denominator of a
25487quotient, is one. Also, @samp{-x} matches the pattern @samp{opt(a) b}
25488with @samp{a = -1}.
25489
25490In particular, the distributive-law rule can be refined to
25491
25492@example
25493opt(a) x + opt(b) x := (a + b) x
25494@end example
25495
25496@noindent
25497so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
25498
25499The pattern @samp{opt(a) + opt(b) x} matches almost any formulas which
25500are linear in @samp{x}. You can also use the @code{lin} and @code{islin}
25501functions with rewrite conditions to test for this; @pxref{Logical
25502Operations}. These functions are not as convenient to use in rewrite
25503rules, but they recognize more kinds of formulas as linear:
25504@samp{x/z} is considered linear with @cite{b = 1/z} by @code{lin},
25505but it will not match the above pattern because that pattern calls
25506for a multiplication, not a division.
25507
25508As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
25509by 1,
25510
25511@example
25512sin(x)^2 + cos(x)^2 := 1
25513@end example
25514
25515@noindent
25516misses many cases because the sine and cosine may both be multiplied by
25517an equal factor. Here's a more successful rule:
25518
25519@example
25520opt(a) sin(x)^2 + opt(a) cos(x)^2 := a
25521@end example
25522
25523Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
25524because one @cite{a} would have ``matched'' 1 while the other matched 6.
25525
25526Calc automatically converts a rule like
25527
25528@example
25529f(x-1, x) := g(x)
25530@end example
25531
25532@noindent
25533into the form
25534
25535@example
25536f(temp, x) := g(x) :: temp = x-1
25537@end example
25538
25539@noindent
25540(where @code{temp} stands for a new, invented meta-variable that
25541doesn't actually have a name). This modified rule will successfully
25542match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
25543respectively, then verifying that they differ by one even though
25544@samp{6} does not superficially look like @samp{x-1}.
25545
25546However, Calc does not solve equations to interpret a rule. The
25547following rule,
25548
25549@example
25550f(x-1, x+1) := g(x)
25551@end example
25552
25553@noindent
25554will not work. That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
25555but not @samp{f(6, 8)}. Calc always interprets at least one occurrence
25556of a variable by literal matching. If the variable appears ``isolated''
25557then Calc is smart enough to use it for literal matching. But in this
25558last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
25559:= g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
25560actual ``something-minus-one'' in the target formula.
25561
25562A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
25563You could make this resemble the original form more closely by using
25564@code{let} notation, which is described in the next section:
25565
25566@example
25567f(xm1, x+1) := g(x) :: let(x := xm1+1)
25568@end example
25569
25570Calc does this rewriting or ``conditionalizing'' for any sub-pattern
25571which involves only the functions in the following list, operating
25572only on constants and meta-variables which have already been matched
25573elsewhere in the pattern. When matching a function call, Calc is
25574careful to match arguments which are plain variables before arguments
25575which are calls to any of the functions below, so that a pattern like
25576@samp{f(x-1, x)} can be conditionalized even though the isolated
25577@samp{x} comes after the @samp{x-1}.
25578
25579@smallexample
25580+ - * / \ % ^ abs sign round rounde roundu trunc floor ceil
25581max min re im conj arg
25582@end smallexample
25583
25584You can suppress all of the special treatments described in this
25585section by surrounding a function call with a @code{plain} marker.
25586This marker causes the function call which is its argument to be
25587matched literally, without regard to commutativity, associativity,
25588negation, or conditionalization. When you use @code{plain}, the
25589``deep structure'' of the formula being matched can show through.
25590For example,
25591
25592@example
25593plain(a - a b) := f(a, b)
25594@end example
25595
25596@noindent
25597will match only literal subtractions. However, the @code{plain}
25598marker does not affect its arguments' arguments. In this case,
25599commutativity and associativity is still considered while matching
25600the @w{@samp{a b}} sub-pattern, so the whole pattern will match
25601@samp{x - y x} as well as @samp{x - x y}. We could go still
25602further and use
25603
25604@example
25605plain(a - plain(a b)) := f(a, b)
25606@end example
25607
25608@noindent
25609which would do a completely strict match for the pattern.
25610
25611By contrast, the @code{quote} marker means that not only the
25612function name but also the arguments must be literally the same.
25613The above pattern will match @samp{x - x y} but
25614
25615@example
25616quote(a - a b) := f(a, b)
25617@end example
25618
25619@noindent
25620will match only the single formula @samp{a - a b}. Also,
25621
25622@example
25623quote(a - quote(a b)) := f(a, b)
25624@end example
25625
25626@noindent
25627will match only @samp{a - quote(a b)}---probably not the desired
25628effect!
25629
25630A certain amount of algebra is also done when substituting the
25631meta-variables on the righthand side of a rule. For example,
25632in the rule
25633
25634@example
25635a + f(b) := f(a + b)
25636@end example
25637
25638@noindent
25639matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
25640taken literally, but the rewrite mechanism will simplify the
25641righthand side to @samp{f(x - y)} automatically. (Of course,
25642the default simplifications would do this anyway, so this
25643special simplification is only noticeable if you have turned the
25644default simplifications off.) This rewriting is done only when
25645a meta-variable expands to a ``negative-looking'' expression.
25646If this simplification is not desirable, you can use a @code{plain}
25647marker on the righthand side:
25648
25649@example
25650a + f(b) := f(plain(a + b))
25651@end example
25652
25653@noindent
25654In this example, we are still allowing the pattern-matcher to
25655use all the algebra it can muster, but the righthand side will
25656always simplify to a literal addition like @samp{f((-y) + x)}.
25657
25658@node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
25659@subsection Other Features of Rewrite Rules
25660
25661@noindent
25662Certain ``function names'' serve as markers in rewrite rules.
25663Here is a complete list of these markers. First are listed the
25664markers that work inside a pattern; then come the markers that
25665work in the righthand side of a rule.
25666
25667@c @starindex
25668@tindex import
25669One kind of marker, @samp{import(x)}, takes the place of a whole
25670rule. Here @cite{x} is the name of a variable containing another
25671rule set; those rules are ``spliced into'' the rule set that
25672imports them. For example, if @samp{[f(a+b) := f(a) + f(b),
25673f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
25674then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
25675all three rules. It is possible to modify the imported rules
25676slightly: @samp{import(x, v1, x1, v2, x2, @dots{})} imports
25677the rule set @cite{x} with all occurrences of @c{$v_1$}
25678@cite{v1}, as either
25679a variable name or a function name, replaced with @c{$x_1$}
25680@cite{x1} and
25681so on. (If @c{$v_1$}
25682@cite{v1} is used as a function name, then @c{$x_1$}
25683@cite{x1}
25684must be either a function name itself or a @w{@samp{< >}} nameless
25685function; @pxref{Specifying Operators}.) For example, @samp{[g(0) := 0,
25686import(linearF, f, g)]} applies the linearity rules to the function
25687@samp{g} instead of @samp{f}. Imports can be nested, but the
25688import-with-renaming feature may fail to rename sub-imports properly.
25689
25690The special functions allowed in patterns are:
25691
25692@table @samp
25693@item quote(x)
25694@c @starindex
25695@tindex quote
25696This pattern matches exactly @cite{x}; variable names in @cite{x} are
25697not interpreted as meta-variables. The only flexibility is that
25698numbers are compared for numeric equality, so that the pattern
25699@samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
25700(Numbers are always treated this way by the rewrite mechanism:
25701The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
25702The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
25703as a result in this case.)
25704
25705@item plain(x)
25706@c @starindex
25707@tindex plain
25708Here @cite{x} must be a function call @samp{f(x1,x2,@dots{})}. This
25709pattern matches a call to function @cite{f} with the specified
25710argument patterns. No special knowledge of the properties of the
25711function @cite{f} is used in this case; @samp{+} is not commutative or
25712associative. Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
25713are treated as patterns. If you wish them to be treated ``plainly''
25714as well, you must enclose them with more @code{plain} markers:
25715@samp{plain(plain(@w{-a}) + plain(b c))}.
25716
25717@item opt(x,def)
25718@c @starindex
25719@tindex opt
25720Here @cite{x} must be a variable name. This must appear as an
25721argument to a function or an element of a vector; it specifies that
25722the argument or element is optional.
25723As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
25724or as the second argument to @samp{/} or @samp{^}, the value @var{def}
25725may be omitted. The pattern @samp{x + opt(y)} matches a sum by
25726binding one summand to @cite{x} and the other to @cite{y}, and it
25727matches anything else by binding the whole expression to @cite{x} and
25728zero to @cite{y}. The other operators above work similarly.@refill
25729
25730For general miscellanous functions, the default value @code{def}
25731must be specified. Optional arguments are dropped starting with
25732the rightmost one during matching. For example, the pattern
25733@samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
25734or @samp{f(a,b,c)}. Default values of zero and @cite{b} are
25735supplied in this example for the omitted arguments. Note that
25736the literal variable @cite{b} will be the default in the latter
25737case, @emph{not} the value that matched the meta-variable @cite{b}.
25738In other words, the default @var{def} is effectively quoted.
25739
25740@item condition(x,c)
25741@c @starindex
25742@tindex condition
25743@tindex ::
25744This matches the pattern @cite{x}, with the attached condition
25745@cite{c}. It is the same as @samp{x :: c}.
25746
25747@item pand(x,y)
25748@c @starindex
25749@tindex pand
25750@tindex &&&
25751This matches anything that matches both pattern @cite{x} and
25752pattern @cite{y}. It is the same as @samp{x &&& y}.
25753@pxref{Composing Patterns in Rewrite Rules}.
25754
25755@item por(x,y)
25756@c @starindex
25757@tindex por
25758@tindex |||
25759This matches anything that matches either pattern @cite{x} or
25760pattern @cite{y}. It is the same as @w{@samp{x ||| y}}.
25761
25762@item pnot(x)
25763@c @starindex
25764@tindex pnot
25765@tindex !!!
25766This matches anything that does not match pattern @cite{x}.
25767It is the same as @samp{!!! x}.
25768
25769@item cons(h,t)
25770@c @mindex cons
25771@tindex cons (rewrites)
25772This matches any vector of one or more elements. The first
25773element is matched to @cite{h}; a vector of the remaining
25774elements is matched to @cite{t}. Note that vectors of fixed
25775length can also be matched as actual vectors: The rule
25776@samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
25777to the rule @samp{[a,b] := [a+b]}.
25778
25779@item rcons(t,h)
25780@c @mindex rcons
25781@tindex rcons (rewrites)
25782This is like @code{cons}, except that the @emph{last} element
25783is matched to @cite{h}, with the remaining elements matched
25784to @cite{t}.
25785
25786@item apply(f,args)
25787@c @mindex apply
25788@tindex apply (rewrites)
25789This matches any function call. The name of the function, in
25790the form of a variable, is matched to @cite{f}. The arguments
25791of the function, as a vector of zero or more objects, are
25792matched to @samp{args}. Constants, variables, and vectors
25793do @emph{not} match an @code{apply} pattern. For example,
25794@samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
25795matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
25796matches any function call with exactly two arguments, and
25797@samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
25798to the function @samp{f} with two or more arguments. Another
25799way to implement the latter, if the rest of the rule does not
25800need to refer to the first two arguments of @samp{f} by name,
25801would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
25802Here's a more interesting sample use of @code{apply}:
25803
25804@example
25805apply(f,[x+n]) := n + apply(f,[x])
25806 :: in(f, [floor,ceil,round,trunc]) :: integer(n)
25807@end example
25808
25809Note, however, that this will be slower to match than a rule
25810set with four separate rules. The reason is that Calc sorts
25811the rules of a rule set according to top-level function name;
25812if the top-level function is @code{apply}, Calc must try the
25813rule for every single formula and sub-formula. If the top-level
25814function in the pattern is, say, @code{floor}, then Calc invokes
25815the rule only for sub-formulas which are calls to @code{floor}.
25816
25817Formulas normally written with operators like @code{+} are still
25818considered function calls: @code{apply(f,x)} matches @samp{a+b}
25819with @samp{f = add}, @samp{x = [a,b]}.
25820
25821You must use @code{apply} for meta-variables with function names
25822on both sides of a rewrite rule: @samp{apply(f, [x]) := f(x+1)}
25823is @emph{not} correct, because it rewrites @samp{spam(6)} into
25824@samp{f(7)}. The righthand side should be @samp{apply(f, [x+1])}.
25825Also note that you will have to use no-simplify (@kbd{m O})
25826mode when entering this rule so that the @code{apply} isn't
25827evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
25828Or, use @kbd{s e} to enter the rule without going through the stack,
25829or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) @w{:: 1}}.
25830@xref{Conditional Rewrite Rules}.
25831
25832@item select(x)
25833@c @starindex
25834@tindex select
25835This is used for applying rules to formulas with selections;
25836@pxref{Selections with Rewrite Rules}.
25837@end table
25838
25839Special functions for the righthand sides of rules are:
25840
25841@table @samp
25842@item quote(x)
25843The notation @samp{quote(x)} is changed to @samp{x} when the
25844righthand side is used. As far as the rewrite rule is concerned,
25845@code{quote} is invisible. However, @code{quote} has the special
25846property in Calc that its argument is not evaluated. Thus,
25847while it will not work to put the rule @samp{t(a) := typeof(a)}
25848on the stack because @samp{typeof(a)} is evaluated immediately
25849to produce @samp{t(a) := 100}, you can use @code{quote} to
25850protect the righthand side: @samp{t(a) := quote(typeof(a))}.
25851(@xref{Conditional Rewrite Rules}, for another trick for
25852protecting rules from evaluation.)
25853
25854@item plain(x)
25855Special properties of and simplifications for the function call
25856@cite{x} are not used. One interesting case where @code{plain}
25857is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
25858shorthand notation for the @code{quote} function. This rule will
25859not work as shown; instead of replacing @samp{q(foo)} with
25860@samp{quote(foo)}, it will replace it with @samp{foo}! The correct
25861rule would be @samp{q(x) := plain(quote(x))}.
25862
25863@item cons(h,t)
25864Where @cite{t} is a vector, this is converted into an expanded
25865vector during rewrite processing. Note that @code{cons} is a regular
25866Calc function which normally does this anyway; the only way @code{cons}
25867is treated specially by rewrites is that @code{cons} on the righthand
25868side of a rule will be evaluated even if default simplifications
25869have been turned off.
25870
25871@item rcons(t,h)
25872Analogous to @code{cons} except putting @cite{h} at the @emph{end} of
25873the vector @cite{t}.
25874
25875@item apply(f,args)
25876Where @cite{f} is a variable and @var{args} is a vector, this
25877is converted to a function call. Once again, note that @code{apply}
25878is also a regular Calc function.
25879
25880@item eval(x)
25881@c @starindex
25882@tindex eval
25883The formula @cite{x} is handled in the usual way, then the
25884default simplifications are applied to it even if they have
25885been turned off normally. This allows you to treat any function
25886similarly to the way @code{cons} and @code{apply} are always
25887treated. However, there is a slight difference: @samp{cons(2+3, [])}
25888with default simplifications off will be converted to @samp{[2+3]},
25889whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
25890
25891@item evalsimp(x)
25892@c @starindex
25893@tindex evalsimp
25894The formula @cite{x} has meta-variables substituted in the usual
25895way, then algebraically simplified as if by the @kbd{a s} command.
25896
25897@item evalextsimp(x)
25898@c @starindex
25899@tindex evalextsimp
25900The formula @cite{x} has meta-variables substituted in the normal
25901way, then ``extendedly'' simplified as if by the @kbd{a e} command.
25902
25903@item select(x)
25904@xref{Selections with Rewrite Rules}.
25905@end table
25906
25907There are also some special functions you can use in conditions.
25908
25909@table @samp
25910@item let(v := x)
25911@c @starindex
25912@tindex let
25913The expression @cite{x} is evaluated with meta-variables substituted.
25914The @kbd{a s} command's simplifications are @emph{not} applied by
25915default, but @cite{x} can include calls to @code{evalsimp} or
25916@code{evalextsimp} as described above to invoke higher levels
25917of simplification. The
25918result of @cite{x} is then bound to the meta-variable @cite{v}. As
25919usual, if this meta-variable has already been matched to something
25920else the two values must be equal; if the meta-variable is new then
25921it is bound to the result of the expression. This variable can then
25922appear in later conditions, and on the righthand side of the rule.
25923In fact, @cite{v} may be any pattern in which case the result of
25924evaluating @cite{x} is matched to that pattern, binding any
25925meta-variables that appear in that pattern. Note that @code{let}
25926can only appear by itself as a condition, or as one term of an
25927@samp{&&} which is a whole condition: It cannot be inside
25928an @samp{||} term or otherwise buried.@refill
25929
25930The alternate, equivalent form @samp{let(v, x)} is also recognized.
25931Note that the use of @samp{:=} by @code{let}, while still being
25932assignment-like in character, is unrelated to the use of @samp{:=}
25933in the main part of a rewrite rule.
25934
25935As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
25936replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
25937that inverse exists and is constant. For example, if @samp{a} is a
25938singular matrix the operation @samp{1/a} is left unsimplified and
25939@samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
25940then the rule succeeds. Without @code{let} there would be no way
25941to express this rule that didn't have to invert the matrix twice.
25942Note that, because the meta-variable @samp{ia} is otherwise unbound
25943in this rule, the @code{let} condition itself always ``succeeds''
25944because no matter what @samp{1/a} evaluates to, it can successfully
25945be bound to @code{ia}.@refill
25946
25947Here's another example, for integrating cosines of linear
25948terms: @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
25949The @code{lin} function returns a 3-vector if its argument is linear,
25950or leaves itself unevaluated if not. But an unevaluated @code{lin}
25951call will not match the 3-vector on the lefthand side of the @code{let},
25952so this @code{let} both verifies that @code{y} is linear, and binds
25953the coefficients @code{a} and @code{b} for use elsewhere in the rule.
25954(It would have been possible to use @samp{sin(a x + b)/b} for the
25955righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
25956rearrangement of the argument of the sine.)@refill
25957
25958@c @starindex
25959@tindex ierf
25960Similarly, here is a rule that implements an inverse-@code{erf}
25961function. It uses @code{root} to search for a solution. If
25962@code{root} succeeds, it will return a vector of two numbers
25963where the first number is the desired solution. If no solution
25964is found, @code{root} remains in symbolic form. So we use
25965@code{let} to check that the result was indeed a vector.
25966
25967@example
25968ierf(x) := y :: let([y,z] := root(erf(a) = x, a, .5))
25969@end example
25970
25971@item matches(v,p)
25972The meta-variable @var{v}, which must already have been matched
25973to something elsewhere in the rule, is compared against pattern
25974@var{p}. Since @code{matches} is a standard Calc function, it
25975can appear anywhere in a condition. But if it appears alone or
25976as a term of a top-level @samp{&&}, then you get the special
25977extra feature that meta-variables which are bound to things
25978inside @var{p} can be used elsewhere in the surrounding rewrite
25979rule.
25980
25981The only real difference between @samp{let(p := v)} and
25982@samp{matches(v, p)} is that the former evaluates @samp{v} using
25983the default simplifications, while the latter does not.
25984
25985@item remember
25986@vindex remember
25987This is actually a variable, not a function. If @code{remember}
25988appears as a condition in a rule, then when that rule succeeds
25989the original expression and rewritten expression are added to the
25990front of the rule set that contained the rule. If the rule set
25991was not stored in a variable, @code{remember} is ignored. The
25992lefthand side is enclosed in @code{quote} in the added rule if it
25993contains any variables.
25994
25995For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
25996to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
25997of the rule set. The rule set @code{EvalRules} works slightly
25998differently: There, the evaluation of @samp{f(6)} will complete before
25999the result is added to the rule set, in this case as @samp{f(7) := 5040}.
26000Thus @code{remember} is most useful inside @code{EvalRules}.
26001
26002It is up to you to ensure that the optimization performed by
26003@code{remember} is safe. For example, the rule @samp{foo(n) := n
26004:: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
26005the function equivalent of the @kbd{=} command); if the variable
26006@code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
26007be added to the rule set and will continue to operate even if
26008@code{eatfoo} is later changed to 0.
26009
26010@item remember(c)
26011@c @starindex
26012@tindex remember
26013Remember the match as described above, but only if condition @cite{c}
26014is true. For example, @samp{remember(n % 4 = 0)} in the above factorial
26015rule remembers only every fourth result. Note that @samp{remember(1)}
26016is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
26017@end table
26018
26019@node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
26020@subsection Composing Patterns in Rewrite Rules
26021
26022@noindent
26023There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
26024that combine rewrite patterns to make larger patterns. The
26025combinations are ``and,'' ``or,'' and ``not,'' respectively, and
26026these operators are the pattern equivalents of @samp{&&}, @samp{||}
26027and @samp{!} (which operate on zero-or-nonzero logical values).
26028
26029Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
26030form by all regular Calc features; they have special meaning only in
26031the context of rewrite rule patterns.
26032
26033The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
26034matches both @var{p1} and @var{p2}. One especially useful case is
26035when one of @var{p1} or @var{p2} is a meta-variable. For example,
26036here is a rule that operates on error forms:
26037
26038@example
26039f(x &&& a +/- b, x) := g(x)
26040@end example
26041
26042This does the same thing, but is arguably simpler than, the rule
26043
26044@example
26045f(a +/- b, a +/- b) := g(a +/- b)
26046@end example
26047
26048@c @starindex
26049@tindex ends
26050Here's another interesting example:
26051
26052@example
26053ends(cons(a, x) &&& rcons(y, b)) := [a, b]
26054@end example
26055
26056@noindent
26057which effectively clips out the middle of a vector leaving just
26058the first and last elements. This rule will change a one-element
26059vector @samp{[a]} to @samp{[a, a]}. The similar rule
26060
26061@example
26062ends(cons(a, rcons(y, b))) := [a, b]
26063@end example
26064
26065@noindent
26066would do the same thing except that it would fail to match a
26067one-element vector.
26068
26069@tex
26070\bigskip
26071@end tex
26072
26073The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
26074matches either @var{p1} or @var{p2}. Calc first tries matching
26075against @var{p1}; if that fails, it goes on to try @var{p2}.
26076
26077@c @starindex
26078@tindex curve
26079A simple example of @samp{|||} is
26080
26081@example
26082curve(inf ||| -inf) := 0
26083@end example
26084
26085@noindent
26086which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
26087
26088Here is a larger example:
26089
26090@example
26091log(a, b) ||| (ln(a) :: let(b := e)) := mylog(a, b)
26092@end example
26093
26094This matches both generalized and natural logarithms in a single rule.
26095Note that the @samp{::} term must be enclosed in parentheses because
26096that operator has lower precedence than @samp{|||} or @samp{:=}.
26097
26098(In practice this rule would probably include a third alternative,
26099omitted here for brevity, to take care of @code{log10}.)
26100
26101While Calc generally treats interior conditions exactly the same as
26102conditions on the outside of a rule, it does guarantee that if all the
26103variables in the condition are special names like @code{e}, or already
26104bound in the pattern to which the condition is attached (say, if
26105@samp{a} had appeared in this condition), then Calc will process this
26106condition right after matching the pattern to the left of the @samp{::}.
26107Thus, we know that @samp{b} will be bound to @samp{e} only if the
26108@code{ln} branch of the @samp{|||} was taken.
26109
26110Note that this rule was careful to bind the same set of meta-variables
26111on both sides of the @samp{|||}. Calc does not check this, but if
26112you bind a certain meta-variable only in one branch and then use that
26113meta-variable elsewhere in the rule, results are unpredictable:
26114
26115@example
26116f(a,b) ||| g(b) := h(a,b)
26117@end example
26118
26119Here if the pattern matches @samp{g(17)}, Calc makes no promises about
26120the value that will be substituted for @samp{a} on the righthand side.
26121
26122@tex
26123\bigskip
26124@end tex
26125
26126The pattern @samp{!!! @var{pat}} matches anything that does not
26127match @var{pat}. Any meta-variables that are bound while matching
26128@var{pat} remain unbound outside of @var{pat}.
26129
26130For example,
26131
26132@example
26133f(x &&& !!! a +/- b, !!![]) := g(x)
26134@end example
26135
26136@noindent
26137converts @code{f} whose first argument is anything @emph{except} an
26138error form, and whose second argument is not the empty vector, into
26139a similar call to @code{g} (but without the second argument).
26140
26141If we know that the second argument will be a vector (empty or not),
26142then an equivalent rule would be:
26143
26144@example
26145f(x, y) := g(x) :: typeof(x) != 7 :: vlen(y) > 0
26146@end example
26147
26148@noindent
26149where of course 7 is the @code{typeof} code for error forms.
26150Another final condition, that works for any kind of @samp{y},
26151would be @samp{!istrue(y == [])}. (The @code{istrue} function
26152returns an explicit 0 if its argument was left in symbolic form;
26153plain @samp{!(y == [])} or @samp{y != []} would not work to replace
26154@samp{!!![]} since these would be left unsimplified, and thus cause
26155the rule to fail, if @samp{y} was something like a variable name.)
26156
26157It is possible for a @samp{!!!} to refer to meta-variables bound
26158elsewhere in the pattern. For example,
26159
26160@example
26161f(a, !!!a) := g(a)
26162@end example
26163
26164@noindent
26165matches any call to @code{f} with different arguments, changing
26166this to @code{g} with only the first argument.
26167
26168If a function call is to be matched and one of the argument patterns
26169contains a @samp{!!!} somewhere inside it, that argument will be
26170matched last. Thus
26171
26172@example
26173f(!!!a, a) := g(a)
26174@end example
26175
26176@noindent
26177will be careful to bind @samp{a} to the second argument of @code{f}
26178before testing the first argument. If Calc had tried to match the
26179first argument of @code{f} first, the results would have been
26180disasterous: Since @code{a} was unbound so far, the pattern @samp{a}
26181would have matched anything at all, and the pattern @samp{!!!a}
26182therefore would @emph{not} have matched anything at all!
26183
26184@node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
26185@subsection Nested Formulas with Rewrite Rules
26186
26187@noindent
26188When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
26189the top of the stack and attempts to match any of the specified rules
26190to any part of the expression, starting with the whole expression
26191and then, if that fails, trying deeper and deeper sub-expressions.
26192For each part of the expression, the rules are tried in the order
26193they appear in the rules vector. The first rule to match the first
26194sub-expression wins; it replaces the matched sub-expression according
26195to the @var{new} part of the rule.
26196
26197Often, the rule set will match and change the formula several times.
26198The top-level formula is first matched and substituted repeatedly until
26199it no longer matches the pattern; then, sub-formulas are tried, and
26200so on. Once every part of the formula has gotten its chance, the
26201rewrite mechanism starts over again with the top-level formula
26202(in case a substitution of one of its arguments has caused it again
26203to match). This continues until no further matches can be made
26204anywhere in the formula.
26205
26206It is possible for a rule set to get into an infinite loop. The
26207most obvious case, replacing a formula with itself, is not a problem
26208because a rule is not considered to ``succeed'' unless the righthand
26209side actually comes out to something different than the original
26210formula or sub-formula that was matched. But if you accidentally
26211had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
26212@samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
26213run forever switching a formula back and forth between the two
26214forms.
26215
26216To avoid disaster, Calc normally stops after 100 changes have been
26217made to the formula. This will be enough for most multiple rewrites,
26218but it will keep an endless loop of rewrites from locking up the
26219computer forever. (On most systems, you can also type @kbd{C-g} to
26220halt any Emacs command prematurely.)
26221
26222To change this limit, give a positive numeric prefix argument.
26223In particular, @kbd{M-1 a r} applies only one rewrite at a time,
26224useful when you are first testing your rule (or just if repeated
26225rewriting is not what is called for by your application).
26226
26227@c @starindex
26228@c @mindex iter@idots
26229@tindex iterations
26230You can also put a ``function call'' @samp{iterations(@var{n})}
26231in place of a rule anywhere in your rules vector (but usually at
26232the top). Then, @var{n} will be used instead of 100 as the default
26233number of iterations for this rule set. You can use
26234@samp{iterations(inf)} if you want no iteration limit by default.
26235A prefix argument will override the @code{iterations} limit in the
26236rule set.
26237
26238@example
26239[ iterations(1),
26240 f(x) := f(x+1) ]
26241@end example
26242
26243More precisely, the limit controls the number of ``iterations,''
26244where each iteration is a successful matching of a rule pattern whose
26245righthand side, after substituting meta-variables and applying the
26246default simplifications, is different from the original sub-formula
26247that was matched.
26248
26249A prefix argument of zero sets the limit to infinity. Use with caution!
26250
26251Given a negative numeric prefix argument, @kbd{a r} will match and
26252substitute the top-level expression up to that many times, but
26253will not attempt to match the rules to any sub-expressions.
26254
26255In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
26256does a rewriting operation. Here @var{expr} is the expression
26257being rewritten, @var{rules} is the rule, vector of rules, or
26258variable containing the rules, and @var{n} is the optional
26259iteration limit, which may be a positive integer, a negative
26260integer, or @samp{inf} or @samp{-inf}. If @var{n} is omitted
26261the @code{iterations} value from the rule set is used; if both
26262are omitted, 100 is used.
26263
26264@node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
26265@subsection Multi-Phase Rewrite Rules
26266
26267@noindent
26268It is possible to separate a rewrite rule set into several @dfn{phases}.
26269During each phase, certain rules will be enabled while certain others
26270will be disabled. A @dfn{phase schedule} controls the order in which
26271phases occur during the rewriting process.
26272
26273@c @starindex
26274@tindex phase
26275@vindex all
26276If a call to the marker function @code{phase} appears in the rules
26277vector in place of a rule, all rules following that point will be
26278members of the phase(s) identified in the arguments to @code{phase}.
26279Phases are given integer numbers. The markers @samp{phase()} and
26280@samp{phase(all)} both mean the following rules belong to all phases;
26281this is the default at the start of the rule set.
26282
26283If you do not explicitly schedule the phases, Calc sorts all phase
26284numbers that appear in the rule set and executes the phases in
26285ascending order. For example, the rule set
26286
26287@group
26288@example
26289[ f0(x) := g0(x),
26290 phase(1),
26291 f1(x) := g1(x),
26292 phase(2),
26293 f2(x) := g2(x),
26294 phase(3),
26295 f3(x) := g3(x),
26296 phase(1,2),
26297 f4(x) := g4(x) ]
26298@end example
26299@end group
26300
26301@noindent
26302has three phases, 1 through 3. Phase 1 consists of the @code{f0},
26303@code{f1}, and @code{f4} rules (in that order). Phase 2 consists of
26304@code{f0}, @code{f2}, and @code{f4}. Phase 3 consists of @code{f0}
26305and @code{f3}.
26306
26307When Calc rewrites a formula using this rule set, it first rewrites
26308the formula using only the phase 1 rules until no further changes are
26309possible. Then it switches to the phase 2 rule set and continues
26310until no further changes occur, then finally rewrites with phase 3.
26311When no more phase 3 rules apply, rewriting finishes. (This is
26312assuming @kbd{a r} with a large enough prefix argument to allow the
26313rewriting to run to completion; the sequence just described stops
26314early if the number of iterations specified in the prefix argument,
26315100 by default, is reached.)
26316
26317During each phase, Calc descends through the nested levels of the
26318formula as described previously. (@xref{Nested Formulas with Rewrite
26319Rules}.) Rewriting starts at the top of the formula, then works its
26320way down to the parts, then goes back to the top and works down again.
26321The phase 2 rules do not begin until no phase 1 rules apply anywhere
26322in the formula.
26323
26324@c @starindex
26325@tindex schedule
26326A @code{schedule} marker appearing in the rule set (anywhere, but
26327conventionally at the top) changes the default schedule of phases.
26328In the simplest case, @code{schedule} has a sequence of phase numbers
26329for arguments; each phase number is invoked in turn until the
26330arguments to @code{schedule} are exhausted. Thus adding
26331@samp{schedule(3,2,1)} at the top of the above rule set would
26332reverse the order of the phases; @samp{schedule(1,2,3)} would have
26333no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
26334would give phase 1 a second chance after phase 2 has completed, before
26335moving on to phase 3.
26336
26337Any argument to @code{schedule} can instead be a vector of phase
26338numbers (or even of sub-vectors). Then the sub-sequence of phases
26339described by the vector are tried repeatedly until no change occurs
26340in any phase in the sequence. For example, @samp{schedule([1, 2], 3)}
26341tries phase 1, then phase 2, then, if either phase made any changes
26342to the formula, repeats these two phases until they can make no
26343further progress. Finally, it goes on to phase 3 for finishing
26344touches.
26345
26346Also, items in @code{schedule} can be variable names as well as
26347numbers. A variable name is interpreted as the name of a function
26348to call on the whole formula. For example, @samp{schedule(1, simplify)}
26349says to apply the phase-1 rules (presumably, all of them), then to
26350call @code{simplify} which is the function name equivalent of @kbd{a s}.
26351Likewise, @samp{schedule([1, simplify])} says to alternate between
26352phase 1 and @kbd{a s} until no further changes occur.
26353
26354Phases can be used purely to improve efficiency; if it is known that
26355a certain group of rules will apply only at the beginning of rewriting,
26356and a certain other group will apply only at the end, then rewriting
26357will be faster if these groups are identified as separate phases.
26358Once the phase 1 rules are done, Calc can put them aside and no longer
26359spend any time on them while it works on phase 2.
26360
26361There are also some problems that can only be solved with several
26362rewrite phases. For a real-world example of a multi-phase rule set,
26363examine the set @code{FitRules}, which is used by the curve-fitting
26364command to convert a model expression to linear form.
26365@xref{Curve Fitting Details}. This set is divided into four phases.
26366The first phase rewrites certain kinds of expressions to be more
26367easily linearizable, but less computationally efficient. After the
26368linear components have been picked out, the final phase includes the
26369opposite rewrites to put each component back into an efficient form.
26370If both sets of rules were included in one big phase, Calc could get
26371into an infinite loop going back and forth between the two forms.
26372
26373Elsewhere in @code{FitRules}, the components are first isolated,
26374then recombined where possible to reduce the complexity of the linear
26375fit, then finally packaged one component at a time into vectors.
26376If the packaging rules were allowed to begin before the recombining
26377rules were finished, some components might be put away into vectors
26378before they had a chance to recombine. By putting these rules in
26379two separate phases, this problem is neatly avoided.
26380
26381@node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
26382@subsection Selections with Rewrite Rules
26383
26384@noindent
26385If a sub-formula of the current formula is selected (as by @kbd{j s};
26386@pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
26387command applies only to that sub-formula. Together with a negative
26388prefix argument, you can use this fact to apply a rewrite to one
26389specific part of a formula without affecting any other parts.
26390
26391@kindex j r
26392@pindex calc-rewrite-selection
26393The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
26394sophisticated operations on selections. This command prompts for
26395the rules in the same way as @kbd{a r}, but it then applies those
26396rules to the whole formula in question even though a sub-formula
26397of it has been selected. However, the selected sub-formula will
26398first have been surrounded by a @samp{select( )} function call.
26399(Calc's evaluator does not understand the function name @code{select};
26400this is only a tag used by the @kbd{j r} command.)
26401
26402For example, suppose the formula on the stack is @samp{2 (a + b)^2}
26403and the sub-formula @samp{a + b} is selected. This formula will
26404be rewritten to @samp{2 select(a + b)^2} and then the rewrite
26405rules will be applied in the usual way. The rewrite rules can
26406include references to @code{select} to tell where in the pattern
26407the selected sub-formula should appear.
26408
26409If there is still exactly one @samp{select( )} function call in
26410the formula after rewriting is done, it indicates which part of
26411the formula should be selected afterwards. Otherwise, the
26412formula will be unselected.
26413
26414You can make @kbd{j r} act much like @kbd{a r} by enclosing both parts
26415of the rewrite rule with @samp{select()}. However, @kbd{j r}
26416allows you to use the current selection in more flexible ways.
26417Suppose you wished to make a rule which removed the exponent from
26418the selected term; the rule @samp{select(a)^x := select(a)} would
26419work. In the above example, it would rewrite @samp{2 select(a + b)^2}
26420to @samp{2 select(a + b)}. This would then be returned to the
26421stack as @samp{2 (a + b)} with the @samp{a + b} selected.
26422
26423The @kbd{j r} command uses one iteration by default, unlike
26424@kbd{a r} which defaults to 100 iterations. A numeric prefix
26425argument affects @kbd{j r} in the same way as @kbd{a r}.
26426@xref{Nested Formulas with Rewrite Rules}.
26427
26428As with other selection commands, @kbd{j r} operates on the stack
26429entry that contains the cursor. (If the cursor is on the top-of-stack
26430@samp{.} marker, it works as if the cursor were on the formula
26431at stack level 1.)
26432
26433If you don't specify a set of rules, the rules are taken from the
26434top of the stack, just as with @kbd{a r}. In this case, the
26435cursor must indicate stack entry 2 or above as the formula to be
26436rewritten (otherwise the same formula would be used as both the
26437target and the rewrite rules).
26438
26439If the indicated formula has no selection, the cursor position within
26440the formula temporarily selects a sub-formula for the purposes of this
26441command. If the cursor is not on any sub-formula (e.g., it is in
26442the line-number area to the left of the formula), the @samp{select( )}
26443markers are ignored by the rewrite mechanism and the rules are allowed
26444to apply anywhere in the formula.
26445
26446As a special feature, the normal @kbd{a r} command also ignores
26447@samp{select( )} calls in rewrite rules. For example, if you used the
26448above rule @samp{select(a)^x := select(a)} with @kbd{a r}, it would apply
26449the rule as if it were @samp{a^x := a}. Thus, you can write general
26450purpose rules with @samp{select( )} hints inside them so that they
26451will ``do the right thing'' in both @kbd{a r} and @kbd{j r},
26452both with and without selections.
26453
26454@node Matching Commands, Automatic Rewrites, Selections with Rewrite Rules, Rewrite Rules
26455@subsection Matching Commands
26456
26457@noindent
26458@kindex a m
26459@pindex calc-match
26460@tindex match
26461The @kbd{a m} (@code{calc-match}) [@code{match}] function takes a
26462vector of formulas and a rewrite-rule-style pattern, and produces
26463a vector of all formulas which match the pattern. The command
26464prompts you to enter the pattern; as for @kbd{a r}, you can enter
26465a single pattern (i.e., a formula with meta-variables), or a
26466vector of patterns, or a variable which contains patterns, or
26467you can give a blank response in which case the patterns are taken
26468from the top of the stack. The pattern set will be compiled once
26469and saved if it is stored in a variable. If there are several
26470patterns in the set, vector elements are kept if they match any
26471of the patterns.
26472
26473For example, @samp{match(a+b, [x, x+y, x-y, 7, x+y+z])}
26474will return @samp{[x+y, x-y, x+y+z]}.
26475
26476The @code{import} mechanism is not available for pattern sets.
26477
26478The @kbd{a m} command can also be used to extract all vector elements
26479which satisfy any condition: The pattern @samp{x :: x>0} will select
26480all the positive vector elements.
26481
26482@kindex I a m
26483@tindex matchnot
26484With the Inverse flag [@code{matchnot}], this command extracts all
26485vector elements which do @emph{not} match the given pattern.
26486
26487@c @starindex
26488@tindex matches
26489There is also a function @samp{matches(@var{x}, @var{p})} which
26490evaluates to 1 if expression @var{x} matches pattern @var{p}, or
26491to 0 otherwise. This is sometimes useful for including into the
26492conditional clauses of other rewrite rules.
26493
26494@c @starindex
26495@tindex vmatches
26496The function @code{vmatches} is just like @code{matches}, except
26497that if the match succeeds it returns a vector of assignments to
26498the meta-variables instead of the number 1. For example,
26499@samp{vmatches(f(1,2), f(a,b))} returns @samp{[a := 1, b := 2]}.
26500If the match fails, the function returns the number 0.
26501
26502@node Automatic Rewrites, Debugging Rewrites, Matching Commands, Rewrite Rules
26503@subsection Automatic Rewrites
26504
26505@noindent
26506@cindex @code{EvalRules} variable
26507@vindex EvalRules
26508It is possible to get Calc to apply a set of rewrite rules on all
26509results, effectively adding to the built-in set of default
26510simplifications. To do this, simply store your rule set in the
26511variable @code{EvalRules}. There is a convenient @kbd{s E} command
26512for editing @code{EvalRules}; @pxref{Operations on Variables}.
26513
26514For example, suppose you want @samp{sin(a + b)} to be expanded out
26515to @samp{sin(b) cos(a) + cos(b) sin(a)} wherever it appears, and
26516similarly for @samp{cos(a + b)}. The corresponding rewrite rule
26517set would be,
26518
26519@group
26520@smallexample
26521[ sin(a + b) := cos(a) sin(b) + sin(a) cos(b),
26522 cos(a + b) := cos(a) cos(b) - sin(a) sin(b) ]
26523@end smallexample
26524@end group
26525
26526To apply these manually, you could put them in a variable called
26527@code{trigexp} and then use @kbd{a r trigexp} every time you wanted
26528to expand trig functions. But if instead you store them in the
26529variable @code{EvalRules}, they will automatically be applied to all
26530sines and cosines of sums. Then, with @samp{2 x} and @samp{45} on
26531the stack, typing @kbd{+ S} will (assuming degrees mode) result in
26532@samp{0.7071 sin(2 x) + 0.7071 cos(2 x)} automatically.
26533
26534As each level of a formula is evaluated, the rules from
26535@code{EvalRules} are applied before the default simplifications.
26536Rewriting continues until no further @code{EvalRules} apply.
26537Note that this is different from the usual order of application of
26538rewrite rules: @code{EvalRules} works from the bottom up, simplifying
26539the arguments to a function before the function itself, while @kbd{a r}
26540applies rules from the top down.
26541
26542Because the @code{EvalRules} are tried first, you can use them to
26543override the normal behavior of any built-in Calc function.
26544
26545It is important not to write a rule that will get into an infinite
26546loop. For example, the rule set @samp{[f(0) := 1, f(n) := n f(n-1)]}
26547appears to be a good definition of a factorial function, but it is
26548unsafe. Imagine what happens if @samp{f(2.5)} is simplified. Calc
26549will continue to subtract 1 from this argument forever without reaching
26550zero. A safer second rule would be @samp{f(n) := n f(n-1) :: n>0}.
26551Another dangerous rule is @samp{g(x, y) := g(y, x)}. Rewriting
26552@samp{g(2, 4)}, this would bounce back and forth between that and
26553@samp{g(4, 2)} forever. If an infinite loop in @code{EvalRules}
26554occurs, Emacs will eventually stop with a ``Computation got stuck
26555or ran too long'' message.
26556
26557Another subtle difference between @code{EvalRules} and regular rewrites
26558concerns rules that rewrite a formula into an identical formula. For
26559example, @samp{f(n) := f(floor(n))} ``fails to match'' when @cite{n} is
26560already an integer. But in @code{EvalRules} this case is detected only
26561if the righthand side literally becomes the original formula before any
26562further simplification. This means that @samp{f(n) := f(floor(n))} will
26563get into an infinite loop if it occurs in @code{EvalRules}. Calc will
26564replace @samp{f(6)} with @samp{f(floor(6))}, which is different from
26565@samp{f(6)}, so it will consider the rule to have matched and will
26566continue simplifying that formula; first the argument is simplified
26567to get @samp{f(6)}, then the rule matches again to get @samp{f(floor(6))}
26568again, ad infinitum. A much safer rule would check its argument first,
26569say, with @samp{f(n) := f(floor(n)) :: !dint(n)}.
26570
26571(What really happens is that the rewrite mechanism substitutes the
26572meta-variables in the righthand side of a rule, compares to see if the
26573result is the same as the original formula and fails if so, then uses
26574the default simplifications to simplify the result and compares again
26575(and again fails if the formula has simplified back to its original
26576form). The only special wrinkle for the @code{EvalRules} is that the
26577same rules will come back into play when the default simplifications
26578are used. What Calc wants to do is build @samp{f(floor(6))}, see that
26579this is different from the original formula, simplify to @samp{f(6)},
26580see that this is the same as the original formula, and thus halt the
26581rewriting. But while simplifying, @samp{f(6)} will again trigger
26582the same @code{EvalRules} rule and Calc will get into a loop inside
26583the rewrite mechanism itself.)
26584
26585The @code{phase}, @code{schedule}, and @code{iterations} markers do
26586not work in @code{EvalRules}. If the rule set is divided into phases,
26587only the phase 1 rules are applied, and the schedule is ignored.
26588The rules are always repeated as many times as possible.
26589
26590The @code{EvalRules} are applied to all function calls in a formula,
26591but not to numbers (and other number-like objects like error forms),
26592nor to vectors or individual variable names. (Though they will apply
26593to @emph{components} of vectors and error forms when appropriate.) You
26594might try to make a variable @code{phihat} which automatically expands
26595to its definition without the need to press @kbd{=} by writing the
26596rule @samp{quote(phihat) := (1-sqrt(5))/2}, but unfortunately this rule
26597will not work as part of @code{EvalRules}.
26598
26599Finally, another limitation is that Calc sometimes calls its built-in
26600functions directly rather than going through the default simplifications.
26601When it does this, @code{EvalRules} will not be able to override those
26602functions. For example, when you take the absolute value of the complex
26603number @cite{(2, 3)}, Calc computes @samp{sqrt(2*2 + 3*3)} by calling
26604the multiplication, addition, and square root functions directly rather
26605than applying the default simplifications to this formula. So an
26606@code{EvalRules} rule that (perversely) rewrites @samp{sqrt(13) := 6}
26607would not apply. (However, if you put Calc into symbolic mode so that
26608@samp{sqrt(13)} will be left in symbolic form by the built-in square
26609root function, your rule will be able to apply. But if the complex
26610number were @cite{(3,4)}, so that @samp{sqrt(25)} must be calculated,
26611then symbolic mode will not help because @samp{sqrt(25)} can be
26612evaluated exactly to 5.)
26613
26614One subtle restriction that normally only manifests itself with
26615@code{EvalRules} is that while a given rewrite rule is in the process
26616of being checked, that same rule cannot be recursively applied. Calc
26617effectively removes the rule from its rule set while checking the rule,
26618then puts it back once the match succeeds or fails. (The technical
26619reason for this is that compiled pattern programs are not reentrant.)
26620For example, consider the rule @samp{foo(x) := x :: foo(x/2) > 0}
26621attempting to match @samp{foo(8)}. This rule will be inactive while
26622the condition @samp{foo(4) > 0} is checked, even though it might be
26623an integral part of evaluating that condition. Note that this is not
26624a problem for the more usual recursive type of rule, such as
26625@samp{foo(x) := foo(x/2)}, because there the rule has succeeded and
26626been reactivated by the time the righthand side is evaluated.
26627
26628If @code{EvalRules} has no stored value (its default state), or if
26629anything but a vector is stored in it, then it is ignored.
26630
26631Even though Calc's rewrite mechanism is designed to compare rewrite
26632rules to formulas as quickly as possible, storing rules in
26633@code{EvalRules} may make Calc run substantially slower. This is
26634particularly true of rules where the top-level call is a commonly used
26635function, or is not fixed. The rule @samp{f(n) := n f(n-1) :: n>0} will
26636only activate the rewrite mechanism for calls to the function @code{f},
26637but @samp{lg(n) + lg(m) := lg(n m)} will check every @samp{+} operator.
26638And @samp{apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) ::
26639in(f, [ln, log10])} may seem more ``efficient'' than two separate
26640rules for @code{ln} and @code{log10}, but actually it is vastly less
26641efficient because rules with @code{apply} as the top-level pattern
26642must be tested against @emph{every} function call that is simplified.
26643
26644@cindex @code{AlgSimpRules} variable
26645@vindex AlgSimpRules
26646Suppose you want @samp{sin(a + b)} to be expanded out not all the time,
26647but only when @kbd{a s} is used to simplify the formula. The variable
26648@code{AlgSimpRules} holds rules for this purpose. The @kbd{a s} command
26649will apply @code{EvalRules} and @code{AlgSimpRules} to the formula, as
26650well as all of its built-in simplifications.
26651
26652Most of the special limitations for @code{EvalRules} don't apply to
26653@code{AlgSimpRules}. Calc simply does an @kbd{a r AlgSimpRules}
26654command with an infinite repeat count as the first step of @kbd{a s}.
26655It then applies its own built-in simplifications throughout the
26656formula, and then repeats these two steps (along with applying the
26657default simplifications) until no further changes are possible.
26658
26659@cindex @code{ExtSimpRules} variable
26660@cindex @code{UnitSimpRules} variable
26661@vindex ExtSimpRules
26662@vindex UnitSimpRules
26663There are also @code{ExtSimpRules} and @code{UnitSimpRules} variables
26664that are used by @kbd{a e} and @kbd{u s}, respectively; these commands
26665also apply @code{EvalRules} and @code{AlgSimpRules}. The variable
26666@code{IntegSimpRules} contains simplification rules that are used
26667only during integration by @kbd{a i}.
26668
26669@node Debugging Rewrites, Examples of Rewrite Rules, Automatic Rewrites, Rewrite Rules
26670@subsection Debugging Rewrites
26671
26672@noindent
26673If a buffer named @samp{*Trace*} exists, the rewrite mechanism will
26674record some useful information there as it operates. The original
26675formula is written there, as is the result of each successful rewrite,
26676and the final result of the rewriting. All phase changes are also
26677noted.
26678
26679Calc always appends to @samp{*Trace*}. You must empty this buffer
26680yourself periodically if it is in danger of growing unwieldy.
26681
26682Note that the rewriting mechanism is substantially slower when the
26683@samp{*Trace*} buffer exists, even if the buffer is not visible on
26684the screen. Once you are done, you will probably want to kill this
26685buffer (with @kbd{C-x k *Trace* @key{RET}}). If you leave it in
26686existence and forget about it, all your future rewrite commands will
26687be needlessly slow.
26688
26689@node Examples of Rewrite Rules, , Debugging Rewrites, Rewrite Rules
26690@subsection Examples of Rewrite Rules
26691
26692@noindent
26693Returning to the example of substituting the pattern
26694@samp{sin(x)^2 + cos(x)^2} with 1, we saw that the rule
26695@samp{opt(a) sin(x)^2 + opt(a) cos(x)^2 := a} does a good job of
26696finding suitable cases. Another solution would be to use the rule
26697@samp{cos(x)^2 := 1 - sin(x)^2}, followed by algebraic simplification
26698if necessary. This rule will be the most effective way to do the job,
26699but at the expense of making some changes that you might not desire.@refill
26700
26701Another algebraic rewrite rule is @samp{exp(x+y) := exp(x) exp(y)}.
26702To make this work with the @w{@kbd{j r}} command so that it can be
26703easily targeted to a particular exponential in a large formula,
26704you might wish to write the rule as @samp{select(exp(x+y)) :=
26705select(exp(x) exp(y))}. The @samp{select} markers will be
26706ignored by the regular @kbd{a r} command
26707(@pxref{Selections with Rewrite Rules}).@refill
26708
26709A surprisingly useful rewrite rule is @samp{a/(b-c) := a*(b+c)/(b^2-c^2)}.
26710This will simplify the formula whenever @cite{b} and/or @cite{c} can
26711be made simpler by squaring. For example, applying this rule to
26712@samp{2 / (sqrt(2) + 3)} yields @samp{6:7 - 2:7 sqrt(2)} (assuming
26713Symbolic Mode has been enabled to keep the square root from being
26714evaulated to a floating-point approximation). This rule is also
26715useful when working with symbolic complex numbers, e.g.,
26716@samp{(a + b i) / (c + d i)}.
26717
26718As another example, we could define our own ``triangular numbers'' function
26719with the rules @samp{[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]}. Enter
26720this vector and store it in a variable: @kbd{@w{s t} trirules}. Now, given
26721a suitable formula like @samp{tri(5)} on the stack, type @samp{a r trirules}
26722to apply these rules repeatedly. After six applications, @kbd{a r} will
26723stop with 15 on the stack. Once these rules are debugged, it would probably
26724be most useful to add them to @code{EvalRules} so that Calc will evaluate
26725the new @code{tri} function automatically. We could then use @kbd{Z K} on
26726the keyboard macro @kbd{' tri($) RET} to make a command that applies
26727@code{tri} to the value on the top of the stack. @xref{Programming}.
26728
26729@cindex Quaternions
26730The following rule set, contributed by @c{Fran\c cois}
26731@asis{Francois} Pinard, implements
26732@dfn{quaternions}, a generalization of the concept of complex numbers.
26733Quaternions have four components, and are here represented by function
26734calls @samp{quat(@var{w}, [@var{x}, @var{y}, @var{z}])} with ``real
26735part'' @var{w} and the three ``imaginary'' parts collected into a
26736vector. Various arithmetical operations on quaternions are supported.
26737To use these rules, either add them to @code{EvalRules}, or create a
26738command based on @kbd{a r} for simplifying quaternion formulas.
26739A convenient way to enter quaternions would be a command defined by
26740a keyboard macro containing: @kbd{' quat($$$$, [$$$, $$, $]) @key{RET}}.
26741
26742@smallexample
26743[ quat(w, x, y, z) := quat(w, [x, y, z]),
26744 quat(w, [0, 0, 0]) := w,
26745 abs(quat(w, v)) := hypot(w, v),
26746 -quat(w, v) := quat(-w, -v),
26747 r + quat(w, v) := quat(r + w, v) :: real(r),
26748 r - quat(w, v) := quat(r - w, -v) :: real(r),
26749 quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
26750 r * quat(w, v) := quat(r * w, r * v) :: real(r),
26751 plain(quat(w1, v1) * quat(w2, v2))
26752 := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
26753 quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
26754 z / quat(w, v) := z * quatinv(quat(w, v)),
26755 quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
26756 quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
26757 quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
26758 :: integer(k) :: k > 0 :: k % 2 = 0,
26759 quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
26760 :: integer(k) :: k > 2,
26761 quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
26762@end smallexample
26763
26764Quaternions, like matrices, have non-commutative multiplication.
26765In other words, @cite{q1 * q2 = q2 * q1} is not necessarily true if
26766@cite{q1} and @cite{q2} are @code{quat} forms. The @samp{quat*quat}
26767rule above uses @code{plain} to prevent Calc from rearranging the
26768product. It may also be wise to add the line @samp{[quat(), matrix]}
26769to the @code{Decls} matrix, to ensure that Calc's other algebraic
26770operations will not rearrange a quaternion product. @xref{Declarations}.
26771
26772These rules also accept a four-argument @code{quat} form, converting
26773it to the preferred form in the first rule. If you would rather see
26774results in the four-argument form, just append the two items
26775@samp{phase(2), quat(w, [x, y, z]) := quat(w, x, y, z)} to the end
26776of the rule set. (But remember that multi-phase rule sets don't work
26777in @code{EvalRules}.)
26778
26779@node Units, Store and Recall, Algebra, Top
26780@chapter Operating on Units
26781
26782@noindent
26783One special interpretation of algebraic formulas is as numbers with units.
26784For example, the formula @samp{5 m / s^2} can be read ``five meters
26785per second squared.'' The commands in this chapter help you
26786manipulate units expressions in this form. Units-related commands
26787begin with the @kbd{u} prefix key.
26788
26789@menu
26790* Basic Operations on Units::
26791* The Units Table::
26792* Predefined Units::
26793* User-Defined Units::
26794@end menu
26795
26796@node Basic Operations on Units, The Units Table, Units, Units
26797@section Basic Operations on Units
26798
26799@noindent
26800A @dfn{units expression} is a formula which is basically a number
26801multiplied and/or divided by one or more @dfn{unit names}, which may
26802optionally be raised to integer powers. Actually, the value part need not
26803be a number; any product or quotient involving unit names is a units
26804expression. Many of the units commands will also accept any formula,
26805where the command applies to all units expressions which appear in the
26806formula.
26807
26808A unit name is a variable whose name appears in the @dfn{unit table},
26809or a variable whose name is a prefix character like @samp{k} (for ``kilo'')
26810or @samp{u} (for ``micro'') followed by a name in the unit table.
26811A substantial table of built-in units is provided with Calc;
26812@pxref{Predefined Units}. You can also define your own unit names;
26813@pxref{User-Defined Units}.@refill
26814
26815Note that if the value part of a units expression is exactly @samp{1},
26816it will be removed by the Calculator's automatic algebra routines: The
26817formula @samp{1 mm} is ``simplified'' to @samp{mm}. This is only a
26818display anomaly, however; @samp{mm} will work just fine as a
26819representation of one millimeter.@refill
26820
26821You may find that Algebraic Mode (@pxref{Algebraic Entry}) makes working
26822with units expressions easier. Otherwise, you will have to remember
26823to hit the apostrophe key every time you wish to enter units.
26824
26825@kindex u s
26826@pindex calc-simplify-units
26827@c @mindex usimpl@idots
26828@tindex usimplify
26829The @kbd{u s} (@code{calc-simplify-units}) [@code{usimplify}] command
26830simplifies a units
26831expression. It uses @kbd{a s} (@code{calc-simplify}) to simplify the
26832expression first as a regular algebraic formula; it then looks for
26833features that can be further simplified by converting one object's units
26834to be compatible with another's. For example, @samp{5 m + 23 mm} will
26835simplify to @samp{5.023 m}. When different but compatible units are
26836added, the righthand term's units are converted to match those of the
26837lefthand term. @xref{Simplification Modes}, for a way to have this done
26838automatically at all times.@refill
26839
26840Units simplification also handles quotients of two units with the same
26841dimensionality, as in @w{@samp{2 in s/L cm}} to @samp{5.08 s/L}; fractional
26842powers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and
26843@samp{sqrt(9 acre)} to a quantity in meters; and @code{floor},
26844@code{ceil}, @code{round}, @code{rounde}, @code{roundu}, @code{trunc},
26845@code{float}, @code{frac}, @code{abs}, and @code{clean}
26846applied to units expressions, in which case
26847the operation in question is applied only to the numeric part of the
26848expression. Finally, trigonometric functions of quantities with units
26849of angle are evaluated, regardless of the current angular mode.@refill
26850
26851@kindex u c
26852@pindex calc-convert-units
26853The @kbd{u c} (@code{calc-convert-units}) command converts a units
26854expression to new, compatible units. For example, given the units
26855expression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces
26856@samp{24.5872 m/s}. If the units you request are inconsistent with
26857the original units, the number will be converted into your units
26858times whatever ``remainder'' units are left over. For example,
26859converting @samp{55 mph} into acres produces @samp{6.08e-3 acre / m s}.
26860(Recall that multiplication binds more strongly than division in Calc
26861formulas, so the units here are acres per meter-second.) Remainder
26862units are expressed in terms of ``fundamental'' units like @samp{m} and
26863@samp{s}, regardless of the input units.
26864
26865One special exception is that if you specify a single unit name, and
26866a compatible unit appears somewhere in the units expression, then
26867that compatible unit will be converted to the new unit and the
26868remaining units in the expression will be left alone. For example,
26869given the input @samp{980 cm/s^2}, the command @kbd{u c ms} will
26870change the @samp{s} to @samp{ms} to get @samp{9.8e-4 cm/ms^2}.
26871The ``remainder unit'' @samp{cm} is left alone rather than being
26872changed to the base unit @samp{m}.
26873
26874You can use explicit unit conversion instead of the @kbd{u s} command
26875to gain more control over the units of the result of an expression.
26876For example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or
26877@kbd{u c mm} to express the result in either meters or millimeters.
26878(For that matter, you could type @kbd{u c fath} to express the result
26879in fathoms, if you preferred!)
26880
26881In place of a specific set of units, you can also enter one of the
26882units system names @code{si}, @code{mks} (equivalent), or @code{cgs}.
26883For example, @kbd{u c si @key{RET}} converts the expression into
26884International System of Units (SI) base units. Also, @kbd{u c base}
26885converts to Calc's base units, which are the same as @code{si} units
26886except that @code{base} uses @samp{g} as the fundamental unit of mass
26887whereas @code{si} uses @samp{kg}.
26888
26889@cindex Composite units
26890The @kbd{u c} command also accepts @dfn{composite units}, which
26891are expressed as the sum of several compatible unit names. For
26892example, converting @samp{30.5 in} to units @samp{mi+ft+in} (miles,
26893feet, and inches) produces @samp{2 ft + 6.5 in}. Calc first
26894sorts the unit names into order of decreasing relative size.
26895It then accounts for as much of the input quantity as it can
26896using an integer number times the largest unit, then moves on
26897to the next smaller unit, and so on. Only the smallest unit
26898may have a non-integer amount attached in the result. A few
26899standard unit names exist for common combinations, such as
26900@code{mfi} for @samp{mi+ft+in}, and @code{tpo} for @samp{ton+lb+oz}.
26901Composite units are expanded as if by @kbd{a x}, so that
26902@samp{(ft+in)/hr} is first converted to @samp{ft/hr+in/hr}.
26903
26904If the value on the stack does not contain any units, @kbd{u c} will
26905prompt first for the old units which this value should be considered
26906to have, then for the new units. Assuming the old and new units you
26907give are consistent with each other, the result also will not contain
26908any units. For example, @kbd{@w{u c} cm RET in RET} converts the number
269092 on the stack to 5.08.
26910
26911@kindex u b
26912@pindex calc-base-units
26913The @kbd{u b} (@code{calc-base-units}) command is shorthand for
26914@kbd{u c base}; it converts the units expression on the top of the
26915stack into @code{base} units. If @kbd{u s} does not simplify a
26916units expression as far as you would like, try @kbd{u b}.
26917
26918The @kbd{u c} and @kbd{u b} commands treat temperature units (like
26919@samp{degC} and @samp{K}) as relative temperatures. For example,
26920@kbd{u c} converts @samp{10 degC} to @samp{18 degF}: A change of 10
26921degrees Celsius corresponds to a change of 18 degrees Fahrenheit.
26922
26923@kindex u t
26924@pindex calc-convert-temperature
26925@cindex Temperature conversion
26926The @kbd{u t} (@code{calc-convert-temperature}) command converts
26927absolute temperatures. The value on the stack must be a simple units
26928expression with units of temperature only. This command would convert
26929@samp{10 degC} to @samp{50 degF}, the equivalent temperature on the
26930Fahrenheit scale.@refill
26931
26932@kindex u r
26933@pindex calc-remove-units
26934@kindex u x
26935@pindex calc-extract-units
26936The @kbd{u r} (@code{calc-remove-units}) command removes units from the
26937formula at the top of the stack. The @kbd{u x}
26938(@code{calc-extract-units}) command extracts only the units portion of a
26939formula. These commands essentially replace every term of the formula
26940that does or doesn't (respectively) look like a unit name by the
26941constant 1, then resimplify the formula.@refill
26942
26943@kindex u a
26944@pindex calc-autorange-units
26945The @kbd{u a} (@code{calc-autorange-units}) command turns on and off a
26946mode in which unit prefixes like @code{k} (``kilo'') are automatically
26947applied to keep the numeric part of a units expression in a reasonable
26948range. This mode affects @kbd{u s} and all units conversion commands
26949except @kbd{u b}. For example, with autoranging on, @samp{12345 Hz}
26950will be simplified to @samp{12.345 kHz}. Autoranging is useful for
26951some kinds of units (like @code{Hz} and @code{m}), but is probably
26952undesirable for non-metric units like @code{ft} and @code{tbsp}.
26953(Composite units are more appropriate for those; see above.)
26954
26955Autoranging always applies the prefix to the leftmost unit name.
26956Calc chooses the largest prefix that causes the number to be greater
26957than or equal to 1.0. Thus an increasing sequence of adjusted times
26958would be @samp{1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks}.
26959Generally the rule of thumb is that the number will be adjusted
26960to be in the interval @samp{[1 .. 1000)}, although there are several
26961exceptions to this rule. First, if the unit has a power then this
26962is not possible; @samp{0.1 s^2} simplifies to @samp{100000 ms^2}.
26963Second, the ``centi-'' prefix is allowed to form @code{cm} (centimeters),
26964but will not apply to other units. The ``deci-,'' ``deka-,'' and
26965``hecto-'' prefixes are never used. Thus the allowable interval is
26966@samp{[1 .. 10)} for millimeters and @samp{[1 .. 100)} for centimeters.
26967Finally, a prefix will not be added to a unit if the resulting name
26968is also the actual name of another unit; @samp{1e-15 t} would normally
26969be considered a ``femto-ton,'' but it is written as @samp{1000 at}
26970(1000 atto-tons) instead because @code{ft} would be confused with feet.
26971
26972@node The Units Table, Predefined Units, Basic Operations on Units, Units
26973@section The Units Table
26974
26975@noindent
26976@kindex u v
26977@pindex calc-enter-units-table
26978The @kbd{u v} (@code{calc-enter-units-table}) command displays the units table
26979in another buffer called @code{*Units Table*}. Each entry in this table
26980gives the unit name as it would appear in an expression, the definition
26981of the unit in terms of simpler units, and a full name or description of
26982the unit. Fundamental units are defined as themselves; these are the
26983units produced by the @kbd{u b} command. The fundamental units are
26984meters, seconds, grams, kelvins, amperes, candelas, moles, radians,
26985and steradians.
26986
26987The Units Table buffer also displays the Unit Prefix Table. Note that
26988two prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case
26989prefix letters. @samp{Meg} is also accepted as a synonym for the @samp{M}
26990prefix. Whenever a unit name can be interpreted as either a built-in name
26991or a prefix followed by another built-in name, the former interpretation
26992wins. For example, @samp{2 pt} means two pints, not two pico-tons.
26993
26994The Units Table buffer, once created, is not rebuilt unless you define
26995new units. To force the buffer to be rebuilt, give any numeric prefix
26996argument to @kbd{u v}.
26997
26998@kindex u V
26999@pindex calc-view-units-table
27000The @kbd{u V} (@code{calc-view-units-table}) command is like @kbd{u v} except
27001that the cursor is not moved into the Units Table buffer. You can
27002type @kbd{u V} again to remove the Units Table from the display. To
27003return from the Units Table buffer after a @kbd{u v}, type @kbd{M-# c}
27004again or use the regular Emacs @w{@kbd{C-x o}} (@code{other-window})
27005command. You can also kill the buffer with @kbd{C-x k} if you wish;
27006the actual units table is safely stored inside the Calculator.
27007
27008@kindex u g
27009@pindex calc-get-unit-definition
27010The @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's
27011defining expression and pushes it onto the Calculator stack. For example,
27012@kbd{u g in} will produce the expression @samp{2.54 cm}. This is the
27013same definition for the unit that would appear in the Units Table buffer.
27014Note that this command works only for actual unit names; @kbd{u g km}
27015will report that no such unit exists, for example, because @code{km} is
27016really the unit @code{m} with a @code{k} (``kilo'') prefix. To see a
27017definition of a unit in terms of base units, it is easier to push the
27018unit name on the stack and then reduce it to base units with @kbd{u b}.
27019
27020@kindex u e
27021@pindex calc-explain-units
27022The @kbd{u e} (@code{calc-explain-units}) command displays an English
27023description of the units of the expression on the stack. For example,
27024for the expression @samp{62 km^2 g / s^2 mol K}, the description is
27025``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).'' This
27026command uses the English descriptions that appear in the righthand
27027column of the Units Table.
27028
27029@node Predefined Units, User-Defined Units, The Units Table, Units
27030@section Predefined Units
27031
27032@noindent
27033Since the exact definitions of many kinds of units have evolved over the
27034years, and since certain countries sometimes have local differences in
27035their definitions, it is a good idea to examine Calc's definition of a
27036unit before depending on its exact value. For example, there are three
27037different units for gallons, corresponding to the US (@code{gal}),
27038Canadian (@code{galC}), and British (@code{galUK}) definitions. Also,
27039note that @code{oz} is a standard ounce of mass, @code{ozt} is a Troy
27040ounce, and @code{ozfl} is a fluid ounce.
27041
27042The temperature units corresponding to degrees Kelvin and Centigrade
27043(Celsius) are the same in this table, since most units commands treat
27044temperatures as being relative. The @code{calc-convert-temperature}
27045command has special rules for handling the different absolute magnitudes
27046of the various temperature scales.
27047
27048The unit of volume ``liters'' can be referred to by either the lower-case
27049@code{l} or the upper-case @code{L}.
27050
27051The unit @code{A} stands for Amperes; the name @code{Ang} is used
27052@tex
27053for \AA ngstroms.
27054@end tex
27055@ifinfo
27056for Angstroms.
27057@end ifinfo
27058
27059The unit @code{pt} stands for pints; the name @code{point} stands for
27060a typographical point, defined by @samp{72 point = 1 in}. There is
27061also @code{tpt}, which stands for a printer's point as defined by the
27062@TeX{} typesetting system: @samp{72.27 tpt = 1 in}.
27063
27064The unit @code{e} stands for the elementary (electron) unit of charge;
27065because algebra command could mistake this for the special constant
27066@cite{e}, Calc provides the alternate unit name @code{ech} which is
27067preferable to @code{e}.
27068
27069The name @code{g} stands for one gram of mass; there is also @code{gf},
27070one gram of force. (Likewise for @kbd{lb}, pounds, and @kbd{lbf}.)
27071Meanwhile, one ``@cite{g}'' of acceleration is denoted @code{ga}.
27072
27073The unit @code{ton} is a U.S. ton of @samp{2000 lb}, and @code{t} is
27074a metric ton of @samp{1000 kg}.
27075
27076The names @code{s} (or @code{sec}) and @code{min} refer to units of
27077time; @code{arcsec} and @code{arcmin} are units of angle.
27078
27079Some ``units'' are really physical constants; for example, @code{c}
27080represents the speed of light, and @code{h} represents Planck's
27081constant. You can use these just like other units: converting
27082@samp{.5 c} to @samp{m/s} expresses one-half the speed of light in
27083meters per second. You can also use this merely as a handy reference;
27084the @kbd{u g} command gets the definition of one of these constants
27085in its normal terms, and @kbd{u b} expresses the definition in base
27086units.
27087
27088Two units, @code{pi} and @code{fsc} (the fine structure constant,
27089approximately @i{1/137}) are dimensionless. The units simplification
27090commands simply treat these names as equivalent to their corresponding
27091values. However you can, for example, use @kbd{u c} to convert a pure
27092number into multiples of the fine structure constant, or @kbd{u b} to
27093convert this back into a pure number. (When @kbd{u c} prompts for the
27094``old units,'' just enter a blank line to signify that the value
27095really is unitless.)
27096
27097@c Describe angular units, luminosity vs. steradians problem.
27098
27099@node User-Defined Units, , Predefined Units, Units
27100@section User-Defined Units
27101
27102@noindent
27103Calc provides ways to get quick access to your selected ``favorite''
27104units, as well as ways to define your own new units.
27105
27106@kindex u 0-9
27107@pindex calc-quick-units
27108@vindex Units
27109@cindex @code{Units} variable
27110@cindex Quick units
27111To select your favorite units, store a vector of unit names or
27112expressions in the Calc variable @code{Units}. The @kbd{u 1}
27113through @kbd{u 9} commands (@code{calc-quick-units}) provide access
27114to these units. If the value on the top of the stack is a plain
27115number (with no units attached), then @kbd{u 1} gives it the
27116specified units. (Basically, it multiplies the number by the
27117first item in the @code{Units} vector.) If the number on the
27118stack @emph{does} have units, then @kbd{u 1} converts that number
27119to the new units. For example, suppose the vector @samp{[in, ft]}
27120is stored in @code{Units}. Then @kbd{30 u 1} will create the
27121expression @samp{30 in}, and @kbd{u 2} will convert that expression
27122to @samp{2.5 ft}.
27123
27124The @kbd{u 0} command accesses the tenth element of @code{Units}.
27125Only ten quick units may be defined at a time. If the @code{Units}
27126variable has no stored value (the default), or if its value is not
27127a vector, then the quick-units commands will not function. The
27128@kbd{s U} command is a convenient way to edit the @code{Units}
27129variable; @pxref{Operations on Variables}.
27130
27131@kindex u d
27132@pindex calc-define-unit
27133@cindex User-defined units
27134The @kbd{u d} (@code{calc-define-unit}) command records the units
27135expression on the top of the stack as the definition for a new,
27136user-defined unit. For example, putting @samp{16.5 ft} on the stack and
27137typing @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to
2713816.5 feet. The unit conversion and simplification commands will now
27139treat @code{rod} just like any other unit of length. You will also be
27140prompted for an optional English description of the unit, which will
27141appear in the Units Table.
27142
27143@kindex u u
27144@pindex calc-undefine-unit
27145The @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined
27146unit. It is not possible to remove one of the predefined units,
27147however.
27148
27149If you define a unit with an existing unit name, your new definition
27150will replace the original definition of that unit. If the unit was a
27151predefined unit, the old definition will not be replaced, only
27152``shadowed.'' The built-in definition will reappear if you later use
27153@kbd{u u} to remove the shadowing definition.
27154
27155To create a new fundamental unit, use either 1 or the unit name itself
27156as the defining expression. Otherwise the expression can involve any
27157other units that you like (except for composite units like @samp{mfi}).
27158You can create a new composite unit with a sum of other units as the
27159defining expression. The next unit operation like @kbd{u c} or @kbd{u v}
27160will rebuild the internal unit table incorporating your modifications.
27161Note that erroneous definitions (such as two units defined in terms of
27162each other) will not be detected until the unit table is next rebuilt;
27163@kbd{u v} is a convenient way to force this to happen.
27164
27165Temperature units are treated specially inside the Calculator; it is not
27166possible to create user-defined temperature units.
27167
27168@kindex u p
27169@pindex calc-permanent-units
27170@cindex @file{.emacs} file, user-defined units
27171The @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined
27172units in your @file{.emacs} file, so that the units will still be
27173available in subsequent Emacs sessions. If there was already a set of
27174user-defined units in your @file{.emacs} file, it is replaced by the
27175new set. (@xref{General Mode Commands}, for a way to tell Calc to use
27176a different file instead of @file{.emacs}.)
27177
27178@node Store and Recall, Graphics, Units, Top
27179@chapter Storing and Recalling
27180
27181@noindent
27182Calculator variables are really just Lisp variables that contain numbers
27183or formulas in a form that Calc can understand. The commands in this
27184section allow you to manipulate variables conveniently. Commands related
27185to variables use the @kbd{s} prefix key.
27186
27187@menu
27188* Storing Variables::
27189* Recalling Variables::
27190* Operations on Variables::
27191* Let Command::
27192* Evaluates-To Operator::
27193@end menu
27194
27195@node Storing Variables, Recalling Variables, Store and Recall, Store and Recall
27196@section Storing Variables
27197
27198@noindent
27199@kindex s s
27200@pindex calc-store
27201@cindex Storing variables
27202@cindex Quick variables
27203@vindex q0
27204@vindex q9
27205The @kbd{s s} (@code{calc-store}) command stores the value at the top of
27206the stack into a specified variable. It prompts you to enter the
27207name of the variable. If you press a single digit, the value is stored
27208immediately in one of the ``quick'' variables @code{var-q0} through
27209@code{var-q9}. Or you can enter any variable name. The prefix @samp{var-}
27210is supplied for you; when a name appears in a formula (as in @samp{a+q2})
27211the prefix @samp{var-} is also supplied there, so normally you can simply
27212forget about @samp{var-} everywhere. Its only purpose is to enable you to
27213use Calc variables without fear of accidentally clobbering some variable in
27214another Emacs package. If you really want to store in an arbitrary Lisp
27215variable, just backspace over the @samp{var-}.
27216
27217@kindex s t
27218@pindex calc-store-into
27219The @kbd{s s} command leaves the stored value on the stack. There is
27220also an @kbd{s t} (@code{calc-store-into}) command, which removes a
27221value from the stack and stores it in a variable.
27222
27223If the top of stack value is an equation @samp{a = 7} or assignment
27224@samp{a := 7} with a variable on the lefthand side, then Calc will
27225assign that variable with that value by default, i.e., if you type
27226@kbd{s s @key{RET}} or @kbd{s t @key{RET}}. In this example, the
27227value 7 would be stored in the variable @samp{a}. (If you do type
27228a variable name at the prompt, the top-of-stack value is stored in
27229its entirety, even if it is an equation: @samp{s s b @key{RET}}
27230with @samp{a := 7} on the stack stores @samp{a := 7} in @code{b}.)
27231
27232In fact, the top of stack value can be a vector of equations or
27233assignments with different variables on their lefthand sides; the
27234default will be to store all the variables with their corresponding
27235righthand sides simultaneously.
27236
27237It is also possible to type an equation or assignment directly at
27238the prompt for the @kbd{s s} or @kbd{s t} command: @kbd{s s foo = 7}.
27239In this case the expression to the right of the @kbd{=} or @kbd{:=}
27240symbol is evaluated as if by the @kbd{=} command, and that value is
27241stored in the variable. No value is taken from the stack; @kbd{s s}
27242and @kbd{s t} are equivalent when used in this way.
27243
27244@kindex s 0-9
27245@kindex t 0-9
27246The prefix keys @kbd{s} and @kbd{t} may be followed immediately by a
27247digit; @kbd{s 9} is equivalent to @kbd{s s 9}, and @kbd{t 9} is
27248equivalent to @kbd{s t 9}. (The @kbd{t} prefix is otherwise used
27249for trail and time/date commands.)
27250
27251@kindex s +
27252@kindex s -
27253@c @mindex @idots
27254@kindex s *
27255@c @mindex @null
27256@kindex s /
27257@c @mindex @null
27258@kindex s ^
27259@c @mindex @null
27260@kindex s |
27261@c @mindex @null
27262@kindex s n
27263@c @mindex @null
27264@kindex s &
27265@c @mindex @null
27266@kindex s [
27267@c @mindex @null
27268@kindex s ]
27269@pindex calc-store-plus
27270@pindex calc-store-minus
27271@pindex calc-store-times
27272@pindex calc-store-div
27273@pindex calc-store-power
27274@pindex calc-store-concat
27275@pindex calc-store-neg
27276@pindex calc-store-inv
27277@pindex calc-store-decr
27278@pindex calc-store-incr
27279There are also several ``arithmetic store'' commands. For example,
27280@kbd{s +} removes a value from the stack and adds it to the specified
27281variable. The other arithmetic stores are @kbd{s -}, @kbd{s *}, @kbd{s /},
27282@kbd{s ^}, and @w{@kbd{s |}} (vector concatenation), plus @kbd{s n} and
27283@kbd{s &} which negate or invert the value in a variable, and @w{@kbd{s [}}
27284and @kbd{s ]} which decrease or increase a variable by one.
27285
27286All the arithmetic stores accept the Inverse prefix to reverse the
27287order of the operands. If @cite{v} represents the contents of the
27288variable, and @cite{a} is the value drawn from the stack, then regular
27289@w{@kbd{s -}} assigns @c{$v \coloneq v - a$}
27290@cite{v := v - a}, but @kbd{I s -} assigns
27291@c{$v \coloneq a - v$}
27292@cite{v := a - v}. While @kbd{I s *} might seem pointless, it is
27293useful if matrix multiplication is involved. Actually, all the
27294arithmetic stores use formulas designed to behave usefully both
27295forwards and backwards:
27296
27297@group
27298@example
27299s + v := v + a v := a + v
27300s - v := v - a v := a - v
27301s * v := v * a v := a * v
27302s / v := v / a v := a / v
27303s ^ v := v ^ a v := a ^ v
27304s | v := v | a v := a | v
27305s n v := v / (-1) v := (-1) / v
27306s & v := v ^ (-1) v := (-1) ^ v
27307s [ v := v - 1 v := 1 - v
27308s ] v := v - (-1) v := (-1) - v
27309@end example
27310@end group
27311
27312In the last four cases, a numeric prefix argument will be used in
27313place of the number one. (For example, @kbd{M-2 s ]} increases
27314a variable by 2, and @kbd{M-2 I s ]} replaces a variable by
27315minus-two minus the variable.
27316
27317The first six arithmetic stores can also be typed @kbd{s t +}, @kbd{s t -},
27318etc. The commands @kbd{s s +}, @kbd{s s -}, and so on are analogous
27319arithmetic stores that don't remove the value @cite{a} from the stack.
27320
27321All arithmetic stores report the new value of the variable in the
27322Trail for your information. They signal an error if the variable
27323previously had no stored value. If default simplifications have been
27324turned off, the arithmetic stores temporarily turn them on for numeric
27325arguments only (i.e., they temporarily do an @kbd{m N} command).
27326@xref{Simplification Modes}. Large vectors put in the trail by
27327these commands always use abbreviated (@kbd{t .}) mode.
27328
27329@kindex s m
27330@pindex calc-store-map
27331The @kbd{s m} command is a general way to adjust a variable's value
27332using any Calc function. It is a ``mapping'' command analogous to
27333@kbd{V M}, @kbd{V R}, etc. @xref{Reducing and Mapping}, to see
27334how to specify a function for a mapping command. Basically,
27335all you do is type the Calc command key that would invoke that
27336function normally. For example, @kbd{s m n} applies the @kbd{n}
27337key to negate the contents of the variable, so @kbd{s m n} is
27338equivalent to @kbd{s n}. Also, @kbd{s m Q} takes the square root
27339of the value stored in a variable, @kbd{s m v v} uses @kbd{v v} to
27340reverse the vector stored in the variable, and @kbd{s m H I S}
27341takes the hyperbolic arcsine of the variable contents.
27342
27343If the mapping function takes two or more arguments, the additional
27344arguments are taken from the stack; the old value of the variable
27345is provided as the first argument. Thus @kbd{s m -} with @cite{a}
27346on the stack computes @cite{v - a}, just like @kbd{s -}. With the
27347Inverse prefix, the variable's original value becomes the @emph{last}
27348argument instead of the first. Thus @kbd{I s m -} is also
27349equivalent to @kbd{I s -}.
27350
27351@kindex s x
27352@pindex calc-store-exchange
27353The @kbd{s x} (@code{calc-store-exchange}) command exchanges the value
27354of a variable with the value on the top of the stack. Naturally, the
27355variable must already have a stored value for this to work.
27356
27357You can type an equation or assignment at the @kbd{s x} prompt. The
27358command @kbd{s x a=6} takes no values from the stack; instead, it
27359pushes the old value of @samp{a} on the stack and stores @samp{a = 6}.
27360
27361@kindex s u
27362@pindex calc-unstore
27363@cindex Void variables
27364@cindex Un-storing variables
27365Until you store something in them, variables are ``void,'' that is, they
27366contain no value at all. If they appear in an algebraic formula they
27367will be left alone even if you press @kbd{=} (@code{calc-evaluate}).
27368The @kbd{s u} (@code{calc-unstore}) command returns a variable to the
27369void state.@refill
27370
27371The only variables with predefined values are the ``special constants''
27372@code{pi}, @code{e}, @code{i}, @code{phi}, and @code{gamma}. You are free
27373to unstore these variables or to store new values into them if you like,
27374although some of the algebraic-manipulation functions may assume these
27375variables represent their standard values. Calc displays a warning if
27376you change the value of one of these variables, or of one of the other
27377special variables @code{inf}, @code{uinf}, and @code{nan} (which are
27378normally void).
27379
27380Note that @code{var-pi} doesn't actually have 3.14159265359 stored
27381in it, but rather a special magic value that evaluates to @c{$\pi$}
27382@cite{pi}
27383at the current precision. Likewise @code{var-e}, @code{var-i}, and
27384@code{var-phi} evaluate according to the current precision or polar mode.
27385If you recall a value from @code{pi} and store it back, this magic
27386property will be lost.
27387
27388@kindex s c
27389@pindex calc-copy-variable
27390The @kbd{s c} (@code{calc-copy-variable}) command copies the stored
27391value of one variable to another. It differs from a simple @kbd{s r}
27392followed by an @kbd{s t} in two important ways. First, the value never
27393goes on the stack and thus is never rounded, evaluated, or simplified
27394in any way; it is not even rounded down to the current precision.
27395Second, the ``magic'' contents of a variable like @code{var-e} can
27396be copied into another variable with this command, perhaps because
27397you need to unstore @code{var-e} right now but you wish to put it
27398back when you're done. The @kbd{s c} command is the only way to
27399manipulate these magic values intact.
27400
27401@node Recalling Variables, Operations on Variables, Storing Variables, Store and Recall
27402@section Recalling Variables
27403
27404@noindent
27405@kindex s r
27406@pindex calc-recall
27407@cindex Recalling variables
27408The most straightforward way to extract the stored value from a variable
27409is to use the @kbd{s r} (@code{calc-recall}) command. This command prompts
27410for a variable name (similarly to @code{calc-store}), looks up the value
27411of the specified variable, and pushes that value onto the stack. It is
27412an error to try to recall a void variable.
27413
27414It is also possible to recall the value from a variable by evaluating a
27415formula containing that variable. For example, @kbd{' a @key{RET} =} is
27416the same as @kbd{s r a @key{RET}} except that if the variable is void, the
27417former will simply leave the formula @samp{a} on the stack whereas the
27418latter will produce an error message.
27419
27420@kindex r 0-9
27421The @kbd{r} prefix may be followed by a digit, so that @kbd{r 9} is
27422equivalent to @kbd{s r 9}. (The @kbd{r} prefix is otherwise unused
27423in the current version of Calc.)
27424
27425@node Operations on Variables, Let Command, Recalling Variables, Store and Recall
27426@section Other Operations on Variables
27427
27428@noindent
27429@kindex s e
27430@pindex calc-edit-variable
27431The @kbd{s e} (@code{calc-edit-variable}) command edits the stored
27432value of a variable without ever putting that value on the stack
27433or simplifying or evaluating the value. It prompts for the name of
27434the variable to edit. If the variable has no stored value, the
27435editing buffer will start out empty. If the editing buffer is
27436empty when you press @key{M-# M-#} to finish, the variable will
27437be made void. @xref{Editing Stack Entries}, for a general
27438description of editing.
27439
27440The @kbd{s e} command is especially useful for creating and editing
27441rewrite rules which are stored in variables. Sometimes these rules
27442contain formulas which must not be evaluated until the rules are
27443actually used. (For example, they may refer to @samp{deriv(x,y)},
27444where @code{x} will someday become some expression involving @code{y};
27445if you let Calc evaluate the rule while you are defining it, Calc will
27446replace @samp{deriv(x,y)} with 0 because the formula @code{x} does
27447not itself refer to @code{y}.) By contrast, recalling the variable,
27448editing with @kbd{`}, and storing will evaluate the variable's value
27449as a side effect of putting the value on the stack.
27450
27451@kindex s A
27452@kindex s D
27453@c @mindex @idots
27454@kindex s E
27455@c @mindex @null
27456@kindex s F
27457@c @mindex @null
27458@kindex s G
27459@c @mindex @null
27460@kindex s H
27461@c @mindex @null
27462@kindex s I
27463@c @mindex @null
27464@kindex s L
27465@c @mindex @null
27466@kindex s P
27467@c @mindex @null
27468@kindex s R
27469@c @mindex @null
27470@kindex s T
27471@c @mindex @null
27472@kindex s U
27473@c @mindex @null
27474@kindex s X
27475@pindex calc-store-AlgSimpRules
27476@pindex calc-store-Decls
27477@pindex calc-store-EvalRules
27478@pindex calc-store-FitRules
27479@pindex calc-store-GenCount
27480@pindex calc-store-Holidays
27481@pindex calc-store-IntegLimit
27482@pindex calc-store-LineStyles
27483@pindex calc-store-PointStyles
27484@pindex calc-store-PlotRejects
27485@pindex calc-store-TimeZone
27486@pindex calc-store-Units
27487@pindex calc-store-ExtSimpRules
27488There are several special-purpose variable-editing commands that
27489use the @kbd{s} prefix followed by a shifted letter:
27490
27491@table @kbd
27492@item s A
27493Edit @code{AlgSimpRules}. @xref{Algebraic Simplifications}.
27494@item s D
27495Edit @code{Decls}. @xref{Declarations}.
27496@item s E
27497Edit @code{EvalRules}. @xref{Default Simplifications}.
27498@item s F
27499Edit @code{FitRules}. @xref{Curve Fitting}.
27500@item s G
27501Edit @code{GenCount}. @xref{Solving Equations}.
27502@item s H
27503Edit @code{Holidays}. @xref{Business Days}.
27504@item s I
27505Edit @code{IntegLimit}. @xref{Calculus}.
27506@item s L
27507Edit @code{LineStyles}. @xref{Graphics}.
27508@item s P
27509Edit @code{PointStyles}. @xref{Graphics}.
27510@item s R
27511Edit @code{PlotRejects}. @xref{Graphics}.
27512@item s T
27513Edit @code{TimeZone}. @xref{Time Zones}.
27514@item s U
27515Edit @code{Units}. @xref{User-Defined Units}.
27516@item s X
27517Edit @code{ExtSimpRules}. @xref{Unsafe Simplifications}.
27518@end table
27519
27520These commands are just versions of @kbd{s e} that use fixed variable
27521names rather than prompting for the variable name.
27522
27523@kindex s p
27524@pindex calc-permanent-variable
27525@cindex Storing variables
27526@cindex Permanent variables
27527@cindex @file{.emacs} file, veriables
27528The @kbd{s p} (@code{calc-permanent-variable}) command saves a
27529variable's value permanently in your @file{.emacs} file, so that its
27530value will still be available in future Emacs sessions. You can
27531re-execute @w{@kbd{s p}} later on to update the saved value, but the
27532only way to remove a saved variable is to edit your @file{.emacs} file
27533by hand. (@xref{General Mode Commands}, for a way to tell Calc to
27534use a different file instead of @file{.emacs}.)
27535
27536If you do not specify the name of a variable to save (i.e.,
27537@kbd{s p @key{RET}}), all @samp{var-} variables with defined values
27538are saved except for the special constants @code{pi}, @code{e},
27539@code{i}, @code{phi}, and @code{gamma}; the variables @code{TimeZone}
27540and @code{PlotRejects};
27541@code{FitRules}, @code{DistribRules}, and other built-in rewrite
27542rules; and @code{PlotData@var{n}} variables generated
27543by the graphics commands. (You can still save these variables by
27544explicitly naming them in an @kbd{s p} command.)@refill
27545
27546@kindex s i
27547@pindex calc-insert-variables
27548The @kbd{s i} (@code{calc-insert-variables}) command writes
27549the values of all @samp{var-} variables into a specified buffer.
27550The variables are written in the form of Lisp @code{setq} commands
27551which store the values in string form. You can place these commands
27552in your @file{.emacs} buffer if you wish, though in this case it
27553would be easier to use @kbd{s p @key{RET}}. (Note that @kbd{s i}
27554omits the same set of variables as @w{@kbd{s p @key{RET}}}; the difference
27555is that @kbd{s i} will store the variables in any buffer, and it also
27556stores in a more human-readable format.)
27557
27558@node Let Command, Evaluates-To Operator, Operations on Variables, Store and Recall
27559@section The Let Command
27560
27561@noindent
27562@kindex s l
27563@pindex calc-let
27564@cindex Variables, temporary assignment
27565@cindex Temporary assignment to variables
27566If you have an expression like @samp{a+b^2} on the stack and you wish to
27567compute its value where @cite{b=3}, you can simply store 3 in @cite{b} and
27568then press @kbd{=} to reevaluate the formula. This has the side-effect
27569of leaving the stored value of 3 in @cite{b} for future operations.
27570
27571The @kbd{s l} (@code{calc-let}) command evaluates a formula under a
27572@emph{temporary} assignment of a variable. It stores the value on the
27573top of the stack into the specified variable, then evaluates the
27574second-to-top stack entry, then restores the original value (or lack of one)
27575in the variable. Thus after @kbd{'@w{ }a+b^2 @key{RET} 3 s l b @key{RET}},
27576the stack will contain the formula @samp{a + 9}. The subsequent command
27577@kbd{@w{5 s l a} @key{RET}} will replace this formula with the number 14.
27578The variables @samp{a} and @samp{b} are not permanently affected in any way
27579by these commands.
27580
27581The value on the top of the stack may be an equation or assignment, or
27582a vector of equations or assignments, in which case the default will be
27583analogous to the case of @kbd{s t @key{RET}}. @xref{Storing Variables}.
27584
27585Also, you can answer the variable-name prompt with an equation or
27586assignment: @kbd{s l b=3 RET} is the same as storing 3 on the stack
27587and typing @kbd{s l b RET}.
27588
27589The @kbd{a b} (@code{calc-substitute}) command is another way to substitute
27590a variable with a value in a formula. It does an actual substitution
27591rather than temporarily assigning the variable and evaluating. For
27592example, letting @cite{n=2} in @samp{f(n pi)} with @kbd{a b} will
27593produce @samp{f(2 pi)}, whereas @kbd{s l} would give @samp{f(6.28)}
27594since the evaluation step will also evaluate @code{pi}.
27595
27596@node Evaluates-To Operator, , Let Command, Store and Recall
27597@section The Evaluates-To Operator
27598
27599@noindent
27600@tindex evalto
27601@tindex =>
27602@cindex Evaluates-to operator
27603@cindex @samp{=>} operator
27604The special algebraic symbol @samp{=>} is known as the @dfn{evaluates-to
27605operator}. (It will show up as an @code{evalto} function call in
27606other language modes like Pascal and @TeX{}.) This is a binary
27607operator, that is, it has a lefthand and a righthand argument,
27608although it can be entered with the righthand argument omitted.
27609
27610A formula like @samp{@var{a} => @var{b}} is evaluated by Calc as
27611follows: First, @var{a} is not simplified or modified in any
27612way. The previous value of argument @var{b} is thrown away; the
27613formula @var{a} is then copied and evaluated as if by the @kbd{=}
27614command according to all current modes and stored variable values,
27615and the result is installed as the new value of @var{b}.
27616
27617For example, suppose you enter the algebraic formula @samp{2 + 3 => 17}.
27618The number 17 is ignored, and the lefthand argument is left in its
27619unevaluated form; the result is the formula @samp{2 + 3 => 5}.
27620
27621@kindex s =
27622@pindex calc-evalto
27623You can enter an @samp{=>} formula either directly using algebraic
27624entry (in which case the righthand side may be omitted since it is
27625going to be replaced right away anyhow), or by using the @kbd{s =}
27626(@code{calc-evalto}) command, which takes @var{a} from the stack
27627and replaces it with @samp{@var{a} => @var{b}}.
27628
27629Calc keeps track of all @samp{=>} operators on the stack, and
27630recomputes them whenever anything changes that might affect their
27631values, i.e., a mode setting or variable value. This occurs only
27632if the @samp{=>} operator is at the top level of the formula, or
27633if it is part of a top-level vector. In other words, pushing
27634@samp{2 + (a => 17)} will change the 17 to the actual value of
27635@samp{a} when you enter the formula, but the result will not be
27636dynamically updated when @samp{a} is changed later because the
27637@samp{=>} operator is buried inside a sum. However, a vector
27638of @samp{=>} operators will be recomputed, since it is convenient
27639to push a vector like @samp{[a =>, b =>, c =>]} on the stack to
27640make a concise display of all the variables in your problem.
27641(Another way to do this would be to use @samp{[a, b, c] =>},
27642which provides a slightly different format of display. You
27643can use whichever you find easiest to read.)
27644
27645@kindex m C
27646@pindex calc-auto-recompute
27647The @kbd{m C} (@code{calc-auto-recompute}) command allows you to
27648turn this automatic recomputation on or off. If you turn
27649recomputation off, you must explicitly recompute an @samp{=>}
27650operator on the stack in one of the usual ways, such as by
27651pressing @kbd{=}. Turning recomputation off temporarily can save
27652a lot of time if you will be changing several modes or variables
27653before you look at the @samp{=>} entries again.
27654
27655Most commands are not especially useful with @samp{=>} operators
27656as arguments. For example, given @samp{x + 2 => 17}, it won't
27657work to type @kbd{1 +} to get @samp{x + 3 => 18}. If you want
27658to operate on the lefthand side of the @samp{=>} operator on
27659the top of the stack, type @kbd{j 1} (that's the digit ``one'')
27660to select the lefthand side, execute your commands, then type
27661@kbd{j u} to unselect.
27662
27663All current modes apply when an @samp{=>} operator is computed,
27664including the current simplification mode. Recall that the
27665formula @samp{x + y + x} is not handled by Calc's default
27666simplifications, but the @kbd{a s} command will reduce it to
27667the simpler form @samp{y + 2 x}. You can also type @kbd{m A}
27668to enable an algebraic-simplification mode in which the
27669equivalent of @kbd{a s} is used on all of Calc's results.
27670If you enter @samp{x + y + x =>} normally, the result will
27671be @samp{x + y + x => x + y + x}. If you change to
27672algebraic-simplification mode, the result will be
27673@samp{x + y + x => y + 2 x}. However, just pressing @kbd{a s}
27674once will have no effect on @samp{x + y + x => x + y + x},
27675because the righthand side depends only on the lefthand side
27676and the current mode settings, and the lefthand side is not
27677affected by commands like @kbd{a s}.
27678
27679The ``let'' command (@kbd{s l}) has an interesting interaction
27680with the @samp{=>} operator. The @kbd{s l} command evaluates the
27681second-to-top stack entry with the top stack entry supplying
27682a temporary value for a given variable. As you might expect,
27683if that stack entry is an @samp{=>} operator its righthand
27684side will temporarily show this value for the variable. In
27685fact, all @samp{=>}s on the stack will be updated if they refer
27686to that variable. But this change is temporary in the sense
27687that the next command that causes Calc to look at those stack
27688entries will make them revert to the old variable value.
27689
27690@group
27691@smallexample
276922: a => a 2: a => 17 2: a => a
276931: a + 1 => a + 1 1: a + 1 => 18 1: a + 1 => a + 1
27694 . . .
27695
27696 17 s l a RET p 8 RET
27697@end smallexample
27698@end group
27699
27700Here the @kbd{p 8} command changes the current precision,
27701thus causing the @samp{=>} forms to be recomputed after the
27702influence of the ``let'' is gone. The @kbd{d SPC} command
27703(@code{calc-refresh}) is a handy way to force the @samp{=>}
27704operators on the stack to be recomputed without any other
27705side effects.
27706
27707@kindex s :
27708@pindex calc-assign
27709@tindex assign
27710@tindex :=
27711Embedded Mode also uses @samp{=>} operators. In embedded mode,
27712the lefthand side of an @samp{=>} operator can refer to variables
27713assigned elsewhere in the file by @samp{:=} operators. The
27714assignment operator @samp{a := 17} does not actually do anything
27715by itself. But Embedded Mode recognizes it and marks it as a sort
27716of file-local definition of the variable. You can enter @samp{:=}
27717operators in algebraic mode, or by using the @kbd{s :}
27718(@code{calc-assign}) [@code{assign}] command which takes a variable
27719and value from the stack and replaces them with an assignment.
27720
27721@xref{TeX Language Mode}, for the way @samp{=>} appears in
27722@TeX{} language output. The @dfn{eqn} mode gives similar
27723treatment to @samp{=>}.
27724
27725@node Graphics, Kill and Yank, Store and Recall, Top
27726@chapter Graphics
27727
27728@noindent
27729The commands for graphing data begin with the @kbd{g} prefix key. Calc
27730uses GNUPLOT 2.0 or 3.0 to do graphics. These commands will only work
27731if GNUPLOT is available on your system. (While GNUPLOT sounds like
27732a relative of GNU Emacs, it is actually completely unrelated.
27733However, it is free software and can be obtained from the Free
27734Software Foundation's machine @samp{prep.ai.mit.edu}.)
27735
27736@vindex calc-gnuplot-name
27737If you have GNUPLOT installed on your system but Calc is unable to
27738find it, you may need to set the @code{calc-gnuplot-name} variable
27739in your @file{.emacs} file. You may also need to set some Lisp
27740variables to show Calc how to run GNUPLOT on your system; these
27741are described under @kbd{g D} and @kbd{g O} below. If you are
27742using the X window system, Calc will configure GNUPLOT for you
27743automatically. If you have GNUPLOT 3.0 and you are not using X,
27744Calc will configure GNUPLOT to display graphs using simple character
27745graphics that will work on any terminal.
27746
27747@menu
27748* Basic Graphics::
27749* Three Dimensional Graphics::
27750* Managing Curves::
27751* Graphics Options::
27752* Devices::
27753@end menu
27754
27755@node Basic Graphics, Three Dimensional Graphics, Graphics, Graphics
27756@section Basic Graphics
27757
27758@noindent
27759@kindex g f
27760@pindex calc-graph-fast
27761The easiest graphics command is @kbd{g f} (@code{calc-graph-fast}).
27762This command takes two vectors of equal length from the stack.
27763The vector at the top of the stack represents the ``y'' values of
27764the various data points. The vector in the second-to-top position
27765represents the corresponding ``x'' values. This command runs
27766GNUPLOT (if it has not already been started by previous graphing
27767commands) and displays the set of data points. The points will
27768be connected by lines, and there will also be some kind of symbol
27769to indicate the points themselves.
27770
27771The ``x'' entry may instead be an interval form, in which case suitable
27772``x'' values are interpolated between the minimum and maximum values of
27773the interval (whether the interval is open or closed is ignored).
27774
27775The ``x'' entry may also be a number, in which case Calc uses the
27776sequence of ``x'' values @cite{x}, @cite{x+1}, @cite{x+2}, etc.
27777(Generally the number 0 or 1 would be used for @cite{x} in this case.)
27778
27779The ``y'' entry may be any formula instead of a vector. Calc effectively
27780uses @kbd{N} (@code{calc-eval-num}) to evaluate variables in the formula;
27781the result of this must be a formula in a single (unassigned) variable.
27782The formula is plotted with this variable taking on the various ``x''
27783values. Graphs of formulas by default use lines without symbols at the
27784computed data points. Note that if neither ``x'' nor ``y'' is a vector,
27785Calc guesses at a reasonable number of data points to use. See the
27786@kbd{g N} command below. (The ``x'' values must be either a vector
27787or an interval if ``y'' is a formula.)
27788
27789@c @starindex
27790@tindex xy
27791If ``y'' is (or evaluates to) a formula of the form
27792@samp{xy(@var{x}, @var{y})} then the result is a
27793parametric plot. The two arguments of the fictitious @code{xy} function
27794are used as the ``x'' and ``y'' coordinates of the curve, respectively.
27795In this case the ``x'' vector or interval you specified is not directly
27796visible in the graph. For example, if ``x'' is the interval @samp{[0..360]}
27797and ``y'' is the formula @samp{xy(sin(t), cos(t))}, the resulting graph
27798will be a circle.@refill
27799
27800Also, ``x'' and ``y'' may each be variable names, in which case Calc
27801looks for suitable vectors, intervals, or formulas stored in those
27802variables.
27803
27804The ``x'' and ``y'' values for the data points (as pulled from the vectors,
27805calculated from the formulas, or interpolated from the intervals) should
27806be real numbers (integers, fractions, or floats). If either the ``x''
27807value or the ``y'' value of a given data point is not a real number, that
27808data point will be omitted from the graph. The points on either side
27809of the invalid point will @emph{not} be connected by a line.
27810
27811See the documentation for @kbd{g a} below for a description of the way
27812numeric prefix arguments affect @kbd{g f}.
27813
27814@cindex @code{PlotRejects} variable
27815@vindex PlotRejects
27816If you store an empty vector in the variable @code{PlotRejects}
27817(i.e., @kbd{[ ] s t PlotRejects}), Calc will append information to
27818this vector for every data point which was rejected because its
27819``x'' or ``y'' values were not real numbers. The result will be
27820a matrix where each row holds the curve number, data point number,
27821``x'' value, and ``y'' value for a rejected data point.
27822@xref{Evaluates-To Operator}, for a handy way to keep tabs on the
27823current value of @code{PlotRejects}. @xref{Operations on Variables},
27824for the @kbd{s R} command which is another easy way to examine
27825@code{PlotRejects}.
27826
27827@kindex g c
27828@pindex calc-graph-clear
27829To clear the graphics display, type @kbd{g c} (@code{calc-graph-clear}).
27830If the GNUPLOT output device is an X window, the window will go away.
27831Effects on other kinds of output devices will vary. You don't need
27832to use @kbd{g c} if you don't want to---if you give another @kbd{g f}
27833or @kbd{g p} command later on, it will reuse the existing graphics
27834window if there is one.
27835
27836@node Three Dimensional Graphics, Managing Curves, Basic Graphics, Graphics
27837@section Three-Dimensional Graphics
27838
27839@kindex g F
27840@pindex calc-graph-fast-3d
27841The @kbd{g F} (@code{calc-graph-fast-3d}) command makes a three-dimensional
27842graph. It works only if you have GNUPLOT 3.0 or later; with GNUPLOT 2.0,
27843you will see a GNUPLOT error message if you try this command.
27844
27845The @kbd{g F} command takes three values from the stack, called ``x'',
27846``y'', and ``z'', respectively. As was the case for 2D graphs, there
27847are several options for these values.
27848
27849In the first case, ``x'' and ``y'' are each vectors (not necessarily of
27850the same length); either or both may instead be interval forms. The
27851``z'' value must be a matrix with the same number of rows as elements
27852in ``x'', and the same number of columns as elements in ``y''. The
27853result is a surface plot where @c{$z_{ij}$}
27854@cite{z_ij} is the height of the point
27855at coordinate @cite{(x_i, y_j)} on the surface. The 3D graph will
27856be displayed from a certain default viewpoint; you can change this
27857viewpoint by adding a @samp{set view} to the @samp{*Gnuplot Commands*}
27858buffer as described later. See the GNUPLOT 3.0 documentation for a
27859description of the @samp{set view} command.
27860
27861Each point in the matrix will be displayed as a dot in the graph,
27862and these points will be connected by a grid of lines (@dfn{isolines}).
27863
27864In the second case, ``x'', ``y'', and ``z'' are all vectors of equal
27865length. The resulting graph displays a 3D line instead of a surface,
27866where the coordinates of points along the line are successive triplets
27867of values from the input vectors.
27868
27869In the third case, ``x'' and ``y'' are vectors or interval forms, and
27870``z'' is any formula involving two variables (not counting variables
27871with assigned values). These variables are sorted into alphabetical
27872order; the first takes on values from ``x'' and the second takes on
27873values from ``y'' to form a matrix of results that are graphed as a
278743D surface.
27875
27876@c @starindex
27877@tindex xyz
27878If the ``z'' formula evaluates to a call to the fictitious function
27879@samp{xyz(@var{x}, @var{y}, @var{z})}, then the result is a
27880``parametric surface.'' In this case, the axes of the graph are
27881taken from the @var{x} and @var{y} values in these calls, and the
27882``x'' and ``y'' values from the input vectors or intervals are used only
27883to specify the range of inputs to the formula. For example, plotting
27884@samp{[0..360], [0..180], xyz(sin(x)*sin(y), cos(x)*sin(y), cos(y))}
27885will draw a sphere. (Since the default resolution for 3D plots is
278865 steps in each of ``x'' and ``y'', this will draw a very crude
27887sphere. You could use the @kbd{g N} command, described below, to
27888increase this resolution, or specify the ``x'' and ``y'' values as
27889vectors with more than 5 elements.
27890
27891It is also possible to have a function in a regular @kbd{g f} plot
27892evaluate to an @code{xyz} call. Since @kbd{g f} plots a line, not
27893a surface, the result will be a 3D parametric line. For example,
27894@samp{[[0..720], xyz(sin(x), cos(x), x)]} will plot two turns of a
27895helix (a three-dimensional spiral).
27896
27897As for @kbd{g f}, each of ``x'', ``y'', and ``z'' may instead be
27898variables containing the relevant data.
27899
27900@node Managing Curves, Graphics Options, Three Dimensional Graphics, Graphics
27901@section Managing Curves
27902
27903@noindent
27904The @kbd{g f} command is really shorthand for the following commands:
27905@kbd{C-u g d g a g p}. Likewise, @w{@kbd{g F}} is shorthand for
27906@kbd{C-u g d g A g p}. You can gain more control over your graph
27907by using these commands directly.
27908
27909@kindex g a
27910@pindex calc-graph-add
27911The @kbd{g a} (@code{calc-graph-add}) command adds the ``curve''
27912represented by the two values on the top of the stack to the current
27913graph. You can have any number of curves in the same graph. When
27914you give the @kbd{g p} command, all the curves will be drawn superimposed
27915on the same axes.
27916
27917The @kbd{g a} command (and many others that affect the current graph)
27918will cause a special buffer, @samp{*Gnuplot Commands*}, to be displayed
27919in another window. This buffer is a template of the commands that will
27920be sent to GNUPLOT when it is time to draw the graph. The first
27921@kbd{g a} command adds a @code{plot} command to this buffer. Succeeding
27922@kbd{g a} commands add extra curves onto that @code{plot} command.
27923Other graph-related commands put other GNUPLOT commands into this
27924buffer. In normal usage you never need to work with this buffer
27925directly, but you can if you wish. The only constraint is that there
27926must be only one @code{plot} command, and it must be the last command
27927in the buffer. If you want to save and later restore a complete graph
27928configuration, you can use regular Emacs commands to save and restore
27929the contents of the @samp{*Gnuplot Commands*} buffer.
27930
27931@vindex PlotData1
27932@vindex PlotData2
27933If the values on the stack are not variable names, @kbd{g a} will invent
27934variable names for them (of the form @samp{PlotData@var{n}}) and store
27935the values in those variables. The ``x'' and ``y'' variables are what
27936go into the @code{plot} command in the template. If you add a curve
27937that uses a certain variable and then later change that variable, you
27938can replot the graph without having to delete and re-add the curve.
27939That's because the variable name, not the vector, interval or formula
27940itself, is what was added by @kbd{g a}.
27941
27942A numeric prefix argument on @kbd{g a} or @kbd{g f} changes the way
27943stack entries are interpreted as curves. With a positive prefix
27944argument @cite{n}, the top @cite{n} stack entries are ``y'' values
27945for @cite{n} different curves which share a common ``x'' value in
27946the @cite{n+1}st stack entry. (Thus @kbd{g a} with no prefix
27947argument is equivalent to @kbd{C-u 1 g a}.)
27948
27949A prefix of zero or plain @kbd{C-u} means to take two stack entries,
27950``x'' and ``y'' as usual, but to interpret ``y'' as a vector of
27951``y'' values for several curves that share a common ``x''.
27952
27953A negative prefix argument tells Calc to read @cite{n} vectors from
27954the stack; each vector @cite{[x, y]} describes an independent curve.
27955This is the only form of @kbd{g a} that creates several curves at once
27956that don't have common ``x'' values. (Of course, the range of ``x''
27957values covered by all the curves ought to be roughly the same if
27958they are to look nice on the same graph.)
27959
27960For example, to plot @c{$\sin n x$}
27961@cite{sin(n x)} for integers @cite{n}
27962from 1 to 5, you could use @kbd{v x} to create a vector of integers
27963(@cite{n}), then @kbd{V M '} or @kbd{V M $} to map @samp{sin(n x)}
27964across this vector. The resulting vector of formulas is suitable
27965for use as the ``y'' argument to a @kbd{C-u g a} or @kbd{C-u g f}
27966command.
27967
27968@kindex g A
27969@pindex calc-graph-add-3d
27970The @kbd{g A} (@code{calc-graph-add-3d}) command adds a 3D curve
27971to the graph. It is not legal to intermix 2D and 3D curves in a
27972single graph. This command takes three arguments, ``x'', ``y'',
27973and ``z'', from the stack. With a positive prefix @cite{n}, it
27974takes @cite{n+2} arguments (common ``x'' and ``y'', plus @cite{n}
27975separate ``z''s). With a zero prefix, it takes three stack entries
27976but the ``z'' entry is a vector of curve values. With a negative
27977prefix @cite{-n}, it takes @cite{n} vectors of the form @cite{[x, y, z]}.
27978The @kbd{g A} command works by adding a @code{splot} (surface-plot)
27979command to the @samp{*Gnuplot Commands*} buffer.
27980
27981(Although @kbd{g a} adds a 2D @code{plot} command to the
27982@samp{*Gnuplot Commands*} buffer, Calc changes this to @code{splot}
27983before sending it to GNUPLOT if it notices that the data points are
27984evaluating to @code{xyz} calls. It will not work to mix 2D and 3D
27985@kbd{g a} curves in a single graph, although Calc does not currently
27986check for this.)
27987
27988@kindex g d
27989@pindex calc-graph-delete
27990The @kbd{g d} (@code{calc-graph-delete}) command deletes the most
27991recently added curve from the graph. It has no effect if there are
27992no curves in the graph. With a numeric prefix argument of any kind,
27993it deletes all of the curves from the graph.
27994
27995@kindex g H
27996@pindex calc-graph-hide
27997The @kbd{g H} (@code{calc-graph-hide}) command ``hides'' or ``unhides''
27998the most recently added curve. A hidden curve will not appear in
27999the actual plot, but information about it such as its name and line and
28000point styles will be retained.
28001
28002@kindex g j
28003@pindex calc-graph-juggle
28004The @kbd{g j} (@code{calc-graph-juggle}) command moves the curve
28005at the end of the list (the ``most recently added curve'') to the
28006front of the list. The next-most-recent curve is thus exposed for
28007@w{@kbd{g d}} or similar commands to use. With @kbd{g j} you can work
28008with any curve in the graph even though curve-related commands only
28009affect the last curve in the list.
28010
28011@kindex g p
28012@pindex calc-graph-plot
28013The @kbd{g p} (@code{calc-graph-plot}) command uses GNUPLOT to draw
28014the graph described in the @samp{*Gnuplot Commands*} buffer. Any
28015GNUPLOT parameters which are not defined by commands in this buffer
28016are reset to their default values. The variables named in the @code{plot}
28017command are written to a temporary data file and the variable names
28018are then replaced by the file name in the template. The resulting
28019plotting commands are fed to the GNUPLOT program. See the documentation
28020for the GNUPLOT program for more specific information. All temporary
28021files are removed when Emacs or GNUPLOT exits.
28022
28023If you give a formula for ``y'', Calc will remember all the values that
28024it calculates for the formula so that later plots can reuse these values.
28025Calc throws out these saved values when you change any circumstances
28026that may affect the data, such as switching from Degrees to Radians
28027mode, or changing the value of a parameter in the formula. You can
28028force Calc to recompute the data from scratch by giving a negative
28029numeric prefix argument to @kbd{g p}.
28030
28031Calc uses a fairly rough step size when graphing formulas over intervals.
28032This is to ensure quick response. You can ``refine'' a plot by giving
28033a positive numeric prefix argument to @kbd{g p}. Calc goes through
28034the data points it has computed and saved from previous plots of the
28035function, and computes and inserts a new data point midway between
28036each of the existing points. You can refine a plot any number of times,
28037but beware that the amount of calculation involved doubles each time.
28038
28039Calc does not remember computed values for 3D graphs. This means the
28040numerix prefix argument, if any, to @kbd{g p} is effectively ignored if
28041the current graph is three-dimensional.
28042
28043@kindex g P
28044@pindex calc-graph-print
28045The @kbd{g P} (@code{calc-graph-print}) command is like @kbd{g p},
28046except that it sends the output to a printer instead of to the
28047screen. More precisely, @kbd{g p} looks for @samp{set terminal}
28048or @samp{set output} commands in the @samp{*Gnuplot Commands*} buffer;
28049lacking these it uses the default settings. However, @kbd{g P}
28050ignores @samp{set terminal} and @samp{set output} commands and
28051uses a different set of default values. All of these values are
28052controlled by the @kbd{g D} and @kbd{g O} commands discussed below.
28053Provided everything is set up properly, @kbd{g p} will plot to
28054the screen unless you have specified otherwise and @kbd{g P} will
28055always plot to the printer.
28056
28057@node Graphics Options, Devices, Managing Curves, Graphics
28058@section Graphics Options
28059
28060@noindent
28061@kindex g g
28062@pindex calc-graph-grid
28063The @kbd{g g} (@code{calc-graph-grid}) command turns the ``grid''
28064on and off. It is off by default; tick marks appear only at the
28065edges of the graph. With the grid turned on, dotted lines appear
28066across the graph at each tick mark. Note that this command only
28067changes the setting in @samp{*Gnuplot Commands*}; to see the effects
28068of the change you must give another @kbd{g p} command.
28069
28070@kindex g b
28071@pindex calc-graph-border
28072The @kbd{g b} (@code{calc-graph-border}) command turns the border
28073(the box that surrounds the graph) on and off. It is on by default.
28074This command will only work with GNUPLOT 3.0 and later versions.
28075
28076@kindex g k
28077@pindex calc-graph-key
28078The @kbd{g k} (@code{calc-graph-key}) command turns the ``key''
28079on and off. The key is a chart in the corner of the graph that
28080shows the correspondence between curves and line styles. It is
28081off by default, and is only really useful if you have several
28082curves on the same graph.
28083
28084@kindex g N
28085@pindex calc-graph-num-points
28086The @kbd{g N} (@code{calc-graph-num-points}) command allows you
28087to select the number of data points in the graph. This only affects
28088curves where neither ``x'' nor ``y'' is specified as a vector.
28089Enter a blank line to revert to the default value (initially 15).
28090With no prefix argument, this command affects only the current graph.
28091With a positive prefix argument this command changes or, if you enter
28092a blank line, displays the default number of points used for all
28093graphs created by @kbd{g a} that don't specify the resolution explicitly.
28094With a negative prefix argument, this command changes or displays
28095the default value (initially 5) used for 3D graphs created by @kbd{g A}.
28096Note that a 3D setting of 5 means that a total of @cite{5^2 = 25} points
28097will be computed for the surface.
28098
28099Data values in the graph of a function are normally computed to a
28100precision of five digits, regardless of the current precision at the
28101time. This is usually more than adequate, but there are cases where
28102it will not be. For example, plotting @cite{1 + x} with @cite{x} in the
28103interval @samp{[0 ..@: 1e-6]} will round all the data points down
28104to 1.0! Putting the command @samp{set precision @var{n}} in the
28105@samp{*Gnuplot Commands*} buffer will cause the data to be computed
28106at precision @var{n} instead of 5. Since this is such a rare case,
28107there is no keystroke-based command to set the precision.
28108
28109@kindex g h
28110@pindex calc-graph-header
28111The @kbd{g h} (@code{calc-graph-header}) command sets the title
28112for the graph. This will show up centered above the graph.
28113The default title is blank (no title).
28114
28115@kindex g n
28116@pindex calc-graph-name
28117The @kbd{g n} (@code{calc-graph-name}) command sets the title of an
28118individual curve. Like the other curve-manipulating commands, it
28119affects the most recently added curve, i.e., the last curve on the
28120list in the @samp{*Gnuplot Commands*} buffer. To set the title of
28121the other curves you must first juggle them to the end of the list
28122with @kbd{g j}, or edit the @samp{*Gnuplot Commands*} buffer by hand.
28123Curve titles appear in the key; if the key is turned off they are
28124not used.
28125
28126@kindex g t
28127@kindex g T
28128@pindex calc-graph-title-x
28129@pindex calc-graph-title-y
28130The @kbd{g t} (@code{calc-graph-title-x}) and @kbd{g T}
28131(@code{calc-graph-title-y}) commands set the titles on the ``x''
28132and ``y'' axes, respectively. These titles appear next to the
28133tick marks on the left and bottom edges of the graph, respectively.
28134Calc does not have commands to control the tick marks themselves,
28135but you can edit them into the @samp{*Gnuplot Commands*} buffer if
28136you wish. See the GNUPLOT documentation for details.
28137
28138@kindex g r
28139@kindex g R
28140@pindex calc-graph-range-x
28141@pindex calc-graph-range-y
28142The @kbd{g r} (@code{calc-graph-range-x}) and @kbd{g R}
28143(@code{calc-graph-range-y}) commands set the range of values on the
28144``x'' and ``y'' axes, respectively. You are prompted to enter a
28145suitable range. This should be either a pair of numbers of the
28146form, @samp{@var{min}:@var{max}}, or a blank line to revert to the
28147default behavior of setting the range based on the range of values
28148in the data, or @samp{$} to take the range from the top of the stack.
28149Ranges on the stack can be represented as either interval forms or
28150vectors: @samp{[@var{min} ..@: @var{max}]} or @samp{[@var{min}, @var{max}]}.
28151
28152@kindex g l
28153@kindex g L
28154@pindex calc-graph-log-x
28155@pindex calc-graph-log-y
28156The @kbd{g l} (@code{calc-graph-log-x}) and @kbd{g L} (@code{calc-graph-log-y})
28157commands allow you to set either or both of the axes of the graph to
28158be logarithmic instead of linear.
28159
28160@kindex g C-l
28161@kindex g C-r
28162@kindex g C-t
28163@pindex calc-graph-log-z
28164@pindex calc-graph-range-z
28165@pindex calc-graph-title-z
28166For 3D plots, @kbd{g C-t}, @kbd{g C-r}, and @kbd{g C-l} (those are
28167letters with the Control key held down) are the corresponding commands
28168for the ``z'' axis.
28169
28170@kindex g z
28171@kindex g Z
28172@pindex calc-graph-zero-x
28173@pindex calc-graph-zero-y
28174The @kbd{g z} (@code{calc-graph-zero-x}) and @kbd{g Z}
28175(@code{calc-graph-zero-y}) commands control whether a dotted line is
28176drawn to indicate the ``x'' and/or ``y'' zero axes. (These are the same
28177dotted lines that would be drawn there anyway if you used @kbd{g g} to
28178turn the ``grid'' feature on.) Zero-axis lines are on by default, and
28179may be turned off only in GNUPLOT 3.0 and later versions. They are
28180not available for 3D plots.
28181
28182@kindex g s
28183@pindex calc-graph-line-style
28184The @kbd{g s} (@code{calc-graph-line-style}) command turns the connecting
28185lines on or off for the most recently added curve, and optionally selects
28186the style of lines to be used for that curve. Plain @kbd{g s} simply
28187toggles the lines on and off. With a numeric prefix argument, @kbd{g s}
28188turns lines on and sets a particular line style. Line style numbers
28189start at one and their meanings vary depending on the output device.
28190GNUPLOT guarantees that there will be at least six different line styles
28191available for any device.
28192
28193@kindex g S
28194@pindex calc-graph-point-style
28195The @kbd{g S} (@code{calc-graph-point-style}) command similarly turns
28196the symbols at the data points on or off, or sets the point style.
28197If you turn both lines and points off, the data points will show as
28198tiny dots.
28199
28200@cindex @code{LineStyles} variable
28201@cindex @code{PointStyles} variable
28202@vindex LineStyles
28203@vindex PointStyles
28204Another way to specify curve styles is with the @code{LineStyles} and
28205@code{PointStyles} variables. These variables initially have no stored
28206values, but if you store a vector of integers in one of these variables,
28207the @kbd{g a} and @kbd{g f} commands will use those style numbers
28208instead of the defaults for new curves that are added to the graph.
28209An entry should be a positive integer for a specific style, or 0 to let
28210the style be chosen automatically, or @i{-1} to turn off lines or points
28211altogether. If there are more curves than elements in the vector, the
28212last few curves will continue to have the default styles. Of course,
28213you can later use @kbd{g s} and @kbd{g S} to change any of these styles.
28214
28215For example, @kbd{'[2 -1 3] RET s t LineStyles} causes the first curve
28216to have lines in style number 2, the second curve to have no connecting
28217lines, and the third curve to have lines in style 3. Point styles will
28218still be assigned automatically, but you could store another vector in
28219@code{PointStyles} to define them, too.
28220
28221@node Devices, , Graphics Options, Graphics
28222@section Graphical Devices
28223
28224@noindent
28225@kindex g D
28226@pindex calc-graph-device
28227The @kbd{g D} (@code{calc-graph-device}) command sets the device name
28228(or ``terminal name'' in GNUPLOT lingo) to be used by @kbd{g p} commands
28229on this graph. It does not affect the permanent default device name.
28230If you enter a blank name, the device name reverts to the default.
28231Enter @samp{?} to see a list of supported devices.
28232
28233With a positive numeric prefix argument, @kbd{g D} instead sets
28234the default device name, used by all plots in the future which do
28235not override it with a plain @kbd{g D} command. If you enter a
28236blank line this command shows you the current default. The special
28237name @code{default} signifies that Calc should choose @code{x11} if
28238the X window system is in use (as indicated by the presence of a
28239@code{DISPLAY} environment variable), or otherwise @code{dumb} under
28240GNUPLOT 3.0 and later, or @code{postscript} under GNUPLOT 2.0.
28241This is the initial default value.
28242
28243The @code{dumb} device is an interface to ``dumb terminals,'' i.e.,
28244terminals with no special graphics facilities. It writes a crude
28245picture of the graph composed of characters like @code{-} and @code{|}
28246to a buffer called @samp{*Gnuplot Trail*}, which Calc then displays.
28247The graph is made the same size as the Emacs screen, which on most
28248dumb terminals will be @c{$80\times24$}
28249@asis{80x24} characters. The graph is displayed in
28250an Emacs ``recursive edit''; type @kbd{q} or @kbd{M-# M-#} to exit
28251the recursive edit and return to Calc. Note that the @code{dumb}
28252device is present only in GNUPLOT 3.0 and later versions.
28253
28254The word @code{dumb} may be followed by two numbers separated by
28255spaces. These are the desired width and height of the graph in
28256characters. Also, the device name @code{big} is like @code{dumb}
28257but creates a graph four times the width and height of the Emacs
28258screen. You will then have to scroll around to view the entire
28259graph. In the @samp{*Gnuplot Trail*} buffer, @key{SPC}, @key{DEL},
28260@kbd{<}, and @kbd{>} are defined to scroll by one screenful in each
28261of the four directions.
28262
28263With a negative numeric prefix argument, @kbd{g D} sets or displays
28264the device name used by @kbd{g P} (@code{calc-graph-print}). This
28265is initially @code{postscript}. If you don't have a PostScript
28266printer, you may decide once again to use @code{dumb} to create a
28267plot on any text-only printer.
28268
28269@kindex g O
28270@pindex calc-graph-output
28271The @kbd{g O} (@code{calc-graph-output}) command sets the name of
28272the output file used by GNUPLOT. For some devices, notably @code{x11},
28273there is no output file and this information is not used. Many other
28274``devices'' are really file formats like @code{postscript}; in these
28275cases the output in the desired format goes into the file you name
28276with @kbd{g O}. Type @kbd{g O stdout RET} to set GNUPLOT to write
28277to its standard output stream, i.e., to @samp{*Gnuplot Trail*}.
28278This is the default setting.
28279
28280Another special output name is @code{tty}, which means that GNUPLOT
28281is going to write graphics commands directly to its standard output,
28282which you wish Emacs to pass through to your terminal. Tektronix
28283graphics terminals, among other devices, operate this way. Calc does
28284this by telling GNUPLOT to write to a temporary file, then running a
28285sub-shell executing the command @samp{cat tempfile >/dev/tty}. On
28286typical Unix systems, this will copy the temporary file directly to
28287the terminal, bypassing Emacs entirely. You will have to type @kbd{C-l}
28288to Emacs afterwards to refresh the screen.
28289
28290Once again, @kbd{g O} with a positive or negative prefix argument
28291sets the default or printer output file names, respectively. In each
28292case you can specify @code{auto}, which causes Calc to invent a temporary
28293file name for each @kbd{g p} (or @kbd{g P}) command. This temporary file
28294will be deleted once it has been displayed or printed. If the output file
28295name is not @code{auto}, the file is not automatically deleted.
28296
28297The default and printer devices and output files can be saved
28298permanently by the @kbd{m m} (@code{calc-save-modes}) command. The
28299default number of data points (see @kbd{g N}) and the X geometry
28300(see @kbd{g X}) are also saved. Other graph information is @emph{not}
28301saved; you can save a graph's configuration simply by saving the contents
28302of the @samp{*Gnuplot Commands*} buffer.
28303
28304@vindex calc-gnuplot-plot-command
28305@vindex calc-gnuplot-default-device
28306@vindex calc-gnuplot-default-output
28307@vindex calc-gnuplot-print-command
28308@vindex calc-gnuplot-print-device
28309@vindex calc-gnuplot-print-output
28310If you are installing Calc you may wish to configure the default and
28311printer devices and output files for the whole system. The relevant
28312Lisp variables are @code{calc-gnuplot-default-device} and @code{-output},
28313and @code{calc-gnuplot-print-device} and @code{-output}. The output
28314file names must be either strings as described above, or Lisp
28315expressions which are evaluated on the fly to get the output file names.
28316
28317Other important Lisp variables are @code{calc-gnuplot-plot-command} and
28318@code{calc-gnuplot-print-command}, which give the system commands to
28319display or print the output of GNUPLOT, respectively. These may be
28320@code{nil} if no command is necessary, or strings which can include
28321@samp{%s} to signify the name of the file to be displayed or printed.
28322Or, these variables may contain Lisp expressions which are evaluated
28323to display or print the output.
28324
28325@kindex g x
28326@pindex calc-graph-display
28327The @kbd{g x} (@code{calc-graph-display}) command lets you specify
28328on which X window system display your graphs should be drawn. Enter
28329a blank line to see the current display name. This command has no
28330effect unless the current device is @code{x11}.
28331
28332@kindex g X
28333@pindex calc-graph-geometry
28334The @kbd{g X} (@code{calc-graph-geometry}) command is a similar
28335command for specifying the position and size of the X window.
28336The normal value is @code{default}, which generally means your
28337window manager will let you place the window interactively.
28338Entering @samp{800x500+0+0} would create an 800-by-500 pixel
28339window in the upper-left corner of the screen.
28340
28341The buffer called @samp{*Gnuplot Trail*} holds a transcript of the
28342session with GNUPLOT. This shows the commands Calc has ``typed'' to
28343GNUPLOT and the responses it has received. Calc tries to notice when an
28344error message has appeared here and display the buffer for you when
28345this happens. You can check this buffer yourself if you suspect
28346something has gone wrong.
28347
28348@kindex g C
28349@pindex calc-graph-command
28350The @kbd{g C} (@code{calc-graph-command}) command prompts you to
28351enter any line of text, then simply sends that line to the current
28352GNUPLOT process. The @samp{*Gnuplot Trail*} buffer looks deceptively
28353like a Shell buffer but you can't type commands in it yourself.
28354Instead, you must use @kbd{g C} for this purpose.
28355
28356@kindex g v
28357@kindex g V
28358@pindex calc-graph-view-commands
28359@pindex calc-graph-view-trail
28360The @kbd{g v} (@code{calc-graph-view-commands}) and @kbd{g V}
28361(@code{calc-graph-view-trail}) commands display the @samp{*Gnuplot Commands*}
28362and @samp{*Gnuplot Trail*} buffers, respectively, in another window.
28363This happens automatically when Calc thinks there is something you
28364will want to see in either of these buffers. If you type @kbd{g v}
28365or @kbd{g V} when the relevant buffer is already displayed, the
28366buffer is hidden again.
28367
28368One reason to use @kbd{g v} is to add your own commands to the
28369@samp{*Gnuplot Commands*} buffer. Press @kbd{g v}, then use
28370@kbd{C-x o} to switch into that window. For example, GNUPLOT has
28371@samp{set label} and @samp{set arrow} commands that allow you to
28372annotate your plots. Since Calc doesn't understand these commands,
28373you have to add them to the @samp{*Gnuplot Commands*} buffer
28374yourself, then use @w{@kbd{g p}} to replot using these new commands. Note
28375that your commands must appear @emph{before} the @code{plot} command.
28376To get help on any GNUPLOT feature, type, e.g., @kbd{g C help set label}.
28377You may have to type @kbd{g C RET} a few times to clear the
28378``press return for more'' or ``subtopic of @dots{}'' requests.
28379Note that Calc always sends commands (like @samp{set nolabel}) to
28380reset all plotting parameters to the defaults before each plot, so
28381to delete a label all you need to do is delete the @samp{set label}
28382line you added (or comment it out with @samp{#}) and then replot
28383with @kbd{g p}.
28384
28385@kindex g q
28386@pindex calc-graph-quit
28387You can use @kbd{g q} (@code{calc-graph-quit}) to kill the GNUPLOT
28388process that is running. The next graphing command you give will
28389start a fresh GNUPLOT process. The word @samp{Graph} appears in
28390the Calc window's mode line whenever a GNUPLOT process is currently
28391running. The GNUPLOT process is automatically killed when you
28392exit Emacs if you haven't killed it manually by then.
28393
28394@kindex g K
28395@pindex calc-graph-kill
28396The @kbd{g K} (@code{calc-graph-kill}) command is like @kbd{g q}
28397except that it also views the @samp{*Gnuplot Trail*} buffer so that
28398you can see the process being killed. This is better if you are
28399killing GNUPLOT because you think it has gotten stuck.
28400
28401@node Kill and Yank, Keypad Mode, Graphics, Top
28402@chapter Kill and Yank Functions
28403
28404@noindent
28405The commands in this chapter move information between the Calculator and
28406other Emacs editing buffers.
28407
28408In many cases Embedded Mode is an easier and more natural way to
28409work with Calc from a regular editing buffer. @xref{Embedded Mode}.
28410
28411@menu
28412* Killing From Stack::
28413* Yanking Into Stack::
28414* Grabbing From Buffers::
28415* Yanking Into Buffers::
28416* X Cut and Paste::
28417@end menu
28418
28419@node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank
28420@section Killing from the Stack
28421
28422@noindent
28423@kindex C-k
28424@pindex calc-kill
28425@kindex M-k
28426@pindex calc-copy-as-kill
28427@kindex C-w
28428@pindex calc-kill-region
28429@kindex M-w
28430@pindex calc-copy-region-as-kill
28431@cindex Kill ring
28432@dfn{Kill} commands are Emacs commands that insert text into the
28433``kill ring,'' from which it can later be ``yanked'' by a @kbd{C-y}
28434command. Three common kill commands in normal Emacs are @kbd{C-k}, which
28435kills one line, @kbd{C-w}, which kills the region between mark and point,
28436and @kbd{M-w}, which puts the region into the kill ring without actually
28437deleting it. All of these commands work in the Calculator, too. Also,
28438@kbd{M-k} has been provided to complete the set; it puts the current line
28439into the kill ring without deleting anything.
28440
28441The kill commands are unusual in that they pay attention to the location
28442of the cursor in the Calculator buffer. If the cursor is on or below the
28443bottom line, the kill commands operate on the top of the stack. Otherwise,
28444they operate on whatever stack element the cursor is on. Calc's kill
28445commands always operate on whole stack entries. (They act the same as their
28446standard Emacs cousins except they ``round up'' the specified region to
28447encompass full lines.) The text is copied into the kill ring exactly as
28448it appears on the screen, including line numbers if they are enabled.
28449
28450A numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number
28451of lines killed. A positive argument kills the current line and @cite{n-1}
28452lines below it. A negative argument kills the @cite{-n} lines above the
28453current line. Again this mirrors the behavior of the standard Emacs
28454@kbd{C-k} command. Although a whole line is always deleted, @kbd{C-k}
28455with no argument copies only the number itself into the kill ring, whereas
28456@kbd{C-k} with a prefix argument of 1 copies the number with its trailing
28457newline.
28458
28459@node Yanking Into Stack, Grabbing From Buffers, Killing From Stack, Kill and Yank
28460@section Yanking into the Stack
28461
28462@noindent
28463@kindex C-y
28464@pindex calc-yank
28465The @kbd{C-y} command yanks the most recently killed text back into the
28466Calculator. It pushes this value onto the top of the stack regardless of
28467the cursor position. In general it re-parses the killed text as a number
28468or formula (or a list of these separated by commas or newlines). However if
28469the thing being yanked is something that was just killed from the Calculator
28470itself, its full internal structure is yanked. For example, if you have
28471set the floating-point display mode to show only four significant digits,
28472then killing and re-yanking 3.14159 (which displays as 3.142) will yank the
28473full 3.14159, even though yanking it into any other buffer would yank the
28474number in its displayed form, 3.142. (Since the default display modes
28475show all objects to their full precision, this feature normally makes no
28476difference.)
28477
28478@node Grabbing From Buffers, Yanking Into Buffers, Yanking Into Stack, Kill and Yank
28479@section Grabbing from Other Buffers
28480
28481@noindent
28482@kindex M-# g
28483@pindex calc-grab-region
28484The @kbd{M-# g} (@code{calc-grab-region}) command takes the text between
28485point and mark in the current buffer and attempts to parse it as a
28486vector of values. Basically, it wraps the text in vector brackets
28487@samp{[ ]} unless the text already is enclosed in vector brackets,
28488then reads the text as if it were an algebraic entry. The contents
28489of the vector may be numbers, formulas, or any other Calc objects.
28490If the @kbd{M-# g} command works successfully, it does an automatic
28491@kbd{M-# c} to enter the Calculator buffer.
28492
28493A numeric prefix argument grabs the specified number of lines around
28494point, ignoring the mark. A positive prefix grabs from point to the
28495@cite{n}th following newline (so that @kbd{M-1 M-# g} grabs from point
28496to the end of the current line); a negative prefix grabs from point
28497back to the @cite{n+1}st preceding newline. In these cases the text
28498that is grabbed is exactly the same as the text that @kbd{C-k} would
28499delete given that prefix argument.
28500
28501A prefix of zero grabs the current line; point may be anywhere on the
28502line.
28503
28504A plain @kbd{C-u} prefix interprets the region between point and mark
28505as a single number or formula rather than a vector. For example,
28506@kbd{M-# g} on the text @samp{2 a b} produces the vector of three
28507values @samp{[2, a, b]}, but @kbd{C-u M-# g} on the same region
28508reads a formula which is a product of three things: @samp{2 a b}.
28509(The text @samp{a + b}, on the other hand, will be grabbed as a
28510vector of one element by plain @kbd{M-# g} because the interpretation
28511@samp{[a, +, b]} would be a syntax error.)
28512
28513If a different language has been specified (@pxref{Language Modes}),
28514the grabbed text will be interpreted according to that language.
28515
28516@kindex M-# r
28517@pindex calc-grab-rectangle
28518The @kbd{M-# r} (@code{calc-grab-rectangle}) command takes the text between
28519point and mark and attempts to parse it as a matrix. If point and mark
28520are both in the leftmost column, the lines in between are parsed in their
28521entirety. Otherwise, point and mark define the corners of a rectangle
28522whose contents are parsed.
28523
28524Each line of the grabbed area becomes a row of the matrix. The result
28525will actually be a vector of vectors, which Calc will treat as a matrix
28526only if every row contains the same number of values.
28527
28528If a line contains a portion surrounded by square brackets (or curly
28529braces), that portion is interpreted as a vector which becomes a row
28530of the matrix. Any text surrounding the bracketed portion on the line
28531is ignored.
28532
28533Otherwise, the entire line is interpreted as a row vector as if it
28534were surrounded by square brackets. Leading line numbers (in the
28535format used in the Calc stack buffer) are ignored. If you wish to
28536force this interpretation (even if the line contains bracketed
28537portions), give a negative numeric prefix argument to the
28538@kbd{M-# r} command.
28539
28540If you give a numeric prefix argument of zero or plain @kbd{C-u}, each
28541line is instead interpreted as a single formula which is converted into
28542a one-element vector. Thus the result of @kbd{C-u M-# r} will be a
28543one-column matrix. For example, suppose one line of the data is the
28544expression @samp{2 a}. A plain @w{@kbd{M-# r}} will interpret this as
28545@samp{[2 a]}, which in turn is read as a two-element vector that forms
28546one row of the matrix. But a @kbd{C-u M-# r} will interpret this row
28547as @samp{[2*a]}.
28548
28549If you give a positive numeric prefix argument @var{n}, then each line
28550will be split up into columns of width @var{n}; each column is parsed
28551separately as a matrix element. If a line contained
28552@w{@samp{2 +/- 3 4 +/- 5}}, then grabbing with a prefix argument of 8
28553would correctly split the line into two error forms.@refill
28554
28555@xref{Matrix Functions}, to see how to pull the matrix apart into its
28556constituent rows and columns. (If it is a @c{$1\times1$}
28557@asis{1x1} matrix, just hit @kbd{v u}
28558(@code{calc-unpack}) twice.)
28559
28560@kindex M-# :
28561@kindex M-# _
28562@pindex calc-grab-sum-across
28563@pindex calc-grab-sum-down
28564@cindex Summing rows and columns of data
28565The @kbd{M-# :} (@code{calc-grab-sum-down}) command is a handy way to
28566grab a rectangle of data and sum its columns. It is equivalent to
28567typing @kbd{M-# r}, followed by @kbd{V R : +} (the vector reduction
28568command that sums the columns of a matrix; @pxref{Reducing}). The
28569result of the command will be a vector of numbers, one for each column
28570in the input data. The @kbd{M-# _} (@code{calc-grab-sum-across}) command
28571similarly grabs a rectangle and sums its rows by executing @w{@kbd{V R _ +}}.
28572
28573As well as being more convenient, @kbd{M-# :} and @kbd{M-# _} are also
28574much faster because they don't actually place the grabbed vector on
28575the stack. In a @kbd{M-# r V R : +} sequence, formatting the vector
28576for display on the stack takes a large fraction of the total time
28577(unless you have planned ahead and used @kbd{v .} and @kbd{t .} modes).
28578
28579For example, suppose we have a column of numbers in a file which we
28580wish to sum. Go to one corner of the column and press @kbd{C-@@} to
28581set the mark; go to the other corner and type @kbd{M-# :}. Since there
28582is only one column, the result will be a vector of one number, the sum.
28583(You can type @kbd{v u} to unpack this vector into a plain number if
28584you want to do further arithmetic with it.)
28585
28586To compute the product of the column of numbers, we would have to do
28587it ``by hand'' since there's no special grab-and-multiply command.
28588Use @kbd{M-# r} to grab the column of numbers into the calculator in
28589the form of a column matrix. The statistics command @kbd{u *} is a
28590handy way to find the product of a vector or matrix of numbers.
28591@xref{Statistical Operations}. Another approach would be to use
28592an explicit column reduction command, @kbd{V R : *}.
28593
28594@node Yanking Into Buffers, X Cut and Paste, Grabbing From Buffers, Kill and Yank
28595@section Yanking into Other Buffers
28596
28597@noindent
28598@kindex y
28599@pindex calc-copy-to-buffer
28600The plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number
28601at the top of the stack into the most recently used normal editing buffer.
28602(More specifically, this is the most recently used buffer which is displayed
28603in a window and whose name does not begin with @samp{*}. If there is no
28604such buffer, this is the most recently used buffer except for Calculator
28605and Calc Trail buffers.) The number is inserted exactly as it appears and
28606without a newline. (If line-numbering is enabled, the line number is
28607normally not included.) The number is @emph{not} removed from the stack.
28608
28609With a prefix argument, @kbd{y} inserts several numbers, one per line.
28610A positive argument inserts the specified number of values from the top
28611of the stack. A negative argument inserts the @cite{n}th value from the
28612top of the stack. An argument of zero inserts the entire stack. Note
28613that @kbd{y} with an argument of 1 is slightly different from @kbd{y}
28614with no argument; the former always copies full lines, whereas the
28615latter strips off the trailing newline.
28616
28617With a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the
28618region in the other buffer with the yanked text, then quits the
28619Calculator, leaving you in that buffer. A typical use would be to use
28620@kbd{M-# g} to read a region of data into the Calculator, operate on the
28621data to produce a new matrix, then type @kbd{C-u y} to replace the
28622original data with the new data. One might wish to alter the matrix
28623display style (@pxref{Vector and Matrix Formats}) or change the current
28624display language (@pxref{Language Modes}) before doing this. Also, note
28625that this command replaces a linear region of text (as grabbed by
28626@kbd{M-# g}), not a rectangle (as grabbed by @kbd{M-# r}).@refill
28627
28628If the editing buffer is in overwrite (as opposed to insert) mode,
28629and the @kbd{C-u} prefix was not used, then the yanked number will
28630overwrite the characters following point rather than being inserted
28631before those characters. The usual conventions of overwrite mode
28632are observed; for example, characters will be inserted at the end of
28633a line rather than overflowing onto the next line. Yanking a multi-line
28634object such as a matrix in overwrite mode overwrites the next @var{n}
28635lines in the buffer, lengthening or shortening each line as necessary.
28636Finally, if the thing being yanked is a simple integer or floating-point
28637number (like @samp{-1.2345e-3}) and the characters following point also
28638make up such a number, then Calc will replace that number with the new
28639number, lengthening or shortening as necessary. The concept of
28640``overwrite mode'' has thus been generalized from overwriting characters
28641to overwriting one complete number with another.
28642
28643@kindex M-# y
28644The @kbd{M-# y} key sequence is equivalent to @kbd{y} except that
28645it can be typed anywhere, not just in Calc. This provides an easy
28646way to guarantee that Calc knows which editing buffer you want to use!
28647
28648@node X Cut and Paste, , Yanking Into Buffers, Kill and Yank
28649@section X Cut and Paste
28650
28651@noindent
28652If you are using Emacs with the X window system, there is an easier
28653way to move small amounts of data into and out of the calculator:
28654Use the mouse-oriented cut and paste facilities of X.
28655
28656The default bindings for a three-button mouse cause the left button
28657to move the Emacs cursor to the given place, the right button to
28658select the text between the cursor and the clicked location, and
28659the middle button to yank the selection into the buffer at the
28660clicked location. So, if you have a Calc window and an editing
28661window on your Emacs screen, you can use left-click/right-click
28662to select a number, vector, or formula from one window, then
28663middle-click to paste that value into the other window. When you
28664paste text into the Calc window, Calc interprets it as an algebraic
28665entry. It doesn't matter where you click in the Calc window; the
28666new value is always pushed onto the top of the stack.
28667
28668The @code{xterm} program that is typically used for general-purpose
28669shell windows in X interprets the mouse buttons in the same way.
28670So you can use the mouse to move data between Calc and any other
28671Unix program. One nice feature of @code{xterm} is that a double
28672left-click selects one word, and a triple left-click selects a
28673whole line. So you can usually transfer a single number into Calc
28674just by double-clicking on it in the shell, then middle-clicking
28675in the Calc window.
28676
28677@node Keypad Mode, Embedded Mode, Kill and Yank, Introduction
28678@chapter ``Keypad'' Mode
28679
28680@noindent
28681@kindex M-# k
28682@pindex calc-keypad
28683The @kbd{M-# k} (@code{calc-keypad}) command starts the Calculator
28684and displays a picture of a calculator-style keypad. If you are using
28685the X window system, you can click on any of the ``keys'' in the
28686keypad using the left mouse button to operate the calculator.
28687The original window remains the selected window; in keypad mode
28688you can type in your file while simultaneously performing
28689calculations with the mouse.
28690
28691@pindex full-calc-keypad
28692If you have used @kbd{M-# b} first, @kbd{M-# k} instead invokes
28693the @code{full-calc-keypad} command, which takes over the whole
28694Emacs screen and displays the keypad, the Calc stack, and the Calc
28695trail all at once. This mode would normally be used when running
28696Calc standalone (@pxref{Standalone Operation}).
28697
28698If you aren't using the X window system, you must switch into
28699the @samp{*Calc Keypad*} window, place the cursor on the desired
28700``key,'' and type @key{SPC} or @key{RET}. If you think this
28701is easier than using Calc normally, go right ahead.
28702
28703Calc commands are more or less the same in keypad mode. Certain
28704keypad keys differ slightly from the corresponding normal Calc
28705keystrokes; all such deviations are described below.
28706
28707Keypad Mode includes many more commands than will fit on the keypad
28708at once. Click the right mouse button [@code{calc-keypad-menu}]
28709to switch to the next menu. The bottom five rows of the keypad
28710stay the same; the top three rows change to a new set of commands.
28711To return to earlier menus, click the middle mouse button
28712[@code{calc-keypad-menu-back}] or simply advance through the menus
28713until you wrap around. Typing @key{TAB} inside the keypad window
28714is equivalent to clicking the right mouse button there.
28715
28716You can always click the @key{EXEC} button and type any normal
28717Calc key sequence. This is equivalent to switching into the
28718Calc buffer, typing the keys, then switching back to your
28719original buffer.
28720
28721@menu
28722* Keypad Main Menu::
28723* Keypad Functions Menu::
28724* Keypad Binary Menu::
28725* Keypad Vectors Menu::
28726* Keypad Modes Menu::
28727@end menu
28728
28729@node Keypad Main Menu, Keypad Functions Menu, Keypad Mode, Keypad Mode
28730@section Main Menu
28731
28732@group
28733@smallexample
28734|----+-----Calc 2.00-----+----1
28735|FLR |CEIL|RND |TRNC|CLN2|FLT |
28736|----+----+----+----+----+----|
28737| LN |EXP | |ABS |IDIV|MOD |
28738|----+----+----+----+----+----|
28739|SIN |COS |TAN |SQRT|y^x |1/x |
28740|----+----+----+----+----+----|
28741| ENTER |+/- |EEX |UNDO| <- |
28742|-----+---+-+--+--+-+---++----|
28743| INV | 7 | 8 | 9 | / |
28744|-----+-----+-----+-----+-----|
28745| HYP | 4 | 5 | 6 | * |
28746|-----+-----+-----+-----+-----|
28747|EXEC | 1 | 2 | 3 | - |
28748|-----+-----+-----+-----+-----|
28749| OFF | 0 | . | PI | + |
28750|-----+-----+-----+-----+-----+
28751@end smallexample
28752@end group
28753
28754@noindent
28755This is the menu that appears the first time you start Keypad Mode.
28756It will show up in a vertical window on the right side of your screen.
28757Above this menu is the traditional Calc stack display. On a 24-line
28758screen you will be able to see the top three stack entries.
28759
28760The ten digit keys, decimal point, and @key{EEX} key are used for
28761entering numbers in the obvious way. @key{EEX} begins entry of an
28762exponent in scientific notation. Just as with regular Calc, the
28763number is pushed onto the stack as soon as you press @key{ENTER}
28764or any other function key.
28765
28766The @key{+/-} key corresponds to normal Calc's @kbd{n} key. During
28767numeric entry it changes the sign of the number or of the exponent.
28768At other times it changes the sign of the number on the top of the
28769stack.
28770
28771The @key{INV} and @key{HYP} keys modify other keys. As well as
28772having the effects described elsewhere in this manual, Keypad Mode
28773defines several other ``inverse'' operations. These are described
28774below and in the following sections.
28775
28776The @key{ENTER} key finishes the current numeric entry, or otherwise
28777duplicates the top entry on the stack.
28778
28779The @key{UNDO} key undoes the most recent Calc operation.
28780@kbd{INV UNDO} is the ``redo'' command, and @kbd{HYP UNDO} is
28781``last arguments'' (@kbd{M-RET}).
28782
28783The @key{<-} key acts as a ``backspace'' during numeric entry.
28784At other times it removes the top stack entry. @kbd{INV <-}
28785clears the entire stack. @kbd{HYP <-} takes an integer from
28786the stack, then removes that many additional stack elements.
28787
28788The @key{EXEC} key prompts you to enter any keystroke sequence
28789that would normally work in Calc mode. This can include a
28790numeric prefix if you wish. It is also possible simply to
28791switch into the Calc window and type commands in it; there is
28792nothing ``magic'' about this window when Keypad Mode is active.
28793
28794The other keys in this display perform their obvious calculator
28795functions. @key{CLN2} rounds the top-of-stack by temporarily
28796reducing the precision by 2 digits. @key{FLT} converts an
28797integer or fraction on the top of the stack to floating-point.
28798
28799The @key{INV} and @key{HYP} keys combined with several of these keys
28800give you access to some common functions even if the appropriate menu
28801is not displayed. Obviously you don't need to learn these keys
28802unless you find yourself wasting time switching among the menus.
28803
28804@table @kbd
28805@item INV +/-
28806is the same as @key{1/x}.
28807@item INV +
28808is the same as @key{SQRT}.
28809@item INV -
28810is the same as @key{CONJ}.
28811@item INV *
28812is the same as @key{y^x}.
28813@item INV /
28814is the same as @key{INV y^x} (the @cite{x}th root of @cite{y}).
28815@item HYP/INV 1
28816are the same as @key{SIN} / @kbd{INV SIN}.
28817@item HYP/INV 2
28818are the same as @key{COS} / @kbd{INV COS}.
28819@item HYP/INV 3
28820are the same as @key{TAN} / @kbd{INV TAN}.
28821@item INV/HYP 4
28822are the same as @key{LN} / @kbd{HYP LN}.
28823@item INV/HYP 5
28824are the same as @key{EXP} / @kbd{HYP EXP}.
28825@item INV 6
28826is the same as @key{ABS}.
28827@item INV 7
28828is the same as @key{RND} (@code{calc-round}).
28829@item INV 8
28830is the same as @key{CLN2}.
28831@item INV 9
28832is the same as @key{FLT} (@code{calc-float}).
28833@item INV 0
28834is the same as @key{IMAG}.
28835@item INV .
28836is the same as @key{PREC}.
28837@item INV ENTER
28838is the same as @key{SWAP}.
28839@item HYP ENTER
28840is the same as @key{RLL3}.
28841@item INV HYP ENTER
28842is the same as @key{OVER}.
28843@item HYP +/-
28844packs the top two stack entries as an error form.
28845@item HYP EEX
28846packs the top two stack entries as a modulo form.
28847@item INV EEX
28848creates an interval form; this removes an integer which is one
28849of 0 @samp{[]}, 1 @samp{[)}, 2 @samp{(]} or 3 @samp{()}, followed
28850by the two limits of the interval.
28851@end table
28852
28853The @kbd{OFF} key turns Calc off; typing @kbd{M-# k} or @kbd{M-# M-#}
28854again has the same effect. This is analogous to typing @kbd{q} or
28855hitting @kbd{M-# c} again in the normal calculator. If Calc is
28856running standalone (the @code{full-calc-keypad} command appeared in the
28857command line that started Emacs), then @kbd{OFF} is replaced with
28858@kbd{EXIT}; clicking on this actually exits Emacs itself.
28859
28860@node Keypad Functions Menu, Keypad Binary Menu, Keypad Main Menu, Keypad Mode
28861@section Functions Menu
28862
28863@group
28864@smallexample
28865|----+----+----+----+----+----2
28866|IGAM|BETA|IBET|ERF |BESJ|BESY|
28867|----+----+----+----+----+----|
28868|IMAG|CONJ| RE |ATN2|RAND|RAGN|
28869|----+----+----+----+----+----|
28870|GCD |FACT|DFCT|BNOM|PERM|NXTP|
28871|----+----+----+----+----+----|
28872@end smallexample
28873@end group
28874
28875@noindent
28876This menu provides various operations from the @kbd{f} and @kbd{k}
28877prefix keys.
28878
28879@key{IMAG} multiplies the number on the stack by the imaginary
28880number @cite{i = (0, 1)}.
28881
28882@key{RE} extracts the real part a complex number. @kbd{INV RE}
28883extracts the imaginary part.
28884
28885@key{RAND} takes a number from the top of the stack and computes
28886a random number greater than or equal to zero but less than that
28887number. (@xref{Random Numbers}.) @key{RAGN} is the ``random
28888again'' command; it computes another random number using the
28889same limit as last time.
28890
28891@key{INV GCD} computes the LCM (least common multiple) function.
28892
28893@key{INV FACT} is the gamma function. @c{$\Gamma(x) = (x-1)!$}
28894@cite{gamma(x) = (x-1)!}.
28895
28896@key{PERM} is the number-of-permutations function, which is on the
28897@kbd{H k c} key in normal Calc.
28898
28899@key{NXTP} finds the next prime after a number. @kbd{INV NXTP}
28900finds the previous prime.
28901
28902@node Keypad Binary Menu, Keypad Vectors Menu, Keypad Functions Menu, Keypad Mode
28903@section Binary Menu
28904
28905@group
28906@smallexample
28907|----+----+----+----+----+----3
28908|AND | OR |XOR |NOT |LSH |RSH |
28909|----+----+----+----+----+----|
28910|DEC |HEX |OCT |BIN |WSIZ|ARSH|
28911|----+----+----+----+----+----|
28912| A | B | C | D | E | F |
28913|----+----+----+----+----+----|
28914@end smallexample
28915@end group
28916
28917@noindent
28918The keys in this menu perform operations on binary integers.
28919Note that both logical and arithmetic right-shifts are provided.
28920@key{INV LSH} rotates one bit to the left.
28921
28922The ``difference'' function (normally on @kbd{b d}) is on @key{INV AND}.
28923The ``clip'' function (normally on @w{@kbd{b c}}) is on @key{INV NOT}.
28924
28925The @key{DEC}, @key{HEX}, @key{OCT}, and @key{BIN} keys select the
28926current radix for display and entry of numbers: Decimal, hexadecimal,
28927octal, or binary. The six letter keys @key{A} through @key{F} are used
28928for entering hexadecimal numbers.
28929
28930The @key{WSIZ} key displays the current word size for binary operations
28931and allows you to enter a new word size. You can respond to the prompt
28932using either the keyboard or the digits and @key{ENTER} from the keypad.
28933The initial word size is 32 bits.
28934
28935@node Keypad Vectors Menu, Keypad Modes Menu, Keypad Binary Menu, Keypad Mode
28936@section Vectors Menu
28937
28938@group
28939@smallexample
28940|----+----+----+----+----+----4
28941|SUM |PROD|MAX |MAP*|MAP^|MAP$|
28942|----+----+----+----+----+----|
28943|MINV|MDET|MTRN|IDNT|CRSS|"x" |
28944|----+----+----+----+----+----|
28945|PACK|UNPK|INDX|BLD |LEN |... |
28946|----+----+----+----+----+----|
28947@end smallexample
28948@end group
28949
28950@noindent
28951The keys in this menu operate on vectors and matrices.
28952
28953@key{PACK} removes an integer @var{n} from the top of the stack;
28954the next @var{n} stack elements are removed and packed into a vector,
28955which is replaced onto the stack. Thus the sequence
28956@kbd{1 ENTER 3 ENTER 5 ENTER 3 PACK} enters the vector
28957@samp{[1, 3, 5]} onto the stack. To enter a matrix, build each row
28958on the stack as a vector, then use a final @key{PACK} to collect the
28959rows into a matrix.
28960
28961@key{UNPK} unpacks the vector on the stack, pushing each of its
28962components separately.
28963
28964@key{INDX} removes an integer @var{n}, then builds a vector of
28965integers from 1 to @var{n}. @kbd{INV INDX} takes three numbers
28966from the stack: The vector size @var{n}, the starting number,
28967and the increment. @kbd{BLD} takes an integer @var{n} and any
28968value @var{x} and builds a vector of @var{n} copies of @var{x}.
28969
28970@key{IDNT} removes an integer @var{n}, then builds an @var{n}-by-@var{n}
28971identity matrix.
28972
28973@key{LEN} replaces a vector by its length, an integer.
28974
28975@key{...} turns on or off ``abbreviated'' display mode for large vectors.
28976
28977@key{MINV}, @key{MDET}, @key{MTRN}, and @key{CROSS} are the matrix
28978inverse, determinant, and transpose, and vector cross product.
28979
28980@key{SUM} replaces a vector by the sum of its elements. It is
28981equivalent to @kbd{u +} in normal Calc (@pxref{Statistical Operations}).
28982@key{PROD} computes the product of the elements of a vector, and
28983@key{MAX} computes the maximum of all the elements of a vector.
28984
28985@key{INV SUM} computes the alternating sum of the first element
28986minus the second, plus the third, minus the fourth, and so on.
28987@key{INV MAX} computes the minimum of the vector elements.
28988
28989@key{HYP SUM} computes the mean of the vector elements.
28990@key{HYP PROD} computes the sample standard deviation.
28991@key{HYP MAX} computes the median.
28992
28993@key{MAP*} multiplies two vectors elementwise. It is equivalent
28994to the @kbd{V M *} command. @key{MAP^} computes powers elementwise.
28995The arguments must be vectors of equal length, or one must be a vector
28996and the other must be a plain number. For example, @kbd{2 MAP^} squares
28997all the elements of a vector.
28998
28999@key{MAP$} maps the formula on the top of the stack across the
29000vector in the second-to-top position. If the formula contains
29001several variables, Calc takes that many vectors starting at the
29002second-to-top position and matches them to the variables in
29003alphabetical order. The result is a vector of the same size as
29004the input vectors, whose elements are the formula evaluated with
29005the variables set to the various sets of numbers in those vectors.
29006For example, you could simulate @key{MAP^} using @key{MAP$} with
29007the formula @samp{x^y}.
29008
29009The @kbd{"x"} key pushes the variable name @cite{x} onto the
29010stack. To build the formula @cite{x^2 + 6}, you would use the
29011key sequence @kbd{"x" 2 y^x 6 +}. This formula would then be
29012suitable for use with the @key{MAP$} key described above.
29013With @key{INV}, @key{HYP}, or @key{INV} and @key{HYP}, the
29014@kbd{"x"} key pushes the variable names @cite{y}, @cite{z}, and
29015@cite{t}, respectively.
29016
29017@node Keypad Modes Menu, , Keypad Vectors Menu, Keypad Mode
29018@section Modes Menu
29019
29020@group
29021@smallexample
29022|----+----+----+----+----+----5
29023|FLT |FIX |SCI |ENG |GRP | |
29024|----+----+----+----+----+----|
29025|RAD |DEG |FRAC|POLR|SYMB|PREC|
29026|----+----+----+----+----+----|
29027|SWAP|RLL3|RLL4|OVER|STO |RCL |
29028|----+----+----+----+----+----|
29029@end smallexample
29030@end group
29031
29032@noindent
29033The keys in this menu manipulate modes, variables, and the stack.
29034
29035The @key{FLT}, @key{FIX}, @key{SCI}, and @key{ENG} keys select
29036floating-point, fixed-point, scientific, or engineering notation.
29037@key{FIX} displays two digits after the decimal by default; the
29038others display full precision. With the @key{INV} prefix, these
29039keys pop a number-of-digits argument from the stack.
29040
29041The @key{GRP} key turns grouping of digits with commas on or off.
29042@kbd{INV GRP} enables grouping to the right of the decimal point as
29043well as to the left.
29044
29045The @key{RAD} and @key{DEG} keys switch between radians and degrees
29046for trigonometric functions.
29047
29048The @key{FRAC} key turns Fraction mode on or off. This affects
29049whether commands like @kbd{/} with integer arguments produce
29050fractional or floating-point results.
29051
29052The @key{POLR} key turns Polar mode on or off, determining whether
29053polar or rectangular complex numbers are used by default.
29054
29055The @key{SYMB} key turns Symbolic mode on or off, in which
29056operations that would produce inexact floating-point results
29057are left unevaluated as algebraic formulas.
29058
29059The @key{PREC} key selects the current precision. Answer with
29060the keyboard or with the keypad digit and @key{ENTER} keys.
29061
29062The @key{SWAP} key exchanges the top two stack elements.
29063The @key{RLL3} key rotates the top three stack elements upwards.
29064The @key{RLL4} key rotates the top four stack elements upwards.
29065The @key{OVER} key duplicates the second-to-top stack element.
29066
29067The @key{STO} and @key{RCL} keys are analogous to @kbd{s t} and
29068@kbd{s r} in regular Calc. @xref{Store and Recall}. Click the
29069@key{STO} or @key{RCL} key, then one of the ten digits. (Named
29070variables are not available in Keypad Mode.) You can also use,
29071for example, @kbd{STO + 3} to add to register 3.
29072
29073@node Embedded Mode, Programming, Keypad Mode, Top
29074@chapter Embedded Mode
29075
29076@noindent
29077Embedded Mode in Calc provides an alternative to copying numbers
29078and formulas back and forth between editing buffers and the Calc
29079stack. In Embedded Mode, your editing buffer becomes temporarily
29080linked to the stack and this copying is taken care of automatically.
29081
29082@menu
29083* Basic Embedded Mode::
29084* More About Embedded Mode::
29085* Assignments in Embedded Mode::
29086* Mode Settings in Embedded Mode::
29087* Customizing Embedded Mode::
29088@end menu
29089
29090@node Basic Embedded Mode, More About Embedded Mode, Embedded Mode, Embedded Mode
29091@section Basic Embedded Mode
29092
29093@noindent
29094@kindex M-# e
29095@pindex calc-embedded
29096To enter Embedded mode, position the Emacs point (cursor) on a
29097formula in any buffer and press @kbd{M-# e} (@code{calc-embedded}).
29098Note that @kbd{M-# e} is not to be used in the Calc stack buffer
29099like most Calc commands, but rather in regular editing buffers that
29100are visiting your own files.
29101
29102Calc normally scans backward and forward in the buffer for the
29103nearest opening and closing @dfn{formula delimiters}. The simplest
29104delimiters are blank lines. Other delimiters that Embedded Mode
29105understands are:
29106
29107@enumerate
29108@item
29109The @TeX{} and La@TeX{} math delimiters @samp{$ $}, @samp{$$ $$},
29110@samp{\[ \]}, and @samp{\( \)};
29111@item
29112Lines beginning with @samp{\begin} and @samp{\end};
29113@item
29114Lines beginning with @samp{@@} (Texinfo delimiters).
29115@item
29116Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
29117@item
29118Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
29119@end enumerate
29120
29121@xref{Customizing Embedded Mode}, to see how to make Calc recognize
29122your own favorite delimiters. Delimiters like @samp{$ $} can appear
29123on their own separate lines or in-line with the formula.
29124
29125If you give a positive or negative numeric prefix argument, Calc
29126instead uses the current point as one end of the formula, and moves
29127forward or backward (respectively) by that many lines to find the
29128other end. Explicit delimiters are not necessary in this case.
29129
29130With a prefix argument of zero, Calc uses the current region
29131(delimited by point and mark) instead of formula delimiters.
29132
29133@kindex M-# w
29134@pindex calc-embedded-word
29135With a prefix argument of @kbd{C-u} only, Calc scans for the first
29136non-numeric character (i.e., the first character that is not a
29137digit, sign, decimal point, or upper- or lower-case @samp{e})
29138forward and backward to delimit the formula. @kbd{M-# w}
29139(@code{calc-embedded-word}) is equivalent to @kbd{C-u M-# e}.
29140
29141When you enable Embedded mode for a formula, Calc reads the text
29142between the delimiters and tries to interpret it as a Calc formula.
29143It's best if the current Calc language mode is correct for the
29144formula, but Calc can generally identify @TeX{} formulas and
29145Big-style formulas even if the language mode is wrong. If Calc
29146can't make sense of the formula, it beeps and refuses to enter
29147Embedded mode. But if the current language is wrong, Calc can
29148sometimes parse the formula successfully (but incorrectly);
29149for example, the C expression @samp{atan(a[1])} can be parsed
29150in Normal language mode, but the @code{atan} won't correspond to
29151the built-in @code{arctan} function, and the @samp{a[1]} will be
29152interpreted as @samp{a} times the vector @samp{[1]}!
29153
29154If you press @kbd{M-# e} or @kbd{M-# w} to activate an embedded
29155formula which is blank, say with the cursor on the space between
29156the two delimiters @samp{$ $}, Calc will immediately prompt for
29157an algebraic entry.
29158
29159Only one formula in one buffer can be enabled at a time. If you
29160move to another area of the current buffer and give Calc commands,
29161Calc turns Embedded mode off for the old formula and then tries
29162to restart Embedded mode at the new position. Other buffers are
29163not affected by Embedded mode.
29164
29165When Embedded mode begins, Calc pushes the current formula onto
29166the stack. No Calc stack window is created; however, Calc copies
29167the top-of-stack position into the original buffer at all times.
29168You can create a Calc window by hand with @kbd{M-# o} if you
29169find you need to see the entire stack.
29170
29171For example, typing @kbd{M-# e} while somewhere in the formula
29172@samp{n>2} in the following line enables Embedded mode on that
29173inequality:
29174
29175@example
29176We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
29177@end example
29178
29179@noindent
29180The formula @cite{n>2} will be pushed onto the Calc stack, and
29181the top of stack will be copied back into the editing buffer.
29182This means that spaces will appear around the @samp{>} symbol
29183to match Calc's usual display style:
29184
29185@example
29186We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
29187@end example
29188
29189@noindent
29190No spaces have appeared around the @samp{+} sign because it's
29191in a different formula, one which we have not yet touched with
29192Embedded mode.
29193
29194Now that Embedded mode is enabled, keys you type in this buffer
29195are interpreted as Calc commands. At this point we might use
29196the ``commute'' command @kbd{j C} to reverse the inequality.
29197This is a selection-based command for which we first need to
29198move the cursor onto the operator (@samp{>} in this case) that
29199needs to be commuted.
29200
29201@example
29202We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
29203@end example
29204
29205The @kbd{M-# o} command is a useful way to open a Calc window
29206without actually selecting that window. Giving this command
29207verifies that @samp{2 < n} is also on the Calc stack. Typing
29208@kbd{17 RET} would produce:
29209
29210@example
29211We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
29212@end example
29213
29214@noindent
29215with @samp{2 < n} and @samp{17} on the stack; typing @key{TAB}
29216at this point will exchange the two stack values and restore
29217@samp{2 < n} to the embedded formula. Even though you can't
29218normally see the stack in Embedded mode, it is still there and
29219it still operates in the same way. But, as with old-fashioned
29220RPN calculators, you can only see the value at the top of the
29221stack at any given time (unless you use @kbd{M-# o}).
29222
29223Typing @kbd{M-# e} again turns Embedded mode off. The Calc
29224window reveals that the formula @w{@samp{2 < n}} is automatically
29225removed from the stack, but the @samp{17} is not. Entering
29226Embedded mode always pushes one thing onto the stack, and
29227leaving Embedded mode always removes one thing. Anything else
29228that happens on the stack is entirely your business as far as
29229Embedded mode is concerned.
29230
29231If you press @kbd{M-# e} in the wrong place by accident, it is
29232possible that Calc will be able to parse the nearby text as a
29233formula and will mangle that text in an attempt to redisplay it
29234``properly'' in the current language mode. If this happens,
29235press @kbd{M-# e} again to exit Embedded mode, then give the
29236regular Emacs ``undo'' command (@kbd{C-_} or @kbd{C-x u}) to put
29237the text back the way it was before Calc edited it. Note that Calc's
29238own Undo command (typed before you turn Embedded mode back off)
29239will not do you any good, because as far as Calc is concerned
29240you haven't done anything with this formula yet.
29241
29242@node More About Embedded Mode, Assignments in Embedded Mode, Basic Embedded Mode, Embedded Mode
29243@section More About Embedded Mode
29244
29245@noindent
29246When Embedded mode ``activates'' a formula, i.e., when it examines
29247the formula for the first time since the buffer was created or
29248loaded, Calc tries to sense the language in which the formula was
29249written. If the formula contains any @TeX{}-like @samp{\} sequences,
29250it is parsed (i.e., read) in @TeX{} mode. If the formula appears to
29251be written in multi-line Big mode, it is parsed in Big mode. Otherwise,
29252it is parsed according to the current language mode.
29253
29254Note that Calc does not change the current language mode according
29255to what it finds. Even though it can read a @TeX{} formula when
29256not in @TeX{} mode, it will immediately rewrite this formula using
29257whatever language mode is in effect. You must then type @kbd{d T}
29258to switch Calc permanently into @TeX{} mode if that is what you
29259desire.
29260
29261@tex
29262\bigskip
29263@end tex
29264
29265@kindex d p
29266@pindex calc-show-plain
29267Calc's parser is unable to read certain kinds of formulas. For
29268example, with @kbd{v ]} (@code{calc-matrix-brackets}) you can
29269specify matrix display styles which the parser is unable to
29270recognize as matrices. The @kbd{d p} (@code{calc-show-plain})
29271command turns on a mode in which a ``plain'' version of a
29272formula is placed in front of the fully-formatted version.
29273When Calc reads a formula that has such a plain version in
29274front, it reads the plain version and ignores the formatted
29275version.
29276
29277Plain formulas are preceded and followed by @samp{%%%} signs
29278by default. This notation has the advantage that the @samp{%}
29279character begins a comment in @TeX{}, so if your formula is
29280embedded in a @TeX{} document its plain version will be
29281invisible in the final printed copy. @xref{Customizing
29282Embedded Mode}, to see how to change the ``plain'' formula
29283delimiters, say to something that @dfn{eqn} or some other
29284formatter will treat as a comment.
29285
29286There are several notations which Calc's parser for ``big''
29287formatted formulas can't yet recognize. In particular, it can't
29288read the large symbols for @code{sum}, @code{prod}, and @code{integ},
29289and it can't handle @samp{=>} with the righthand argument omitted.
29290Also, Calc won't recognize special formats you have defined with
29291the @kbd{Z C} command (@pxref{User-Defined Compositions}). In
29292these cases it is important to use ``plain'' mode to make sure
29293Calc will be able to read your formula later.
29294
29295Another example where ``plain'' mode is important is if you have
29296specified a float mode with few digits of precision. Normally
29297any digits that are computed but not displayed will simply be
29298lost when you save and re-load your embedded buffer, but ``plain''
29299mode allows you to make sure that the complete number is present
29300in the file as well as the rounded-down number.
29301
29302@tex
29303\bigskip
29304@end tex
29305
29306Embedded buffers remember active formulas for as long as they
29307exist in Emacs memory. Suppose you have an embedded formula
29308which is @c{$\pi$}
29309@cite{pi} to the normal 12 decimal places, and then
29310type @w{@kbd{C-u 5 d n}} to display only five decimal places.
29311If you then type @kbd{d n}, all 12 places reappear because the
29312full number is still there on the Calc stack. More surprisingly,
29313even if you exit Embedded mode and later re-enter it for that
29314formula, typing @kbd{d n} will restore all 12 places because
29315each buffer remembers all its active formulas. However, if you
29316save the buffer in a file and reload it in a new Emacs session,
29317all non-displayed digits will have been lost unless you used
29318``plain'' mode.
29319
29320@tex
29321\bigskip
29322@end tex
29323
29324In some applications of Embedded mode, you will want to have a
29325sequence of copies of a formula that show its evolution as you
29326work on it. For example, you might want to have a sequence
29327like this in your file (elaborating here on the example from
29328the ``Getting Started'' chapter):
29329
29330@smallexample
29331The derivative of
29332
29333 ln(ln(x))
29334
29335is
29336
29337 @r{(the derivative of }ln(ln(x))@r{)}
29338
29339whose value at x = 2 is
29340
29341 @r{(the value)}
29342
29343and at x = 3 is
29344
29345 @r{(the value)}
29346@end smallexample
29347
29348@kindex M-# d
29349@pindex calc-embedded-duplicate
29350The @kbd{M-# d} (@code{calc-embedded-duplicate}) command is a
29351handy way to make sequences like this. If you type @kbd{M-# d},
29352the formula under the cursor (which may or may not have Embedded
29353mode enabled for it at the time) is copied immediately below and
29354Embedded mode is then enabled for that copy.
29355
29356For this example, you would start with just
29357
29358@smallexample
29359The derivative of
29360
29361 ln(ln(x))
29362@end smallexample
29363
29364@noindent
29365and press @kbd{M-# d} with the cursor on this formula. The result
29366is
29367
29368@smallexample
29369The derivative of
29370
29371 ln(ln(x))
29372
29373
29374 ln(ln(x))
29375@end smallexample
29376
29377@noindent
29378with the second copy of the formula enabled in Embedded mode.
29379You can now press @kbd{a d x RET} to take the derivative, and
29380@kbd{M-# d M-# d} to make two more copies of the derivative.
29381To complete the computations, type @kbd{3 s l x RET} to evaluate
29382the last formula, then move up to the second-to-last formula
29383and type @kbd{2 s l x RET}.
29384
29385Finally, you would want to press @kbd{M-# e} to exit Embedded
29386mode, then go up and insert the necessary text in between the
29387various formulas and numbers.
29388
29389@tex
29390\bigskip
29391@end tex
29392
29393@kindex M-# f
29394@kindex M-# '
29395@pindex calc-embedded-new-formula
29396The @kbd{M-# f} (@code{calc-embedded-new-formula}) command
29397creates a new embedded formula at the current point. It inserts
29398some default delimiters, which are usually just blank lines,
29399and then does an algebraic entry to get the formula (which is
29400then enabled for Embedded mode). This is just shorthand for
29401typing the delimiters yourself, positioning the cursor between
29402the new delimiters, and pressing @kbd{M-# e}. The key sequence
29403@kbd{M-# '} is equivalent to @kbd{M-# f}.
29404
29405@kindex M-# n
29406@kindex M-# p
29407@pindex calc-embedded-next
29408@pindex calc-embedded-previous
29409The @kbd{M-# n} (@code{calc-embedded-next}) and @kbd{M-# p}
29410(@code{calc-embedded-previous}) commands move the cursor to the
29411next or previous active embedded formula in the buffer. They
29412can take positive or negative prefix arguments to move by several
29413formulas. Note that these commands do not actually examine the
29414text of the buffer looking for formulas; they only see formulas
29415which have previously been activated in Embedded mode. In fact,
29416@kbd{M-# n} and @kbd{M-# p} are a useful way to tell which
29417embedded formulas are currently active. Also, note that these
29418commands do not enable Embedded mode on the next or previous
29419formula, they just move the cursor. (By the way, @kbd{M-# n} is
29420not as awkward to type as it may seem, because @kbd{M-#} ignores
29421Shift and Meta on the second keystroke: @kbd{M-# M-N} can be typed
29422by holding down Shift and Meta and alternately typing two keys.)
29423
29424@kindex M-# `
29425@pindex calc-embedded-edit
29426The @kbd{M-# `} (@code{calc-embedded-edit}) command edits the
29427embedded formula at the current point as if by @kbd{`} (@code{calc-edit}).
29428Embedded mode does not have to be enabled for this to work. Press
29429@kbd{M-# M-#} to finish the edit, or @kbd{M-# x} to cancel.
29430
29431@node Assignments in Embedded Mode, Mode Settings in Embedded Mode, More About Embedded Mode, Embedded Mode
29432@section Assignments in Embedded Mode
29433
29434@noindent
29435The @samp{:=} (assignment) and @samp{=>} (``evaluates-to'') operators
29436are especially useful in Embedded mode. They allow you to make
29437a definition in one formula, then refer to that definition in
29438other formulas embedded in the same buffer.
29439
29440An embedded formula which is an assignment to a variable, as in
29441
29442@example
29443foo := 5
29444@end example
29445
29446@noindent
29447records @cite{5} as the stored value of @code{foo} for the
29448purposes of Embedded mode operations in the current buffer. It
29449does @emph{not} actually store @cite{5} as the ``global'' value
29450of @code{foo}, however. Regular Calc operations, and Embedded
29451formulas in other buffers, will not see this assignment.
29452
29453One way to use this assigned value is simply to create an
29454Embedded formula elsewhere that refers to @code{foo}, and to press
29455@kbd{=} in that formula. However, this permanently replaces the
29456@code{foo} in the formula with its current value. More interesting
29457is to use @samp{=>} elsewhere:
29458
29459@example
29460foo + 7 => 12
29461@end example
29462
29463@xref{Evaluates-To Operator}, for a general discussion of @samp{=>}.
29464
29465If you move back and change the assignment to @code{foo}, any
29466@samp{=>} formulas which refer to it are automatically updated.
29467
29468@example
29469foo := 17
29470
29471foo + 7 => 24
29472@end example
29473
29474The obvious question then is, @emph{how} can one easily change the
29475assignment to @code{foo}? If you simply select the formula in
29476Embedded mode and type 17, the assignment itself will be replaced
29477by the 17. The effect on the other formula will be that the
29478variable @code{foo} becomes unassigned:
29479
29480@example
2948117
29482
29483foo + 7 => foo + 7
29484@end example
29485
29486The right thing to do is first to use a selection command (@kbd{j 2}
29487will do the trick) to select the righthand side of the assignment.
29488Then, @kbd{17 TAB DEL} will swap the 17 into place (@pxref{Selecting
29489Subformulas}, to see how this works).
29490
29491@kindex M-# j
29492@pindex calc-embedded-select
29493The @kbd{M-# j} (@code{calc-embedded-select}) command provides an
29494easy way to operate on assigments. It is just like @kbd{M-# e},
29495except that if the enabled formula is an assignment, it uses
29496@kbd{j 2} to select the righthand side. If the enabled formula
29497is an evaluates-to, it uses @kbd{j 1} to select the lefthand side.
29498A formula can also be a combination of both:
29499
29500@example
29501bar := foo + 3 => 20
29502@end example
29503
29504@noindent
29505in which case @kbd{M-# j} will select the middle part (@samp{foo + 3}).
29506
29507The formula is automatically deselected when you leave Embedded
29508mode.
29509
29510@kindex M-# u
29511@kindex M-# =
29512@pindex calc-embedded-update
29513Another way to change the assignment to @code{foo} would simply be
29514to edit the number using regular Emacs editing rather than Embedded
29515mode. Then, we have to find a way to get Embedded mode to notice
29516the change. The @kbd{M-# u} or @kbd{M-# =}
29517(@code{calc-embedded-update-formula}) command is a convenient way
29518to do this.@refill
29519
29520@example
29521foo := 6
29522
29523foo + 7 => 13
29524@end example
29525
29526Pressing @kbd{M-# u} is much like pressing @kbd{M-# e = M-# e}, that
29527is, temporarily enabling Embedded mode for the formula under the
29528cursor and then evaluating it with @kbd{=}. But @kbd{M-# u} does
29529not actually use @kbd{M-# e}, and in fact another formula somewhere
29530else can be enabled in Embedded mode while you use @kbd{M-# u} and
29531that formula will not be disturbed.
29532
29533With a numeric prefix argument, @kbd{M-# u} updates all active
29534@samp{=>} formulas in the buffer. Formulas which have not yet
29535been activated in Embedded mode, and formulas which do not have
29536@samp{=>} as their top-level operator, are not affected by this.
29537(This is useful only if you have used @kbd{m C}; see below.)
29538
29539With a plain @kbd{C-u} prefix, @kbd{C-u M-# u} updates only in the
29540region between mark and point rather than in the whole buffer.
29541
29542@kbd{M-# u} is also a handy way to activate a formula, such as an
29543@samp{=>} formula that has freshly been typed in or loaded from a
29544file.
29545
29546@kindex M-# a
29547@pindex calc-embedded-activate
29548The @kbd{M-# a} (@code{calc-embedded-activate}) command scans
29549through the current buffer and activates all embedded formulas
29550that contain @samp{:=} or @samp{=>} symbols. This does not mean
29551that Embedded mode is actually turned on, but only that the
29552formulas' positions are registered with Embedded mode so that
29553the @samp{=>} values can be properly updated as assignments are
29554changed.
29555
29556It is a good idea to type @kbd{M-# a} right after loading a file
29557that uses embedded @samp{=>} operators. Emacs includes a nifty
29558``buffer-local variables'' feature that you can use to do this
29559automatically. The idea is to place near the end of your file
29560a few lines that look like this:
29561
29562@example
29563--- Local Variables: ---
29564--- eval:(calc-embedded-activate) ---
29565--- End: ---
29566@end example
29567
29568@noindent
29569where the leading and trailing @samp{---} can be replaced by
29570any suitable strings (which must be the same on all three lines)
29571or omitted altogether; in a @TeX{} file, @samp{%} would be a good
29572leading string and no trailing string would be necessary. In a
29573C program, @samp{/*} and @samp{*/} would be good leading and
29574trailing strings.
29575
29576When Emacs loads a file into memory, it checks for a Local Variables
29577section like this one at the end of the file. If it finds this
29578section, it does the specified things (in this case, running
29579@kbd{M-# a} automatically) before editing of the file begins.
29580The Local Variables section must be within 3000 characters of the
29581end of the file for Emacs to find it, and it must be in the last
29582page of the file if the file has any page separators.
29583@xref{File Variables, , Local Variables in Files, emacs, the
29584Emacs manual}.
29585
29586Note that @kbd{M-# a} does not update the formulas it finds.
29587To do this, type, say, @kbd{M-1 M-# u} after @w{@kbd{M-# a}}.
29588Generally this should not be a problem, though, because the
29589formulas will have been up-to-date already when the file was
29590saved.
29591
29592Normally, @kbd{M-# a} activates all the formulas it finds, but
29593any previous active formulas remain active as well. With a
29594positive numeric prefix argument, @kbd{M-# a} first deactivates
29595all current active formulas, then actives the ones it finds in
29596its scan of the buffer. With a negative prefix argument,
29597@kbd{M-# a} simply deactivates all formulas.
29598
29599Embedded mode has two symbols, @samp{Active} and @samp{~Active},
29600which it puts next to the major mode name in a buffer's mode line.
29601It puts @samp{Active} if it has reason to believe that all
29602formulas in the buffer are active, because you have typed @kbd{M-# a}
29603and Calc has not since had to deactivate any formulas (which can
29604happen if Calc goes to update an @samp{=>} formula somewhere because
29605a variable changed, and finds that the formula is no longer there
29606due to some kind of editing outside of Embedded mode). Calc puts
29607@samp{~Active} in the mode line if some, but probably not all,
29608formulas in the buffer are active. This happens if you activate
29609a few formulas one at a time but never use @kbd{M-# a}, or if you
29610used @kbd{M-# a} but then Calc had to deactivate a formula
29611because it lost track of it. If neither of these symbols appears
29612in the mode line, no embedded formulas are active in the buffer
29613(e.g., before Embedded mode has been used, or after a @kbd{M-- M-# a}).
29614
29615Embedded formulas can refer to assignments both before and after them
29616in the buffer. If there are several assignments to a variable, the
29617nearest preceding assignment is used if there is one, otherwise the
29618following assignment is used.
29619
29620@example
29621x => 1
29622
29623x := 1
29624
29625x => 1
29626
29627x := 2
29628
29629x => 2
29630@end example
29631
29632As well as simple variables, you can also assign to subscript
29633expressions of the form @samp{@var{var}_@var{number}} (as in
29634@code{x_0}), or @samp{@var{var}_@var{var}} (as in @code{x_max}).
29635Assignments to other kinds of objects can be represented by Calc,
29636but the automatic linkage between assignments and references works
29637only for plain variables and these two kinds of subscript expressions.
29638
29639If there are no assignments to a given variable, the global
29640stored value for the variable is used (@pxref{Storing Variables}),
29641or, if no value is stored, the variable is left in symbolic form.
29642Note that global stored values will be lost when the file is saved
29643and loaded in a later Emacs session, unless you have used the
29644@kbd{s p} (@code{calc-permanent-variable}) command to save them;
29645@pxref{Operations on Variables}.
29646
29647The @kbd{m C} (@code{calc-auto-recompute}) command turns automatic
29648recomputation of @samp{=>} forms on and off. If you turn automatic
29649recomputation off, you will have to use @kbd{M-# u} to update these
29650formulas manually after an assignment has been changed. If you
29651plan to change several assignments at once, it may be more efficient
29652to type @kbd{m C}, change all the assignments, then use @kbd{M-1 M-# u}
29653to update the entire buffer afterwards. The @kbd{m C} command also
29654controls @samp{=>} formulas on the stack; @pxref{Evaluates-To
29655Operator}. When you turn automatic recomputation back on, the
29656stack will be updated but the Embedded buffer will not; you must
29657use @kbd{M-# u} to update the buffer by hand.
29658
29659@node Mode Settings in Embedded Mode, Customizing Embedded Mode, Assignments in Embedded Mode, Embedded Mode
29660@section Mode Settings in Embedded Mode
29661
29662@noindent
29663Embedded Mode has a rather complicated mechanism for handling mode
29664settings in Embedded formulas. It is possible to put annotations
29665in the file that specify mode settings either global to the entire
29666file or local to a particular formula or formulas. In the latter
29667case, different modes can be specified for use when a formula
29668is the enabled Embedded Mode formula.
29669
29670When you give any mode-setting command, like @kbd{m f} (for fraction
29671mode) or @kbd{d s} (for scientific notation), Embedded Mode adds
29672a line like the following one to the file just before the opening
29673delimiter of the formula.
29674
29675@example
29676% [calc-mode: fractions: t]
29677% [calc-mode: float-format: (sci 0)]
29678@end example
29679
29680When Calc interprets an embedded formula, it scans the text before
29681the formula for mode-setting annotations like these and sets the
29682Calc buffer to match these modes. Modes not explicitly described
29683in the file are not changed. Calc scans all the way to the top of
29684the file, or up to a line of the form
29685
29686@example
29687% [calc-defaults]
29688@end example
29689
29690@noindent
29691which you can insert at strategic places in the file if this backward
29692scan is getting too slow, or just to provide a barrier between one
29693``zone'' of mode settings and another.
29694
29695If the file contains several annotations for the same mode, the
29696closest one before the formula is used. Annotations after the
29697formula are never used (except for global annotations, described
29698below).
29699
29700The scan does not look for the leading @samp{% }, only for the
29701square brackets and the text they enclose. You can edit the mode
29702annotations to a style that works better in context if you wish.
29703@xref{Customizing Embedded Mode}, to see how to change the style
29704that Calc uses when it generates the annotations. You can write
29705mode annotations into the file yourself if you know the syntax;
29706the easiest way to find the syntax for a given mode is to let
29707Calc write the annotation for it once and see what it does.
29708
29709If you give a mode-changing command for a mode that already has
29710a suitable annotation just above the current formula, Calc will
29711modify that annotation rather than generating a new, conflicting
29712one.
29713
29714Mode annotations have three parts, separated by colons. (Spaces
29715after the colons are optional.) The first identifies the kind
29716of mode setting, the second is a name for the mode itself, and
29717the third is the value in the form of a Lisp symbol, number,
29718or list. Annotations with unrecognizable text in the first or
29719second parts are ignored. The third part is not checked to make
29720sure the value is of a legal type or range; if you write an
29721annotation by hand, be sure to give a proper value or results
29722will be unpredictable. Mode-setting annotations are case-sensitive.
29723
29724While Embedded Mode is enabled, the word @code{Local} appears in
29725the mode line. This is to show that mode setting commands generate
29726annotations that are ``local'' to the current formula or set of
29727formulas. The @kbd{m R} (@code{calc-mode-record-mode}) command
29728causes Calc to generate different kinds of annotations. Pressing
29729@kbd{m R} repeatedly cycles through the possible modes.
29730
29731@code{LocEdit} and @code{LocPerm} modes generate annotations
29732that look like this, respectively:
29733
29734@example
29735% [calc-edit-mode: float-format: (sci 0)]
29736% [calc-perm-mode: float-format: (sci 5)]
29737@end example
29738
29739The first kind of annotation will be used only while a formula
29740is enabled in Embedded Mode. The second kind will be used only
29741when the formula is @emph{not} enabled. (Whether the formula
29742is ``active'' or not, i.e., whether Calc has seen this formula
29743yet, is not relevant here.)
29744
29745@code{Global} mode generates an annotation like this at the end
29746of the file:
29747
29748@example
29749% [calc-global-mode: fractions t]
29750@end example
29751
29752Global mode annotations affect all formulas throughout the file,
29753and may appear anywhere in the file. This allows you to tuck your
29754mode annotations somewhere out of the way, say, on a new page of
29755the file, as long as those mode settings are suitable for all
29756formulas in the file.
29757
29758Enabling a formula with @kbd{M-# e} causes a fresh scan for local
29759mode annotations; you will have to use this after adding annotations
29760above a formula by hand to get the formula to notice them. Updating
29761a formula with @kbd{M-# u} will also re-scan the local modes, but
29762global modes are only re-scanned by @kbd{M-# a}.
29763
29764Another way that modes can get out of date is if you add a local
29765mode annotation to a formula that has another formula after it.
29766In this example, we have used the @kbd{d s} command while the
29767first of the two embedded formulas is active. But the second
29768formula has not changed its style to match, even though by the
29769rules of reading annotations the @samp{(sci 0)} applies to it, too.
29770
29771@example
29772% [calc-mode: float-format: (sci 0)]
297731.23e2
29774
29775456.
29776@end example
29777
29778We would have to go down to the other formula and press @kbd{M-# u}
29779on it in order to get it to notice the new annotation.
29780
29781Two more mode-recording modes selectable by @kbd{m R} are @code{Save}
29782(which works even outside of Embedded Mode), in which mode settings
29783are recorded permanently in your Emacs startup file @file{~/.emacs}
29784rather than by annotating the current document, and no-recording
29785mode (where there is no symbol like @code{Save} or @code{Local} in
29786the mode line), in which mode-changing commands do not leave any
29787annotations at all.
29788
29789When Embedded Mode is not enabled, mode-recording modes except
29790for @code{Save} have no effect.
29791
29792@node Customizing Embedded Mode, , Mode Settings in Embedded Mode, Embedded Mode
29793@section Customizing Embedded Mode
29794
29795@noindent
29796You can modify Embedded Mode's behavior by setting various Lisp
29797variables described here. Use @kbd{M-x set-variable} or
29798@kbd{M-x edit-options} to adjust a variable on the fly, or
29799put a suitable @code{setq} statement in your @file{~/.emacs}
29800file to set a variable permanently. (Another possibility would
29801be to use a file-local variable annotation at the end of the
29802file; @pxref{File Variables, , Local Variables in Files, emacs, the
29803Emacs manual}.)
29804
29805While none of these variables will be buffer-local by default, you
29806can make any of them local to any embedded-mode buffer. (Their
29807values in the @samp{*Calculator*} buffer are never used.)
29808
29809@vindex calc-embedded-open-formula
29810The @code{calc-embedded-open-formula} variable holds a regular
29811expression for the opening delimiter of a formula. @xref{Regexp Search,
29812, Regular Expression Search, emacs, the Emacs manual}, to see
29813how regular expressions work. Basically, a regular expression is a
29814pattern that Calc can search for. A regular expression that considers
29815blank lines, @samp{$}, and @samp{$$} to be opening delimiters is
29816@code{"\\`\\|^\n\\|\\$\\$?"}. Just in case the meaning of this
29817regular expression is not completely plain, let's go through it
29818in detail.
29819
29820The surrounding @samp{" "} marks quote the text between them as a
29821Lisp string. If you left them off, @code{set-variable} or
29822@code{edit-options} would try to read the regular expression as a
29823Lisp program.
29824
29825The most obvious property of this regular expression is that it
29826contains indecently many backslashes. There are actually two levels
29827of backslash usage going on here. First, when Lisp reads a quoted
29828string, all pairs of characters beginning with a backslash are
29829interpreted as special characters. Here, @code{\n} changes to a
29830new-line character, and @code{\\} changes to a single backslash.
29831So the actual regular expression seen by Calc is
29832@samp{\`\|^ @r{(newline)} \|\$\$?}.
29833
29834Regular expressions also consider pairs beginning with backslash
29835to have special meanings. Sometimes the backslash is used to quote
29836a character that otherwise would have a special meaning in a regular
29837expression, like @samp{$}, which normally means ``end-of-line,''
29838or @samp{?}, which means that the preceding item is optional. So
29839@samp{\$\$?} matches either one or two dollar signs.
29840
29841The other codes in this regular expression are @samp{^}, which matches
29842``beginning-of-line,'' @samp{\|}, which means ``or,'' and @samp{\`},
29843which matches ``beginning-of-buffer.'' So the whole pattern means
29844that a formula begins at the beginning of the buffer, or on a newline
29845that occurs at the beginning of a line (i.e., a blank line), or at
29846one or two dollar signs.
29847
29848The default value of @code{calc-embedded-open-formula} looks just
29849like this example, with several more alternatives added on to
29850recognize various other common kinds of delimiters.
29851
29852By the way, the reason to use @samp{^\n} rather than @samp{^$}
29853or @samp{\n\n}, which also would appear to match blank lines,
29854is that the former expression actually ``consumes'' only one
29855newline character as @emph{part of} the delimiter, whereas the
29856latter expressions consume zero or two newlines, respectively.
29857The former choice gives the most natural behavior when Calc
29858must operate on a whole formula including its delimiters.
29859
29860See the Emacs manual for complete details on regular expressions.
29861But just for your convenience, here is a list of all characters
29862which must be quoted with backslash (like @samp{\$}) to avoid
29863some special interpretation: @samp{. * + ? [ ] ^ $ \}. (Note
29864the backslash in this list; for example, to match @samp{\[} you
29865must use @code{"\\\\\\["}. An exercise for the reader is to
29866account for each of these six backslashes!)
29867
29868@vindex calc-embedded-close-formula
29869The @code{calc-embedded-close-formula} variable holds a regular
29870expression for the closing delimiter of a formula. A closing
29871regular expression to match the above example would be
29872@code{"\\'\\|\n$\\|\\$\\$?"}. This is almost the same as the
29873other one, except it now uses @samp{\'} (``end-of-buffer'') and
29874@samp{\n$} (newline occurring at end of line, yet another way
29875of describing a blank line that is more appropriate for this
29876case).
29877
29878@vindex calc-embedded-open-word
29879@vindex calc-embedded-close-word
29880The @code{calc-embedded-open-word} and @code{calc-embedded-close-word}
29881variables are similar expressions used when you type @kbd{M-# w}
29882instead of @kbd{M-# e} to enable Embedded mode.
29883
29884@vindex calc-embedded-open-plain
29885The @code{calc-embedded-open-plain} variable is a string which
29886begins a ``plain'' formula written in front of the formatted
29887formula when @kbd{d p} mode is turned on. Note that this is an
29888actual string, not a regular expression, because Calc must be able
29889to write this string into a buffer as well as to recognize it.
29890The default string is @code{"%%% "} (note the trailing space).
29891
29892@vindex calc-embedded-close-plain
29893The @code{calc-embedded-close-plain} variable is a string which
29894ends a ``plain'' formula. The default is @code{" %%%\n"}. Without
29895the trailing newline here, the first line of a ``big'' mode formula
29896that followed might be shifted over with respect to the other lines.
29897
29898@vindex calc-embedded-open-new-formula
29899The @code{calc-embedded-open-new-formula} variable is a string
29900which is inserted at the front of a new formula when you type
29901@kbd{M-# f}. Its default value is @code{"\n\n"}. If this
29902string begins with a newline character and the @kbd{M-# f} is
29903typed at the beginning of a line, @kbd{M-# f} will skip this
29904first newline to avoid introducing unnecessary blank lines in
29905the file.
29906
29907@vindex calc-embedded-close-new-formula
29908The @code{calc-embedded-close-new-formula} variable is the corresponding
29909string which is inserted at the end of a new formula. Its default
29910value is also @code{"\n\n"}. The final newline is omitted by
29911@w{@kbd{M-# f}} if typed at the end of a line. (It follows that if
29912@kbd{M-# f} is typed on a blank line, both a leading opening
29913newline and a trailing closing newline are omitted.)
29914
29915@vindex calc-embedded-announce-formula
29916The @code{calc-embedded-announce-formula} variable is a regular
29917expression which is sure to be followed by an embedded formula.
29918The @kbd{M-# a} command searches for this pattern as well as for
29919@samp{=>} and @samp{:=} operators. Note that @kbd{M-# a} will
29920not activate just anything surrounded by formula delimiters; after
29921all, blank lines are considered formula delimiters by default!
29922But if your language includes a delimiter which can only occur
29923actually in front of a formula, you can take advantage of it here.
29924The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, which
29925checks for @samp{%Embed} followed by any number of lines beginning
29926with @samp{%} and a space. This last is important to make Calc
29927consider mode annotations part of the pattern, so that the formula's
29928opening delimiter really is sure to follow the pattern.
29929
29930@vindex calc-embedded-open-mode
29931The @code{calc-embedded-open-mode} variable is a string (not a
29932regular expression) which should precede a mode annotation.
29933Calc never scans for this string; Calc always looks for the
29934annotation itself. But this is the string that is inserted before
29935the opening bracket when Calc adds an annotation on its own.
29936The default is @code{"% "}.
29937
29938@vindex calc-embedded-close-mode
29939The @code{calc-embedded-close-mode} variable is a string which
29940follows a mode annotation written by Calc. Its default value
29941is simply a newline, @code{"\n"}. If you change this, it is a
29942good idea still to end with a newline so that mode annotations
29943will appear on lines by themselves.
29944
29945@node Programming, Installation, Embedded Mode, Top
29946@chapter Programming
29947
29948@noindent
29949There are several ways to ``program'' the Emacs Calculator, depending
29950on the nature of the problem you need to solve.
29951
29952@enumerate
29953@item
29954@dfn{Keyboard macros} allow you to record a sequence of keystrokes
29955and play them back at a later time. This is just the standard Emacs
29956keyboard macro mechanism, dressed up with a few more features such
29957as loops and conditionals.
29958
29959@item
29960@dfn{Algebraic definitions} allow you to use any formula to define a
29961new function. This function can then be used in algebraic formulas or
29962as an interactive command.
29963
29964@item
29965@dfn{Rewrite rules} are discussed in the section on algebra commands.
29966@xref{Rewrite Rules}. If you put your rewrite rules in the variable
29967@code{EvalRules}, they will be applied automatically to all Calc
29968results in just the same way as an internal ``rule'' is applied to
29969evaluate @samp{sqrt(9)} to 3 and so on. @xref{Automatic Rewrites}.
29970
29971@item
29972@dfn{Lisp} is the programming language that Calc (and most of Emacs)
29973is written in. If the above techniques aren't powerful enough, you
29974can write Lisp functions to do anything that built-in Calc commands
29975can do. Lisp code is also somewhat faster than keyboard macros or
29976rewrite rules.
29977@end enumerate
29978
29979@kindex z
29980Programming features are available through the @kbd{z} and @kbd{Z}
29981prefix keys. New commands that you define are two-key sequences
29982beginning with @kbd{z}. Commands for managing these definitions
29983use the shift-@kbd{Z} prefix. (The @kbd{Z T} (@code{calc-timing})
29984command is described elsewhere; @pxref{Troubleshooting Commands}.
29985The @kbd{Z C} (@code{calc-user-define-composition}) command is also
29986described elsewhere; @pxref{User-Defined Compositions}.)
29987
29988@menu
29989* Creating User Keys::
29990* Keyboard Macros::
29991* Invocation Macros::
29992* Algebraic Definitions::
29993* Lisp Definitions::
29994@end menu
29995
29996@node Creating User Keys, Keyboard Macros, Programming, Programming
29997@section Creating User Keys
29998
29999@noindent
30000@kindex Z D
30001@pindex calc-user-define
30002Any Calculator command may be bound to a key using the @kbd{Z D}
30003(@code{calc-user-define}) command. Actually, it is bound to a two-key
30004sequence beginning with the lower-case @kbd{z} prefix.
30005
30006The @kbd{Z D} command first prompts for the key to define. For example,
30007press @kbd{Z D a} to define the new key sequence @kbd{z a}. You are then
30008prompted for the name of the Calculator command that this key should
30009run. For example, the @code{calc-sincos} command is not normally
30010available on a key. Typing @kbd{Z D s sincos @key{RET}} programs the
30011@kbd{z s} key sequence to run @code{calc-sincos}. This definition will remain
30012in effect for the rest of this Emacs session, or until you redefine
30013@kbd{z s} to be something else.
30014
30015You can actually bind any Emacs command to a @kbd{z} key sequence by
30016backspacing over the @samp{calc-} when you are prompted for the command name.
30017
30018As with any other prefix key, you can type @kbd{z ?} to see a list of
30019all the two-key sequences you have defined that start with @kbd{z}.
30020Initially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined.
30021
30022User keys are typically letters, but may in fact be any key.
30023(@key{META}-keys are not permitted, nor are a terminal's special
30024function keys which generate multi-character sequences when pressed.)
30025You can define different commands on the shifted and unshifted versions
30026of a letter if you wish.
30027
30028@kindex Z U
30029@pindex calc-user-undefine
30030The @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key.
30031For example, the key sequence @kbd{Z U s} will undefine the @code{sincos}
30032key we defined above.
30033
30034@kindex Z P
30035@pindex calc-user-define-permanent
30036@cindex Storing user definitions
30037@cindex Permanent user definitions
30038@cindex @file{.emacs} file, user-defined commands
30039The @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key
30040binding permanent so that it will remain in effect even in future Emacs
30041sessions. (It does this by adding a suitable bit of Lisp code into
30042your @file{.emacs} file.) For example, @kbd{Z P s} would register
30043our @code{sincos} command permanently. If you later wish to unregister
30044this command you must edit your @file{.emacs} file by hand.
30045(@xref{General Mode Commands}, for a way to tell Calc to use a
30046different file instead of @file{.emacs}.)
30047
30048The @kbd{Z P} command also saves the user definition, if any, for the
30049command bound to the key. After @kbd{Z F} and @kbd{Z C}, a given user
30050key could invoke a command, which in turn calls an algebraic function,
30051which might have one or more special display formats. A single @kbd{Z P}
30052command will save all of these definitions.
30053
30054To save a command or function without its key binding (or if there is
30055no key binding for the command or function), type @kbd{'} (the apostrophe)
30056when prompted for a key. Then, type the function name, or backspace
30057to change the @samp{calcFunc-} prefix to @samp{calc-} and enter a
30058command name. (If the command you give implies a function, the function
30059will be saved, and if the function has any display formats, those will
30060be saved, but not the other way around: Saving a function will not save
30061any commands or key bindings associated with the function.)
30062
30063@kindex Z E
30064@pindex calc-user-define-edit
30065@cindex Editing user definitions
30066The @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition
30067of a user key. This works for keys that have been defined by either
30068keyboard macros or formulas; further details are contained in the relevant
30069following sections.
30070
30071@node Keyboard Macros, Invocation Macros, Creating User Keys, Programming
30072@section Programming with Keyboard Macros
30073
30074@noindent
30075@kindex X
30076@cindex Programming with keyboard macros
30077@cindex Keyboard macros
30078The easiest way to ``program'' the Emacs Calculator is to use standard
30079keyboard macros. Press @w{@kbd{C-x (}} to begin recording a macro. From
30080this point on, keystrokes you type will be saved away as well as
30081performing their usual functions. Press @kbd{C-x )} to end recording.
30082Press shift-@kbd{X} (or the standard Emacs key sequence @kbd{C-x e}) to
30083execute your keyboard macro by replaying the recorded keystrokes.
30084@xref{Keyboard Macros, , , emacs, the Emacs Manual}, for further
30085information.@refill
30086
30087When you use @kbd{X} to invoke a keyboard macro, the entire macro is
30088treated as a single command by the undo and trail features. The stack
30089display buffer is not updated during macro execution, but is instead
30090fixed up once the macro completes. Thus, commands defined with keyboard
30091macros are convenient and efficient. The @kbd{C-x e} command, on the
30092other hand, invokes the keyboard macro with no special treatment: Each
30093command in the macro will record its own undo information and trail entry,
30094and update the stack buffer accordingly. If your macro uses features
30095outside of Calc's control to operate on the contents of the Calc stack
30096buffer, or if it includes Undo, Redo, or last-arguments commands, you
30097must use @kbd{C-x e} to make sure the buffer and undo list are up-to-date
30098at all times. You could also consider using @kbd{K} (@code{calc-keep-args})
30099instead of @kbd{M-@key{RET}} (@code{calc-last-args}).
30100
30101Calc extends the standard Emacs keyboard macros in several ways.
30102Keyboard macros can be used to create user-defined commands. Keyboard
30103macros can include conditional and iteration structures, somewhat
30104analogous to those provided by a traditional programmable calculator.
30105
30106@menu
30107* Naming Keyboard Macros::
30108* Conditionals in Macros::
30109* Loops in Macros::
30110* Local Values in Macros::
30111* Queries in Macros::
30112@end menu
30113
30114@node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros
30115@subsection Naming Keyboard Macros
30116
30117@noindent
30118@kindex Z K
30119@pindex calc-user-define-kbd-macro
30120Once you have defined a keyboard macro, you can bind it to a @kbd{z}
30121key sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command.
30122This command prompts first for a key, then for a command name. For
30123example, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will
30124define a keyboard macro which negates the top two numbers on the stack
30125(@key{TAB} swaps the top two stack elements). Now you can type
30126@kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key
30127sequence. The default command name (if you answer the second prompt with
30128just the @key{RET} key as in this example) will be something like
30129@samp{calc-User-n}. The keyboard macro will now be available as both
30130@kbd{z n} and @kbd{M-x calc-User-n}. You can backspace and enter a more
30131descriptive command name if you wish.@refill
30132
30133Macros defined by @kbd{Z K} act like single commands; they are executed
30134in the same way as by the @kbd{X} key. If you wish to define the macro
30135as a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}),
30136give a negative prefix argument to @kbd{Z K}.
30137
30138Once you have bound your keyboard macro to a key, you can use
30139@kbd{Z P} to register it permanently with Emacs. @xref{Creating User Keys}.
30140
30141@cindex Keyboard macros, editing
30142The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
30143been defined by a keyboard macro tries to use the @code{edit-kbd-macro}
30144command to edit the macro. This command may be found in the
30145@file{macedit} package, a copy of which comes with Calc. It decomposes
30146the macro definition into full Emacs command names, like @code{calc-pop}
30147and @code{calc-add}. Type @kbd{M-# M-#} to finish editing and update
30148the definition stored on the key, or, to cancel the edit, type
30149@kbd{M-# x}.@refill
30150
30151If you give a negative numeric prefix argument to @kbd{Z E}, the keyboard
30152macro is edited in spelled-out keystroke form. For example, the editing
30153buffer might contain the nine characters @w{@samp{1 RET 2 +}}. When you press
30154@kbd{M-# M-#}, the @code{read-kbd-macro} feature of the @file{macedit}
30155package is used to reinterpret these key names. The
30156notations @code{RET}, @code{LFD}, @code{TAB}, @code{SPC}, @code{DEL}, and
30157@code{NUL} must be written in all uppercase, as must the prefixes @code{C-}
30158and @code{M-}. Spaces and line breaks are ignored. Other characters are
30159copied verbatim into the keyboard macro. Basically, the notation is the
30160same as is used in all of this manual's examples, except that the manual
30161takes some liberties with spaces: When we say @kbd{' [1 2 3] RET}, we take
30162it for granted that it is clear we really mean @kbd{' [1 SPC 2 SPC 3] RET},
30163which is what @code{read-kbd-macro} wants to see.@refill
30164
30165If @file{macedit} is not available, @kbd{Z E} edits the keyboard macro
30166in ``raw'' form; the editing buffer simply contains characters like
30167@samp{1^M2+} (here @samp{^M} represents the carriage-return character).
30168Editing in this mode, you will have to use @kbd{C-q} to enter new
30169control characters into the buffer.@refill
30170
30171@kindex M-# m
30172@pindex read-kbd-macro
30173The @kbd{M-# m} (@code{read-kbd-macro}) command reads an Emacs ``region''
30174of spelled-out keystrokes and defines it as the current keyboard macro.
30175It is a convenient way to define a keyboard macro that has been stored
30176in a file, or to define a macro without executing it at the same time.
30177The @kbd{M-# m} command works only if @file{macedit} is present.
30178
30179@node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros
30180@subsection Conditionals in Keyboard Macros
30181
30182@noindent
30183@kindex Z [
30184@kindex Z ]
30185@pindex calc-kbd-if
30186@pindex calc-kbd-else
30187@pindex calc-kbd-else-if
30188@pindex calc-kbd-end-if
30189@cindex Conditional structures
30190The @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if})
30191commands allow you to put simple tests in a keyboard macro. When Calc
30192sees the @kbd{Z [}, it pops an object from the stack and, if the object is
30193a non-zero value, continues executing keystrokes. But if the object is
30194zero, or if it is not provably nonzero, Calc skips ahead to the matching
30195@kbd{Z ]} keystroke. @xref{Logical Operations}, for a set of commands for
30196performing tests which conveniently produce 1 for true and 0 for false.
30197
30198For example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value
30199function in the form of a keyboard macro. This macro duplicates the
30200number on the top of the stack, pushes zero and compares using @kbd{a <}
30201(@code{calc-less-than}), then, if the number was less than zero,
30202executes @kbd{n} (@code{calc-change-sign}). Otherwise, the change-sign
30203command is skipped.
30204
30205To program this macro, type @kbd{C-x (}, type the above sequence of
30206keystrokes, then type @kbd{C-x )}. Note that the keystrokes will be
30207executed while you are making the definition as well as when you later
30208re-execute the macro by typing @kbd{X}. Thus you should make sure a
30209suitable number is on the stack before defining the macro so that you
30210don't get a stack-underflow error during the definition process.
30211
30212Conditionals can be nested arbitrarily. However, there should be exactly
30213one @kbd{Z ]} for each @kbd{Z [} in a keyboard macro.
30214
30215@kindex Z :
30216The @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between
30217two keystroke sequences. The general format is @kbd{@var{cond} Z [
30218@var{then-part} Z : @var{else-part} Z ]}. If @var{cond} is true
30219(i.e., if the top of stack contains a non-zero number after @var{cond}
30220has been executed), the @var{then-part} will be executed and the
30221@var{else-part} will be skipped. Otherwise, the @var{then-part} will
30222be skipped and the @var{else-part} will be executed.
30223
30224@kindex Z |
30225The @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose
30226between any number of alternatives. For example,
30227@kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z :
30228@var{part3} Z ]} will execute @var{part1} if @var{cond1} is true,
30229otherwise it will execute @var{part2} if @var{cond2} is true, otherwise
30230it will execute @var{part3}.
30231
30232More precisely, @kbd{Z [} pops a number and conditionally skips to the
30233next matching @kbd{Z :} or @kbd{Z ]} key. @w{@kbd{Z ]}} has no effect when
30234actually executed. @kbd{Z :} skips to the next matching @kbd{Z ]}.
30235@kbd{Z |} pops a number and conditionally skips to the next matching
30236@kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally
30237equivalent except that @kbd{Z [} participates in nesting but @kbd{Z |}
30238does not.
30239
30240Calc's conditional and looping constructs work by scanning the
30241keyboard macro for occurrences of character sequences like @samp{Z:}
30242and @samp{Z]}. One side-effect of this is that if you use these
30243constructs you must be careful that these character pairs do not
30244occur by accident in other parts of the macros. Since Calc rarely
30245uses shift-@kbd{Z} for any purpose except as a prefix character, this
30246is not likely to be a problem. Another side-effect is that it will
30247not work to define your own custom key bindings for these commands.
30248Only the standard shift-@kbd{Z} bindings will work correctly.
30249
30250@kindex Z C-g
30251If Calc gets stuck while skipping characters during the definition of a
30252macro, type @kbd{Z C-g} to cancel the definition. (Typing plain @kbd{C-g}
30253actually adds a @kbd{C-g} keystroke to the macro.)
30254
30255@node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros
30256@subsection Loops in Keyboard Macros
30257
30258@noindent
30259@kindex Z <
30260@kindex Z >
30261@pindex calc-kbd-repeat
30262@pindex calc-kbd-end-repeat
30263@cindex Looping structures
30264@cindex Iterative structures
30265The @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >}
30266(@code{calc-kbd-end-repeat}) commands pop a number from the stack,
30267which must be an integer, then repeat the keystrokes between the brackets
30268the specified number of times. If the integer is zero or negative, the
30269body is skipped altogether. For example, @kbd{1 @key{TAB} Z < 2 * Z >}
30270computes two to a nonnegative integer power. First, we push 1 on the
30271stack and then swap the integer argument back to the top. The @kbd{Z <}
30272pops that argument leaving the 1 back on top of the stack. Then, we
30273repeat a multiply-by-two step however many times.@refill
30274
30275Once again, the keyboard macro is executed as it is being entered.
30276In this case it is especially important to set up reasonable initial
30277conditions before making the definition: Suppose the integer 1000 just
30278happened to be sitting on the stack before we typed the above definition!
30279Another approach is to enter a harmless dummy definition for the macro,
30280then go back and edit in the real one with a @kbd{Z E} command. Yet
30281another approach is to type the macro as written-out keystroke names
30282in a buffer, then use @kbd{M-# m} (@code{read-kbd-macro}) to read the
30283macro.
30284
30285@kindex Z /
30286@pindex calc-break
30287The @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out
30288of a keyboard macro loop prematurely. It pops an object from the stack;
30289if that object is true (a non-zero number), control jumps out of the
30290innermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues
30291after the @kbd{Z >}. If the object is false, the @kbd{Z /} has no
30292effect. Thus @kbd{@var{cond} Z /} is similar to @samp{if (@var{cond}) break;}
30293in the C language.@refill
30294
30295@kindex Z (
30296@kindex Z )
30297@pindex calc-kbd-for
30298@pindex calc-kbd-end-for
30299The @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for})
30300commands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the
30301value of the counter available inside the loop. The general layout is
30302@kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}. The @kbd{Z (}
30303command pops initial and final values from the stack. It then creates
30304a temporary internal counter and initializes it with the value @var{init}.
30305The @kbd{Z (} command then repeatedly pushes the counter value onto the
30306stack and executes @var{body} and @var{step}, adding @var{step} to the
30307counter each time until the loop finishes.@refill
30308
30309@cindex Summations (by keyboard macros)
30310By default, the loop finishes when the counter becomes greater than (or
30311less than) @var{final}, assuming @var{initial} is less than (greater
30312than) @var{final}. If @var{initial} is equal to @var{final}, the body
30313executes exactly once. The body of the loop always executes at least
30314once. For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the
30315squares of the integers from 1 to 10, in steps of 1.
30316
30317If you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is
30318forced to use upward-counting conventions. In this case, if @var{initial}
30319is greater than @var{final} the body will not be executed at all.
30320Note that @var{step} may still be negative in this loop; the prefix
30321argument merely constrains the loop-finished test. Likewise, a prefix
30322argument of @i{-1} forces downward-counting conventions.
30323
30324@kindex Z @{
30325@kindex Z @}
30326@pindex calc-kbd-loop
30327@pindex calc-kbd-end-loop
30328The @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}}
30329(@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and
30330@kbd{Z >}, except that they do not pop a count from the stack---they
30331effectively create an infinite loop. Every @kbd{Z @{} @dots{} @kbd{Z @}}
30332loop ought to include at least one @kbd{Z /} to make sure the loop
30333doesn't run forever. (If any error message occurs which causes Emacs
30334to beep, the keyboard macro will also be halted; this is a standard
30335feature of Emacs. You can also generally press @kbd{C-g} to halt a
30336running keyboard macro, although not all versions of Unix support
30337this feature.)
30338
30339The conditional and looping constructs are not actually tied to
30340keyboard macros, but they are most often used in that context.
30341For example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push
30342ten copies of 23 onto the stack. This can be typed ``live'' just
30343as easily as in a macro definition.
30344
30345@xref{Conditionals in Macros}, for some additional notes about
30346conditional and looping commands.
30347
30348@node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros
30349@subsection Local Values in Macros
30350
30351@noindent
30352@cindex Local variables
30353@cindex Restoring saved modes
30354Keyboard macros sometimes want to operate under known conditions
30355without affecting surrounding conditions. For example, a keyboard
30356macro may wish to turn on Fraction Mode, or set a particular
30357precision, independent of the user's normal setting for those
30358modes.
30359
30360@kindex Z `
30361@kindex Z '
30362@pindex calc-kbd-push
30363@pindex calc-kbd-pop
30364Macros also sometimes need to use local variables. Assignments to
30365local variables inside the macro should not affect any variables
30366outside the macro. The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '}
30367(@code{calc-kbd-pop}) commands give you both of these capabilities.
30368
30369When you type @kbd{Z `} (with a backquote or accent grave character),
30370the values of various mode settings are saved away. The ten ``quick''
30371variables @code{q0} through @code{q9} are also saved. When
30372you type @w{@kbd{Z '}} (with an apostrophe), these values are restored.
30373Pairs of @kbd{Z `} and @kbd{Z '} commands may be nested.
30374
30375If a keyboard macro halts due to an error in between a @kbd{Z `} and
30376a @kbd{Z '}, the saved values will be restored correctly even though
30377the macro never reaches the @kbd{Z '} command. Thus you can use
30378@kbd{Z `} and @kbd{Z '} without having to worry about what happens
30379in exceptional conditions.
30380
30381If you type @kbd{Z `} ``live'' (not in a keyboard macro), Calc puts
30382you into a ``recursive edit.'' You can tell you are in a recursive
30383edit because there will be extra square brackets in the mode line,
30384as in @samp{[(Calculator)]}. These brackets will go away when you
30385type the matching @kbd{Z '} command. The modes and quick variables
30386will be saved and restored in just the same way as if actual keyboard
30387macros were involved.
30388
30389The modes saved by @kbd{Z `} and @kbd{Z '} are the current precision
30390and binary word size, the angular mode (Deg, Rad, or HMS), the
30391simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
30392Matrix or Scalar mode, Fraction mode, and the current complex mode
30393(Polar or Rectangular). The ten ``quick'' variables' values (or lack
30394thereof) are also saved.
30395
30396Most mode-setting commands act as toggles, but with a numeric prefix
30397they force the mode either on (positive prefix) or off (negative
30398or zero prefix). Since you don't know what the environment might
30399be when you invoke your macro, it's best to use prefix arguments
30400for all mode-setting commands inside the macro.
30401
30402In fact, @kbd{C-u Z `} is like @kbd{Z `} except that it sets the modes
30403listed above to their default values. As usual, the matching @kbd{Z '}
30404will restore the modes to their settings from before the @kbd{C-u Z `}.
30405Also, @w{@kbd{Z `}} with a negative prefix argument resets algebraic mode
30406to its default (off) but leaves the other modes the same as they were
30407outside the construct.
30408
30409The contents of the stack and trail, values of non-quick variables, and
30410other settings such as the language mode and the various display modes,
30411are @emph{not} affected by @kbd{Z `} and @kbd{Z '}.
30412
30413@node Queries in Macros, , Local Values in Macros, Keyboard Macros
30414@subsection Queries in Keyboard Macros
30415
30416@noindent
30417@kindex Z =
30418@pindex calc-kbd-report
30419The @kbd{Z =} (@code{calc-kbd-report}) command displays an informative
30420message including the value on the top of the stack. You are prompted
30421to enter a string. That string, along with the top-of-stack value,
30422is displayed unless @kbd{m w} (@code{calc-working}) has been used
30423to turn such messages off.
30424
30425@kindex Z #
30426@pindex calc-kbd-query
30427The @kbd{Z #} (@code{calc-kbd-query}) command displays a prompt message
30428(which you enter during macro definition), then does an algebraic entry
30429which takes its input from the keyboard, even during macro execution.
30430This command allows your keyboard macros to accept numbers or formulas
30431as interactive input. All the normal conventions of algebraic input,
30432including the use of @kbd{$} characters, are supported.
30433
30434@xref{Kbd Macro Query, , , emacs, the Emacs Manual}, for a description of
30435@kbd{C-x q} (@code{kbd-macro-query}), the standard Emacs way to accept
30436keyboard input during a keyboard macro. In particular, you can use
30437@kbd{C-x q} to enter a recursive edit, which allows the user to perform
30438any Calculator operations interactively before pressing @kbd{C-M-c} to
30439return control to the keyboard macro.
30440
30441@node Invocation Macros, Algebraic Definitions, Keyboard Macros, Programming
30442@section Invocation Macros
30443
30444@kindex M-# z
30445@kindex Z I
30446@pindex calc-user-invocation
30447@pindex calc-user-define-invocation
30448Calc provides one special keyboard macro, called up by @kbd{M-# z}
30449(@code{calc-user-invocation}), that is intended to allow you to define
30450your own special way of starting Calc. To define this ``invocation
30451macro,'' create the macro in the usual way with @kbd{C-x (} and
30452@kbd{C-x )}, then type @kbd{Z I} (@code{calc-user-define-invocation}).
30453There is only one invocation macro, so you don't need to type any
30454additional letters after @kbd{Z I}. From now on, you can type
30455@kbd{M-# z} at any time to execute your invocation macro.
30456
30457For example, suppose you find yourself often grabbing rectangles of
30458numbers into Calc and multiplying their columns. You can do this
30459by typing @kbd{M-# r} to grab, and @kbd{V R : *} to multiply columns.
30460To make this into an invocation macro, just type @kbd{C-x ( M-# r
30461V R : * C-x )}, then @kbd{Z I}. Then, to multiply a rectangle of data,
30462just mark the data in its buffer in the usual way and type @kbd{M-# z}.
30463
30464Invocation macros are treated like regular Emacs keyboard macros;
30465all the special features described above for @kbd{Z K}-style macros
30466do not apply. @kbd{M-# z} is just like @kbd{C-x e}, except that it
30467uses the macro that was last stored by @kbd{Z I}. (In fact, the
30468macro does not even have to have anything to do with Calc!)
30469
30470The @kbd{m m} command saves the last invocation macro defined by
30471@kbd{Z I} along with all the other Calc mode settings.
30472@xref{General Mode Commands}.
30473
30474@node Algebraic Definitions, Lisp Definitions, Invocation Macros, Programming
30475@section Programming with Formulas
30476
30477@noindent
30478@kindex Z F
30479@pindex calc-user-define-formula
30480@cindex Programming with algebraic formulas
30481Another way to create a new Calculator command uses algebraic formulas.
30482The @kbd{Z F} (@code{calc-user-define-formula}) command stores the
30483formula at the top of the stack as the definition for a key. This
30484command prompts for five things: The key, the command name, the function
30485name, the argument list, and the behavior of the command when given
30486non-numeric arguments.
30487
30488For example, suppose we type @kbd{' a+2b @key{RET}} to push the formula
30489@samp{a + 2*b} onto the stack. We now type @kbd{Z F m} to define this
30490formula on the @kbd{z m} key sequence. The next prompt is for a command
30491name, beginning with @samp{calc-}, which should be the long (@kbd{M-x}) form
30492for the new command. If you simply press @key{RET}, a default name like
30493@code{calc-User-m} will be constructed. In our example, suppose we enter
30494@kbd{spam @key{RET}} to define the new command as @code{calc-spam}.
30495
30496If you want to give the formula a long-style name only, you can press
30497@key{SPC} or @key{RET} when asked which single key to use. For example
30498@kbd{Z F @key{RET} spam @key{RET}} defines the new command as
30499@kbd{M-x calc-spam}, with no keyboard equivalent.
30500
30501The third prompt is for a function name. The default is to use the same
30502name as the command name but with @samp{calcFunc-} in place of
30503@samp{calc-}. This is the name you will use if you want to enter your
30504new function in an algebraic formula. Suppose we enter @kbd{yow @key{RET}}.
30505Then the new function can be invoked by pushing two numbers on the
30506stack and typing @kbd{z m} or @kbd{x spam}, or by entering the algebraic
30507formula @samp{yow(x,y)}.@refill
30508
30509The fourth prompt is for the function's argument list. This is used to
30510associate values on the stack with the variables that appear in the formula.
30511The default is a list of all variables which appear in the formula, sorted
30512into alphabetical order. In our case, the default would be @samp{(a b)}.
30513This means that, when the user types @kbd{z m}, the Calculator will remove
30514two numbers from the stack, substitute these numbers for @samp{a} and
30515@samp{b} (respectively) in the formula, then simplify the formula and
30516push the result on the stack. In other words, @kbd{10 @key{RET} 100 z m}
30517would replace the 10 and 100 on the stack with the number 210, which is
30518@cite{a + 2 b} with @cite{a=10} and @cite{b=100}. Likewise, the formula
30519@samp{yow(10, 100)} will be evaluated by substituting @cite{a=10} and
30520@cite{b=100} in the definition.
30521
30522You can rearrange the order of the names before pressing @key{RET} to
30523control which stack positions go to which variables in the formula. If
30524you remove a variable from the argument list, that variable will be left
30525in symbolic form by the command. Thus using an argument list of @samp{(b)}
30526for our function would cause @kbd{10 z m} to replace the 10 on the stack
30527with the formula @samp{a + 20}. If we had used an argument list of
30528@samp{(b a)}, the result with inputs 10 and 100 would have been 120.
30529
30530You can also put a nameless function on the stack instead of just a
30531formula, as in @samp{<a, b : a + 2 b>}. @xref{Specifying Operators}.
30532In this example, the command will be defined by the formula @samp{a + 2 b}
30533using the argument list @samp{(a b)}.
30534
30535The final prompt is a y-or-n question concerning what to do if symbolic
30536arguments are given to your function. If you answer @kbd{y}, then
30537executing @kbd{z m} (using the original argument list @samp{(a b)}) with
30538arguments @cite{10} and @cite{x} will leave the function in symbolic
30539form, i.e., @samp{yow(10,x)}. On the other hand, if you answer @kbd{n},
30540then the formula will always be expanded, even for non-constant
30541arguments: @samp{10 + 2 x}. If you never plan to feed algebraic
30542formulas to your new function, it doesn't matter how you answer this
30543question.@refill
30544
30545If you answered @kbd{y} to this question you can still cause a function
30546call to be expanded by typing @kbd{a "} (@code{calc-expand-formula}).
30547Also, Calc will expand the function if necessary when you take a
30548derivative or integral or solve an equation involving the function.
30549
30550@kindex Z G
30551@pindex calc-get-user-defn
30552Once you have defined a formula on a key, you can retrieve this formula
30553with the @kbd{Z G} (@code{calc-user-define-get-defn}) command. Press a
30554key, and this command pushes the formula that was used to define that
30555key onto the stack. Actually, it pushes a nameless function that
30556specifies both the argument list and the defining formula. You will get
30557an error message if the key is undefined, or if the key was not defined
30558by a @kbd{Z F} command.@refill
30559
30560The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
30561been defined by a formula uses a variant of the @code{calc-edit} command
30562to edit the defining formula. Press @kbd{M-# M-#} to finish editing and
30563store the new formula back in the definition, or @kbd{M-# x} to
30564cancel the edit. (The argument list and other properties of the
30565definition are unchanged; to adjust the argument list, you can use
30566@kbd{Z G} to grab the function onto the stack, edit with @kbd{`}, and
30567then re-execute the @kbd{Z F} command.)
30568
30569As usual, the @kbd{Z P} command records your definition permanently.
30570In this case it will permanently record all three of the relevant
30571definitions: the key, the command, and the function.
30572
30573You may find it useful to turn off the default simplifications with
30574@kbd{m O} (@code{calc-no-simplify-mode}) when entering a formula to be
30575used as a function definition. For example, the formula @samp{deriv(a^2,v)}
30576which might be used to define a new function @samp{dsqr(a,v)} will be
30577``simplified'' to 0 immediately upon entry since @code{deriv} considers
30578@cite{a} to be constant with respect to @cite{v}. Turning off
30579default simplifications cures this problem: The definition will be stored
30580in symbolic form without ever activating the @code{deriv} function. Press
30581@kbd{m D} to turn the default simplifications back on afterwards.
30582
30583@node Lisp Definitions, , Algebraic Definitions, Programming
30584@section Programming with Lisp
30585
30586@noindent
30587The Calculator can be programmed quite extensively in Lisp. All you
30588do is write a normal Lisp function definition, but with @code{defmath}
30589in place of @code{defun}. This has the same form as @code{defun}, but it
30590automagically replaces calls to standard Lisp functions like @code{+} and
30591@code{zerop} with calls to the corresponding functions in Calc's own library.
30592Thus you can write natural-looking Lisp code which operates on all of the
30593standard Calculator data types. You can then use @kbd{Z D} if you wish to
30594bind your new command to a @kbd{z}-prefix key sequence. The @kbd{Z E} command
30595will not edit a Lisp-based definition.
30596
30597Emacs Lisp is described in the GNU Emacs Lisp Reference Manual. This section
30598assumes a familiarity with Lisp programming concepts; if you do not know
30599Lisp, you may find keyboard macros or rewrite rules to be an easier way
30600to program the Calculator.
30601
30602This section first discusses ways to write commands, functions, or
30603small programs to be executed inside of Calc. Then it discusses how
30604your own separate programs are able to call Calc from the outside.
30605Finally, there is a list of internal Calc functions and data structures
30606for the true Lisp enthusiast.
30607
30608@menu
30609* Defining Functions::
30610* Defining Simple Commands::
30611* Defining Stack Commands::
30612* Argument Qualifiers::
30613* Example Definitions::
30614
30615* Calling Calc from Your Programs::
30616* Internals::
30617@end menu
30618
30619@node Defining Functions, Defining Simple Commands, Lisp Definitions, Lisp Definitions
30620@subsection Defining New Functions
30621
30622@noindent
30623@findex defmath
30624The @code{defmath} function (actually a Lisp macro) is like @code{defun}
30625except that code in the body of the definition can make use of the full
30626range of Calculator data types. The prefix @samp{calcFunc-} is added
30627to the specified name to get the actual Lisp function name. As a simple
30628example,
30629
30630@example
30631(defmath myfact (n)
30632 (if (> n 0)
30633 (* n (myfact (1- n)))
30634 1))
30635@end example
30636
30637@noindent
30638This actually expands to the code,
30639
30640@example
30641(defun calcFunc-myfact (n)
30642 (if (math-posp n)
30643 (math-mul n (calcFunc-myfact (math-add n -1)))
30644 1))
30645@end example
30646
30647@noindent
30648This function can be used in algebraic expressions, e.g., @samp{myfact(5)}.
30649
30650The @samp{myfact} function as it is defined above has the bug that an
30651expression @samp{myfact(a+b)} will be simplified to 1 because the
30652formula @samp{a+b} is not considered to be @code{posp}. A robust
30653factorial function would be written along the following lines:
30654
30655@smallexample
30656(defmath myfact (n)
30657 (if (> n 0)
30658 (* n (myfact (1- n)))
30659 (if (= n 0)
30660 1
30661 nil))) ; this could be simplified as: (and (= n 0) 1)
30662@end smallexample
30663
30664If a function returns @code{nil}, it is left unsimplified by the Calculator
30665(except that its arguments will be simplified). Thus, @samp{myfact(a+1+2)}
30666will be simplified to @samp{myfact(a+3)} but no further. Beware that every
30667time the Calculator reexamines this formula it will attempt to resimplify
30668it, so your function ought to detect the returning-@code{nil} case as
30669efficiently as possible.
30670
30671The following standard Lisp functions are treated by @code{defmath}:
30672@code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^} or
30673@code{expt}, @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
30674@code{/=}, @code{1+}, @code{1-}, @code{logand}, @code{logior}, @code{logxor},
30675@code{logandc2}, @code{lognot}. Also, @code{~=} is an abbreviation for
30676@code{math-nearly-equal}, which is useful in implementing Taylor series.@refill
30677
30678For other functions @var{func}, if a function by the name
30679@samp{calcFunc-@var{func}} exists it is used, otherwise if a function by the
30680name @samp{math-@var{func}} exists it is used, otherwise if @var{func} itself
30681is defined as a function it is used, otherwise @samp{calcFunc-@var{func}} is
30682used on the assumption that this is a to-be-defined math function. Also, if
30683the function name is quoted as in @samp{('integerp a)} the function name is
30684always used exactly as written (but not quoted).@refill
30685
30686Variable names have @samp{var-} prepended to them unless they appear in
30687the function's argument list or in an enclosing @code{let}, @code{let*},
30688@code{for}, or @code{foreach} form,
30689or their names already contain a @samp{-} character. Thus a reference to
30690@samp{foo} is the same as a reference to @samp{var-foo}.@refill
30691
30692A few other Lisp extensions are available in @code{defmath} definitions:
30693
30694@itemize @bullet
30695@item
30696The @code{elt} function accepts any number of index variables.
30697Note that Calc vectors are stored as Lisp lists whose first
30698element is the symbol @code{vec}; thus, @samp{(elt v 2)} yields
30699the second element of vector @code{v}, and @samp{(elt m i j)}
30700yields one element of a Calc matrix.
30701
30702@item
30703The @code{setq} function has been extended to act like the Common
30704Lisp @code{setf} function. (The name @code{setf} is recognized as
30705a synonym of @code{setq}.) Specifically, the first argument of
30706@code{setq} can be an @code{nth}, @code{elt}, @code{car}, or @code{cdr} form,
30707in which case the effect is to store into the specified
30708element of a list. Thus, @samp{(setq (elt m i j) x)} stores @cite{x}
30709into one element of a matrix.
30710
30711@item
30712A @code{for} looping construct is available. For example,
30713@samp{(for ((i 0 10)) body)} executes @code{body} once for each
30714binding of @cite{i} from zero to 10. This is like a @code{let}
30715form in that @cite{i} is temporarily bound to the loop count
30716without disturbing its value outside the @code{for} construct.
30717Nested loops, as in @samp{(for ((i 0 10) (j 0 (1- i) 2)) body)},
30718are also available. For each value of @cite{i} from zero to 10,
30719@cite{j} counts from 0 to @cite{i-1} in steps of two. Note that
30720@code{for} has the same general outline as @code{let*}, except
30721that each element of the header is a list of three or four
30722things, not just two.
30723
30724@item
30725The @code{foreach} construct loops over elements of a list.
30726For example, @samp{(foreach ((x (cdr v))) body)} executes
30727@code{body} with @cite{x} bound to each element of Calc vector
30728@cite{v} in turn. The purpose of @code{cdr} here is to skip over
30729the initial @code{vec} symbol in the vector.
30730
30731@item
30732The @code{break} function breaks out of the innermost enclosing
30733@code{while}, @code{for}, or @code{foreach} loop. If given a
30734value, as in @samp{(break x)}, this value is returned by the
30735loop. (Lisp loops otherwise always return @code{nil}.)
30736
30737@item
30738The @code{return} function prematurely returns from the enclosing
30739function. For example, @samp{(return (+ x y))} returns @cite{x+y}
30740as the value of a function. You can use @code{return} anywhere
30741inside the body of the function.
30742@end itemize
30743
30744Non-integer numbers (and extremely large integers) cannot be included
30745directly into a @code{defmath} definition. This is because the Lisp
30746reader will fail to parse them long before @code{defmath} ever gets control.
30747Instead, use the notation, @samp{:"3.1415"}. In fact, any algebraic
30748formula can go between the quotes. For example,
30749
30750@smallexample
30751(defmath sqexp (x) ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
30752 (and (numberp x)
30753 (exp :"x * 0.5")))
30754@end smallexample
30755
30756expands to
30757
30758@smallexample
30759(defun calcFunc-sqexp (x)
30760 (and (math-numberp x)
30761 (calcFunc-exp (math-mul x '(float 5 -1)))))
30762@end smallexample
30763
30764Note the use of @code{numberp} as a guard to ensure that the argument is
30765a number first, returning @code{nil} if not. The exponential function
30766could itself have been included in the expression, if we had preferred:
30767@samp{:"exp(x * 0.5)"}. As another example, the multiplication-and-recursion
30768step of @code{myfact} could have been written
30769
30770@example
30771:"n * myfact(n-1)"
30772@end example
30773
30774If a file named @file{.emacs} exists in your home directory, Emacs reads
30775and executes the Lisp forms in this file as it starts up. While it may
30776seem like a good idea to put your favorite @code{defmath} commands here,
30777this has the unfortunate side-effect that parts of the Calculator must be
30778loaded in to process the @code{defmath} commands whether or not you will
30779actually use the Calculator! A better effect can be had by writing
30780
30781@example
30782(put 'calc-define 'thing '(progn
30783 (defmath ... )
30784 (defmath ... )
30785))
30786@end example
30787
30788@noindent
30789@vindex calc-define
30790The @code{put} function adds a @dfn{property} to a symbol. Each Lisp
30791symbol has a list of properties associated with it. Here we add a
30792property with a name of @code{thing} and a @samp{(progn ...)} form as
30793its value. When Calc starts up, and at the start of every Calc command,
30794the property list for the symbol @code{calc-define} is checked and the
30795values of any properties found are evaluated as Lisp forms. The
30796properties are removed as they are evaluated. The property names
30797(like @code{thing}) are not used; you should choose something like the
30798name of your project so as not to conflict with other properties.
30799
30800The net effect is that you can put the above code in your @file{.emacs}
30801file and it will not be executed until Calc is loaded. Or, you can put
30802that same code in another file which you load by hand either before or
30803after Calc itself is loaded.
30804
30805The properties of @code{calc-define} are evaluated in the same order
30806that they were added. They can assume that the Calc modules @file{calc.el},
30807@file{calc-ext.el}, and @file{calc-macs.el} have been fully loaded, and
30808that the @samp{*Calculator*} buffer will be the current buffer.
30809
30810If your @code{calc-define} property only defines algebraic functions,
30811you can be sure that it will have been evaluated before Calc tries to
30812call your function, even if the file defining the property is loaded
30813after Calc is loaded. But if the property defines commands or key
30814sequences, it may not be evaluated soon enough. (Suppose it defines the
30815new command @code{tweak-calc}; the user can load your file, then type
30816@kbd{M-x tweak-calc} before Calc has had chance to do anything.) To
30817protect against this situation, you can put
30818
30819@example
30820(run-hooks 'calc-check-defines)
30821@end example
30822
30823@findex calc-check-defines
30824@noindent
30825at the end of your file. The @code{calc-check-defines} function is what
30826looks for and evaluates properties on @code{calc-define}; @code{run-hooks}
30827has the advantage that it is quietly ignored if @code{calc-check-defines}
30828is not yet defined because Calc has not yet been loaded.
30829
30830Examples of things that ought to be enclosed in a @code{calc-define}
30831property are @code{defmath} calls, @code{define-key} calls that modify
30832the Calc key map, and any calls that redefine things defined inside Calc.
30833Ordinary @code{defun}s need not be enclosed with @code{calc-define}.
30834
30835@node Defining Simple Commands, Defining Stack Commands, Defining Functions, Lisp Definitions
30836@subsection Defining New Simple Commands
30837
30838@noindent
30839@findex interactive
30840If a @code{defmath} form contains an @code{interactive} clause, it defines
30841a Calculator command. Actually such a @code{defmath} results in @emph{two}
30842function definitions: One, a @samp{calcFunc-} function as was just described,
30843with the @code{interactive} clause removed. Two, a @samp{calc-} function
30844with a suitable @code{interactive} clause and some sort of wrapper to make
30845the command work in the Calc environment.
30846
30847In the simple case, the @code{interactive} clause has the same form as
30848for normal Emacs Lisp commands:
30849
30850@smallexample
30851(defmath increase-precision (delta)
30852 "Increase precision by DELTA." ; This is the "documentation string"
30853 (interactive "p") ; Register this as a M-x-able command
30854 (setq calc-internal-prec (+ calc-internal-prec delta)))
30855@end smallexample
30856
30857This expands to the pair of definitions,
30858
30859@smallexample
30860(defun calc-increase-precision (delta)
30861 "Increase precision by DELTA."
30862 (interactive "p")
30863 (calc-wrapper
30864 (setq calc-internal-prec (math-add calc-internal-prec delta))))
30865
30866(defun calcFunc-increase-precision (delta)
30867 "Increase precision by DELTA."
30868 (setq calc-internal-prec (math-add calc-internal-prec delta)))
30869@end smallexample
30870
30871@noindent
30872where in this case the latter function would never really be used! Note
30873that since the Calculator stores small integers as plain Lisp integers,
30874the @code{math-add} function will work just as well as the native
30875@code{+} even when the intent is to operate on native Lisp integers.
30876
30877@findex calc-wrapper
30878The @samp{calc-wrapper} call invokes a macro which surrounds the body of
30879the function with code that looks roughly like this:
30880
30881@smallexample
30882(let ((calc-command-flags nil))
30883 (unwind-protect
30884 (save-excursion
30885 (calc-select-buffer)
30886 @emph{body of function}
30887 @emph{renumber stack}
30888 @emph{clear} Working @emph{message})
30889 @emph{realign cursor and window}
30890 @emph{clear Inverse, Hyperbolic, and Keep Args flags}
30891 @emph{update Emacs mode line}))
30892@end smallexample
30893
30894@findex calc-select-buffer
30895The @code{calc-select-buffer} function selects the @samp{*Calculator*}
30896buffer if necessary, say, because the command was invoked from inside
30897the @samp{*Calc Trail*} window.
30898
30899@findex calc-set-command-flag
30900You can call, for example, @code{(calc-set-command-flag 'no-align)} to set
30901the above-mentioned command flags. The following command flags are
30902recognized by Calc routines:
30903
30904@table @code
30905@item renum-stack
30906Stack line numbers @samp{1:}, @samp{2:}, and so on must be renumbered
30907after this command completes. This is set by routines like
30908@code{calc-push}.
30909
30910@item clear-message
30911Calc should call @samp{(message "")} if this command completes normally
30912(to clear a ``Working@dots{}'' message out of the echo area).
30913
30914@item no-align
30915Do not move the cursor back to the @samp{.} top-of-stack marker.
30916
30917@item position-point
30918Use the variables @code{calc-position-point-line} and
30919@code{calc-position-point-column} to position the cursor after
30920this command finishes.
30921
30922@item keep-flags
30923Do not clear @code{calc-inverse-flag}, @code{calc-hyperbolic-flag},
30924and @code{calc-keep-args-flag} at the end of this command.
30925
30926@item do-edit
30927Switch to buffer @samp{*Calc Edit*} after this command.
30928
30929@item hold-trail
30930Do not move trail pointer to end of trail when something is recorded
30931there.
30932@end table
30933
30934@kindex Y
30935@kindex Y ?
30936@vindex calc-Y-help-msgs
30937Calc reserves a special prefix key, shift-@kbd{Y}, for user-written
30938extensions to Calc. There are no built-in commands that work with
30939this prefix key; you must call @code{define-key} from Lisp (probably
30940from inside a @code{calc-define} property) to add to it. Initially only
30941@kbd{Y ?} is defined; it takes help messages from a list of strings
30942(initially @code{nil}) in the variable @code{calc-Y-help-msgs}. All
30943other undefined keys except for @kbd{Y} are reserved for use by
30944future versions of Calc.
30945
30946If you are writing a Calc enhancement which you expect to give to
30947others, it is best to minimize the number of @kbd{Y}-key sequences
30948you use. In fact, if you have more than one key sequence you should
30949consider defining three-key sequences with a @kbd{Y}, then a key that
30950stands for your package, then a third key for the particular command
30951within your package.
30952
30953Users may wish to install several Calc enhancements, and it is possible
30954that several enhancements will choose to use the same key. In the
30955example below, a variable @code{inc-prec-base-key} has been defined
30956to contain the key that identifies the @code{inc-prec} package. Its
30957value is initially @code{"P"}, but a user can change this variable
30958if necessary without having to modify the file.
30959
30960Here is a complete file, @file{inc-prec.el}, which makes a @kbd{Y P I}
30961command that increases the precision, and a @kbd{Y P D} command that
30962decreases the precision.
30963
30964@smallexample
30965;;; Increase and decrease Calc precision. Dave Gillespie, 5/31/91.
30966;;; (Include copyright or copyleft stuff here.)
30967
30968(defvar inc-prec-base-key "P"
30969 "Base key for inc-prec.el commands.")
30970
30971(put 'calc-define 'inc-prec '(progn
30972
30973(define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
30974 'increase-precision)
30975(define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
30976 'decrease-precision)
30977
30978(setq calc-Y-help-msgs
30979 (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
30980 calc-Y-help-msgs))
30981
30982(defmath increase-precision (delta)
30983 "Increase precision by DELTA."
30984 (interactive "p")
30985 (setq calc-internal-prec (+ calc-internal-prec delta)))
30986
30987(defmath decrease-precision (delta)
30988 "Decrease precision by DELTA."
30989 (interactive "p")
30990 (setq calc-internal-prec (- calc-internal-prec delta)))
30991
30992)) ; end of calc-define property
30993
30994(run-hooks 'calc-check-defines)
30995@end smallexample
30996
30997@node Defining Stack Commands, Argument Qualifiers, Defining Simple Commands, Lisp Definitions
30998@subsection Defining New Stack-Based Commands
30999
31000@noindent
31001To define a new computational command which takes and/or leaves arguments
31002on the stack, a special form of @code{interactive} clause is used.
31003
31004@example
31005(interactive @var{num} @var{tag})
31006@end example
31007
31008@noindent
31009where @var{num} is an integer, and @var{tag} is a string. The effect is
31010to pop @var{num} values off the stack, resimplify them by calling
31011@code{calc-normalize}, and hand them to your function according to the
31012function's argument list. Your function may include @code{&optional} and
31013@code{&rest} parameters, so long as calling the function with @var{num}
31014parameters is legal.
31015
31016Your function must return either a number or a formula in a form
31017acceptable to Calc, or a list of such numbers or formulas. These value(s)
31018are pushed onto the stack when the function completes. They are also
31019recorded in the Calc Trail buffer on a line beginning with @var{tag},
31020a string of (normally) four characters or less. If you omit @var{tag}
31021or use @code{nil} as a tag, the result is not recorded in the trail.
31022
31023As an example, the definition
31024
31025@smallexample
31026(defmath myfact (n)
31027 "Compute the factorial of the integer at the top of the stack."
31028 (interactive 1 "fact")
31029 (if (> n 0)
31030 (* n (myfact (1- n)))
31031 (and (= n 0) 1)))
31032@end smallexample
31033
31034@noindent
31035is a version of the factorial function shown previously which can be used
31036as a command as well as an algebraic function. It expands to
31037
31038@smallexample
31039(defun calc-myfact ()
31040 "Compute the factorial of the integer at the top of the stack."
31041 (interactive)
31042 (calc-slow-wrapper
31043 (calc-enter-result 1 "fact"
31044 (cons 'calcFunc-myfact (calc-top-list-n 1)))))
31045
31046(defun calcFunc-myfact (n)
31047 "Compute the factorial of the integer at the top of the stack."
31048 (if (math-posp n)
31049 (math-mul n (calcFunc-myfact (math-add n -1)))
31050 (and (math-zerop n) 1)))
31051@end smallexample
31052
31053@findex calc-slow-wrapper
31054The @code{calc-slow-wrapper} function is a version of @code{calc-wrapper}
31055that automatically puts up a @samp{Working...} message before the
31056computation begins. (This message can be turned off by the user
31057with an @kbd{m w} (@code{calc-working}) command.)
31058
31059@findex calc-top-list-n
31060The @code{calc-top-list-n} function returns a list of the specified number
31061of values from the top of the stack. It resimplifies each value by
31062calling @code{calc-normalize}. If its argument is zero it returns an
31063empty list. It does not actually remove these values from the stack.
31064
31065@findex calc-enter-result
31066The @code{calc-enter-result} function takes an integer @var{num} and string
31067@var{tag} as described above, plus a third argument which is either a
31068Calculator data object or a list of such objects. These objects are
31069resimplified and pushed onto the stack after popping the specified number
31070of values from the stack. If @var{tag} is non-@code{nil}, the values
31071being pushed are also recorded in the trail.
31072
31073Note that if @code{calcFunc-myfact} returns @code{nil} this represents
31074``leave the function in symbolic form.'' To return an actual empty list,
31075in the sense that @code{calc-enter-result} will push zero elements back
31076onto the stack, you should return the special value @samp{'(nil)}, a list
31077containing the single symbol @code{nil}.
31078
31079The @code{interactive} declaration can actually contain a limited
31080Emacs-style code string as well which comes just before @var{num} and
31081@var{tag}. Currently the only Emacs code supported is @samp{"p"}, as in
31082
31083@example
31084(defmath foo (a b &optional c)
31085 (interactive "p" 2 "foo")
31086 @var{body})
31087@end example
31088
31089In this example, the command @code{calc-foo} will evaluate the expression
31090@samp{foo(a,b)} if executed with no argument, or @samp{foo(a,b,n)} if
31091executed with a numeric prefix argument of @cite{n}.
31092
31093The other code string allowed is @samp{"m"} (unrelated to the usual @samp{"m"}
31094code as used with @code{defun}). It uses the numeric prefix argument as the
31095number of objects to remove from the stack and pass to the function.
31096In this case, the integer @var{num} serves as a default number of
31097arguments to be used when no prefix is supplied.
31098
31099@node Argument Qualifiers, Example Definitions, Defining Stack Commands, Lisp Definitions
31100@subsection Argument Qualifiers
31101
31102@noindent
31103Anywhere a parameter name can appear in the parameter list you can also use
31104an @dfn{argument qualifier}. Thus the general form of a definition is:
31105
31106@example
31107(defmath @var{name} (@var{param} @var{param...}
31108 &optional @var{param} @var{param...}
31109 &rest @var{param})
31110 @var{body})
31111@end example
31112
31113@noindent
31114where each @var{param} is either a symbol or a list of the form
31115
31116@example
31117(@var{qual} @var{param})
31118@end example
31119
31120The following qualifiers are recognized:
31121
31122@table @samp
31123@item complete
31124@findex complete
31125The argument must not be an incomplete vector, interval, or complex number.
31126(This is rarely needed since the Calculator itself will never call your
31127function with an incomplete argument. But there is nothing stopping your
31128own Lisp code from calling your function with an incomplete argument.)@refill
31129
31130@item integer
31131@findex integer
31132The argument must be an integer. If it is an integer-valued float
31133it will be accepted but converted to integer form. Non-integers and
31134formulas are rejected.
31135
31136@item natnum
31137@findex natnum
31138Like @samp{integer}, but the argument must be non-negative.
31139
31140@item fixnum
31141@findex fixnum
31142Like @samp{integer}, but the argument must fit into a native Lisp integer,
31143which on most systems means less than 2^23 in absolute value. The
31144argument is converted into Lisp-integer form if necessary.
31145
31146@item float
31147@findex float
31148The argument is converted to floating-point format if it is a number or
31149vector. If it is a formula it is left alone. (The argument is never
31150actually rejected by this qualifier.)
31151
31152@item @var{pred}
31153The argument must satisfy predicate @var{pred}, which is one of the
31154standard Calculator predicates. @xref{Predicates}.
31155
31156@item not-@var{pred}
31157The argument must @emph{not} satisfy predicate @var{pred}.
31158@end table
31159
31160For example,
31161
31162@example
31163(defmath foo (a (constp (not-matrixp b)) &optional (float c)
31164 &rest (integer d))
31165 @var{body})
31166@end example
31167
31168@noindent
31169expands to
31170
31171@example
31172(defun calcFunc-foo (a b &optional c &rest d)
31173 (and (math-matrixp b)
31174 (math-reject-arg b 'not-matrixp))
31175 (or (math-constp b)
31176 (math-reject-arg b 'constp))
31177 (and c (setq c (math-check-float c)))
31178 (setq d (mapcar 'math-check-integer d))
31179 @var{body})
31180@end example
31181
31182@noindent
31183which performs the necessary checks and conversions before executing the
31184body of the function.
31185
31186@node Example Definitions, Calling Calc from Your Programs, Argument Qualifiers, Lisp Definitions
31187@subsection Example Definitions
31188
31189@noindent
31190This section includes some Lisp programming examples on a larger scale.
31191These programs make use of some of the Calculator's internal functions;
31192@pxref{Internals}.
31193
31194@menu
31195* Bit Counting Example::
31196* Sine Example::
31197@end menu
31198
31199@node Bit Counting Example, Sine Example, Example Definitions, Example Definitions
31200@subsubsection Bit-Counting
31201
31202@noindent
31203@c @starindex
31204@tindex bcount
31205Calc does not include a built-in function for counting the number of
31206``one'' bits in a binary integer. It's easy to invent one using @kbd{b u}
31207to convert the integer to a set, and @kbd{V #} to count the elements of
31208that set; let's write a function that counts the bits without having to
31209create an intermediate set.
31210
31211@smallexample
31212(defmath bcount ((natnum n))
31213 (interactive 1 "bcnt")
31214 (let ((count 0))
31215 (while (> n 0)
31216 (if (oddp n)
31217 (setq count (1+ count)))
31218 (setq n (lsh n -1)))
31219 count))
31220@end smallexample
31221
31222@noindent
31223When this is expanded by @code{defmath}, it will become the following
31224Emacs Lisp function:
31225
31226@smallexample
31227(defun calcFunc-bcount (n)
31228 (setq n (math-check-natnum n))
31229 (let ((count 0))
31230 (while (math-posp n)
31231 (if (math-oddp n)
31232 (setq count (math-add count 1)))
31233 (setq n (calcFunc-lsh n -1)))
31234 count))
31235@end smallexample
31236
31237If the input numbers are large, this function involves a fair amount
31238of arithmetic. A binary right shift is essentially a division by two;
31239recall that Calc stores integers in decimal form so bit shifts must
31240involve actual division.
31241
31242To gain a bit more efficiency, we could divide the integer into
31243@i{n}-bit chunks, each of which can be handled quickly because
31244they fit into Lisp integers. It turns out that Calc's arithmetic
31245routines are especially fast when dividing by an integer less than
312461000, so we can set @i{n = 9} bits and use repeated division by 512:
31247
31248@smallexample
31249(defmath bcount ((natnum n))
31250 (interactive 1 "bcnt")
31251 (let ((count 0))
31252 (while (not (fixnump n))
31253 (let ((qr (idivmod n 512)))
31254 (setq count (+ count (bcount-fixnum (cdr qr)))
31255 n (car qr))))
31256 (+ count (bcount-fixnum n))))
31257
31258(defun bcount-fixnum (n)
31259 (let ((count 0))
31260 (while (> n 0)
31261 (setq count (+ count (logand n 1))
31262 n (lsh n -1)))
31263 count))
31264@end smallexample
31265
31266@noindent
31267Note that the second function uses @code{defun}, not @code{defmath}.
31268Because this function deals only with native Lisp integers (``fixnums''),
31269it can use the actual Emacs @code{+} and related functions rather
31270than the slower but more general Calc equivalents which @code{defmath}
31271uses.
31272
31273The @code{idivmod} function does an integer division, returning both
31274the quotient and the remainder at once. Again, note that while it
31275might seem that @samp{(logand n 511)} and @samp{(lsh n -9)} are
31276more efficient ways to split off the bottom nine bits of @code{n},
31277actually they are less efficient because each operation is really
31278a division by 512 in disguise; @code{idivmod} allows us to do the
31279same thing with a single division by 512.
31280
31281@node Sine Example, , Bit Counting Example, Example Definitions
31282@subsubsection The Sine Function
31283
31284@noindent
31285@c @starindex
31286@tindex mysin
31287A somewhat limited sine function could be defined as follows, using the
31288well-known Taylor series expansion for @c{$\sin x$}
31289@samp{sin(x)}:
31290
31291@smallexample
31292(defmath mysin ((float (anglep x)))
31293 (interactive 1 "mysn")
31294 (setq x (to-radians x)) ; Convert from current angular mode.
31295 (let ((sum x) ; Initial term of Taylor expansion of sin.
31296 newsum
31297 (nfact 1) ; "nfact" equals "n" factorial at all times.
31298 (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
31299 (for ((n 3 100 2)) ; Upper limit of 100 is a good precaution.
31300 (working "mysin" sum) ; Display "Working" message, if enabled.
31301 (setq nfact (* nfact (1- n) n)
31302 x (* x xnegsqr)
31303 newsum (+ sum (/ x nfact)))
31304 (if (~= newsum sum) ; If newsum is "nearly equal to" sum,
31305 (break)) ; then we are done.
31306 (setq sum newsum))
31307 sum))
31308@end smallexample
31309
31310The actual @code{sin} function in Calc works by first reducing the problem
31311to a sine or cosine of a nonnegative number less than @c{$\pi \over 4$}
31312@cite{pi/4}. This
31313ensures that the Taylor series will converge quickly. Also, the calculation
31314is carried out with two extra digits of precision to guard against cumulative
31315round-off in @samp{sum}. Finally, complex arguments are allowed and handled
31316by a separate algorithm.
31317
31318@smallexample
31319(defmath mysin ((float (scalarp x)))
31320 (interactive 1 "mysn")
31321 (setq x (to-radians x)) ; Convert from current angular mode.
31322 (with-extra-prec 2 ; Evaluate with extra precision.
31323 (cond ((complexp x)
31324 (mysin-complex x))
31325 ((< x 0)
31326 (- (mysin-raw (- x))) ; Always call mysin-raw with x >= 0.
31327 (t (mysin-raw x))))))
31328
31329(defmath mysin-raw (x)
31330 (cond ((>= x 7)
31331 (mysin-raw (% x (two-pi)))) ; Now x < 7.
31332 ((> x (pi-over-2))
31333 (- (mysin-raw (- x (pi))))) ; Now -pi/2 <= x <= pi/2.
31334 ((> x (pi-over-4))
31335 (mycos-raw (- x (pi-over-2)))) ; Now -pi/2 <= x <= pi/4.
31336 ((< x (- (pi-over-4)))
31337 (- (mycos-raw (+ x (pi-over-2))))) ; Now -pi/4 <= x <= pi/4,
31338 (t (mysin-series x)))) ; so the series will be efficient.
31339@end smallexample
31340
31341@noindent
31342where @code{mysin-complex} is an appropriate function to handle complex
31343numbers, @code{mysin-series} is the routine to compute the sine Taylor
31344series as before, and @code{mycos-raw} is a function analogous to
31345@code{mysin-raw} for cosines.
31346
31347The strategy is to ensure that @cite{x} is nonnegative before calling
31348@code{mysin-raw}. This function then recursively reduces its argument
31349to a suitable range, namely, plus-or-minus @c{$\pi \over 4$}
31350@cite{pi/4}. Note that each
31351test, and particularly the first comparison against 7, is designed so
31352that small roundoff errors cannnot produce an infinite loop. (Suppose
31353we compared with @samp{(two-pi)} instead; if due to roundoff problems
31354the modulo operator ever returned @samp{(two-pi)} exactly, an infinite
31355recursion could result!) We use modulo only for arguments that will
31356clearly get reduced, knowing that the next rule will catch any reductions
31357that this rule misses.
31358
31359If a program is being written for general use, it is important to code
31360it carefully as shown in this second example. For quick-and-dirty programs,
31361when you know that your own use of the sine function will never encounter
31362a large argument, a simpler program like the first one shown is fine.
31363
31364@node Calling Calc from Your Programs, Internals, Example Definitions, Lisp Definitions
31365@subsection Calling Calc from Your Lisp Programs
31366
31367@noindent
31368A later section (@pxref{Internals}) gives a full description of
31369Calc's internal Lisp functions. It's not hard to call Calc from
31370inside your programs, but the number of these functions can be daunting.
31371So Calc provides one special ``programmer-friendly'' function called
31372@code{calc-eval} that can be made to do just about everything you
31373need. It's not as fast as the low-level Calc functions, but it's
31374much simpler to use!
31375
31376It may seem that @code{calc-eval} itself has a daunting number of
31377options, but they all stem from one simple operation.
31378
31379In its simplest manifestation, @samp{(calc-eval "1+2")} parses the
31380string @code{"1+2"} as if it were a Calc algebraic entry and returns
31381the result formatted as a string: @code{"3"}.
31382
31383Since @code{calc-eval} is on the list of recommended @code{autoload}
31384functions, you don't need to make any special preparations to load
31385Calc before calling @code{calc-eval} the first time. Calc will be
31386loaded and initialized for you.
31387
31388All the Calc modes that are currently in effect will be used when
31389evaluating the expression and formatting the result.
31390
31391@ifinfo
31392@example
31393
31394@end example
31395@end ifinfo
31396@subsubsection Additional Arguments to @code{calc-eval}
31397
31398@noindent
31399If the input string parses to a list of expressions, Calc returns
31400the results separated by @code{", "}. You can specify a different
31401separator by giving a second string argument to @code{calc-eval}:
31402@samp{(calc-eval "1+2,3+4" ";")} returns @code{"3;7"}.
31403
31404The ``separator'' can also be any of several Lisp symbols which
31405request other behaviors from @code{calc-eval}. These are discussed
31406one by one below.
31407
31408You can give additional arguments to be substituted for
31409@samp{$}, @samp{$$}, and so on in the main expression. For
31410example, @samp{(calc-eval "$/$$" nil "7" "1+1")} evaluates the
31411expression @code{"7/(1+1)"} to yield the result @code{"3.5"}
31412(assuming Fraction mode is not in effect). Note the @code{nil}
31413used as a placeholder for the item-separator argument.
31414
31415@ifinfo
31416@example
31417
31418@end example
31419@end ifinfo
31420@subsubsection Error Handling
31421
31422@noindent
31423If @code{calc-eval} encounters an error, it returns a list containing
31424the character position of the error, plus a suitable message as a
31425string. Note that @samp{1 / 0} is @emph{not} an error by Calc's
31426standards; it simply returns the string @code{"1 / 0"} which is the
31427division left in symbolic form. But @samp{(calc-eval "1/")} will
31428return the list @samp{(2 "Expected a number")}.
31429
31430If you bind the variable @code{calc-eval-error} to @code{t}
31431using a @code{let} form surrounding the call to @code{calc-eval},
31432errors instead call the Emacs @code{error} function which aborts
31433to the Emacs command loop with a beep and an error message.
31434
31435If you bind this variable to the symbol @code{string}, error messages
31436are returned as strings instead of lists. The character position is
31437ignored.
31438
31439As a courtesy to other Lisp code which may be using Calc, be sure
31440to bind @code{calc-eval-error} using @code{let} rather than changing
31441it permanently with @code{setq}.
31442
31443@ifinfo
31444@example
31445
31446@end example
31447@end ifinfo
31448@subsubsection Numbers Only
31449
31450@noindent
31451Sometimes it is preferable to treat @samp{1 / 0} as an error
31452rather than returning a symbolic result. If you pass the symbol
31453@code{num} as the second argument to @code{calc-eval}, results
31454that are not constants are treated as errors. The error message
31455reported is the first @code{calc-why} message if there is one,
31456or otherwise ``Number expected.''
31457
31458A result is ``constant'' if it is a number, vector, or other
31459object that does not include variables or function calls. If it
31460is a vector, the components must themselves be constants.
31461
31462@ifinfo
31463@example
31464
31465@end example
31466@end ifinfo
31467@subsubsection Default Modes
31468
31469@noindent
31470If the first argument to @code{calc-eval} is a list whose first
31471element is a formula string, then @code{calc-eval} sets all the
31472various Calc modes to their default values while the formula is
31473evaluated and formatted. For example, the precision is set to 12
31474digits, digit grouping is turned off, and the normal language
31475mode is used.
31476
31477This same principle applies to the other options discussed below.
31478If the first argument would normally be @var{x}, then it can also
31479be the list @samp{(@var{x})} to use the default mode settings.
31480
31481If there are other elements in the list, they are taken as
31482variable-name/value pairs which override the default mode
31483settings. Look at the documentation at the front of the
31484@file{calc.el} file to find the names of the Lisp variables for
31485the various modes. The mode settings are restored to their
31486original values when @code{calc-eval} is done.
31487
31488For example, @samp{(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)}
31489computes the sum of two numbers, requiring a numeric result, and
31490using default mode settings except that the precision is 8 instead
31491of the default of 12.
31492
31493It's usually best to use this form of @code{calc-eval} unless your
31494program actually considers the interaction with Calc's mode settings
31495to be a feature. This will avoid all sorts of potential ``gotchas'';
31496consider what happens with @samp{(calc-eval "sqrt(2)" 'num)}
31497when the user has left Calc in symbolic mode or no-simplify mode.
31498
31499As another example, @samp{(equal (calc-eval '("$<$$") nil a b) "1")}
31500checks if the number in string @cite{a} is less than the one in
31501string @cite{b}. Without using a list, the integer 1 might
31502come out in a variety of formats which would be hard to test for
31503conveniently: @code{"1"}, @code{"8#1"}, @code{"00001"}. (But
31504see ``Predicates'' mode, below.)
31505
31506@ifinfo
31507@example
31508
31509@end example
31510@end ifinfo
31511@subsubsection Raw Numbers
31512
31513@noindent
31514Normally all input and output for @code{calc-eval} is done with strings.
31515You can do arithmetic with, say, @samp{(calc-eval "$+$$" nil a b)}
31516in place of @samp{(+ a b)}, but this is very inefficient since the
31517numbers must be converted to and from string format as they are passed
31518from one @code{calc-eval} to the next.
31519
31520If the separator is the symbol @code{raw}, the result will be returned
31521as a raw Calc data structure rather than a string. You can read about
31522how these objects look in the following sections, but usually you can
31523treat them as ``black box'' objects with no important internal
31524structure.
31525
31526There is also a @code{rawnum} symbol, which is a combination of
31527@code{raw} (returning a raw Calc object) and @code{num} (signalling
31528an error if that object is not a constant).
31529
31530You can pass a raw Calc object to @code{calc-eval} in place of a
31531string, either as the formula itself or as one of the @samp{$}
31532arguments. Thus @samp{(calc-eval "$+$$" 'raw a b)} is an
31533addition function that operates on raw Calc objects. Of course
31534in this case it would be easier to call the low-level @code{math-add}
31535function in Calc, if you can remember its name.
31536
31537In particular, note that a plain Lisp integer is acceptable to Calc
31538as a raw object. (All Lisp integers are accepted on input, but
31539integers of more than six decimal digits are converted to ``big-integer''
31540form for output. @xref{Data Type Formats}.)
31541
31542When it comes time to display the object, just use @samp{(calc-eval a)}
31543to format it as a string.
31544
31545It is an error if the input expression evaluates to a list of
31546values. The separator symbol @code{list} is like @code{raw}
31547except that it returns a list of one or more raw Calc objects.
31548
31549Note that a Lisp string is not a valid Calc object, nor is a list
31550containing a string. Thus you can still safely distinguish all the
31551various kinds of error returns discussed above.
31552
31553@ifinfo
31554@example
31555
31556@end example
31557@end ifinfo
31558@subsubsection Predicates
31559
31560@noindent
31561If the separator symbol is @code{pred}, the result of the formula is
31562treated as a true/false value; @code{calc-eval} returns @code{t} or
31563@code{nil}, respectively. A value is considered ``true'' if it is a
31564non-zero number, or false if it is zero or if it is not a number.
31565
31566For example, @samp{(calc-eval "$<$$" 'pred a b)} tests whether
31567one value is less than another.
31568
31569As usual, it is also possible for @code{calc-eval} to return one of
31570the error indicators described above. Lisp will interpret such an
31571indicator as ``true'' if you don't check for it explicitly. If you
31572wish to have an error register as ``false'', use something like
31573@samp{(eq (calc-eval ...) t)}.
31574
31575@ifinfo
31576@example
31577
31578@end example
31579@end ifinfo
31580@subsubsection Variable Values
31581
31582@noindent
31583Variables in the formula passed to @code{calc-eval} are not normally
31584replaced by their values. If you wish this, you can use the
31585@code{evalv} function (@pxref{Algebraic Manipulation}). For example,
31586if 4 is stored in Calc variable @code{a} (i.e., in Lisp variable
31587@code{var-a}), then @samp{(calc-eval "a+pi")} will return the
31588formula @code{"a + pi"}, but @samp{(calc-eval "evalv(a+pi)")}
31589will return @code{"7.14159265359"}.
31590
31591To store in a Calc variable, just use @code{setq} to store in the
31592corresponding Lisp variable. (This is obtained by prepending
31593@samp{var-} to the Calc variable name.) Calc routines will
31594understand either string or raw form values stored in variables,
31595although raw data objects are much more efficient. For example,
31596to increment the Calc variable @code{a}:
31597
31598@example
31599(setq var-a (calc-eval "evalv(a+1)" 'raw))
31600@end example
31601
31602@ifinfo
31603@example
31604
31605@end example
31606@end ifinfo
31607@subsubsection Stack Access
31608
31609@noindent
31610If the separator symbol is @code{push}, the formula argument is
31611evaluated (with possible @samp{$} expansions, as usual). The
31612result is pushed onto the Calc stack. The return value is @code{nil}
31613(unless there is an error from evaluating the formula, in which
31614case the return value depends on @code{calc-eval-error} in the
31615usual way).
31616
31617If the separator symbol is @code{pop}, the first argument to
31618@code{calc-eval} must be an integer instead of a string. That
31619many values are popped from the stack and thrown away. A negative
31620argument deletes the entry at that stack level. The return value
31621is the number of elements remaining in the stack after popping;
31622@samp{(calc-eval 0 'pop)} is a good way to measure the size of
31623the stack.
31624
31625If the separator symbol is @code{top}, the first argument to
31626@code{calc-eval} must again be an integer. The value at that
31627stack level is formatted as a string and returned. Thus
31628@samp{(calc-eval 1 'top)} returns the top-of-stack value. If the
31629integer is out of range, @code{nil} is returned.
31630
31631The separator symbol @code{rawtop} is just like @code{top} except
31632that the stack entry is returned as a raw Calc object instead of
31633as a string.
31634
31635In all of these cases the first argument can be made a list in
31636order to force the default mode settings, as described above.
31637Thus @samp{(calc-eval '(2 calc-number-radix 16) 'top)} returns the
31638second-to-top stack entry, formatted as a string using the default
31639instead of current display modes, except that the radix is
31640hexadecimal instead of decimal.
31641
31642It is, of course, polite to put the Calc stack back the way you
31643found it when you are done, unless the user of your program is
31644actually expecting it to affect the stack.
31645
31646Note that you do not actually have to switch into the @samp{*Calculator*}
31647buffer in order to use @code{calc-eval}; it temporarily switches into
31648the stack buffer if necessary.
31649
31650@ifinfo
31651@example
31652
31653@end example
31654@end ifinfo
31655@subsubsection Keyboard Macros
31656
31657@noindent
31658If the separator symbol is @code{macro}, the first argument must be a
31659string of characters which Calc can execute as a sequence of keystrokes.
31660This switches into the Calc buffer for the duration of the macro.
31661For example, @samp{(calc-eval "vx5\rVR+" 'macro)} pushes the
31662vector @samp{[1,2,3,4,5]} on the stack and then replaces it
31663with the sum of those numbers. Note that @samp{\r} is the Lisp
31664notation for the carriage-return, @key{RET}, character.
31665
31666If your keyboard macro wishes to pop the stack, @samp{\C-d} is
31667safer than @samp{\177} (the @key{DEL} character) because some
31668installations may have switched the meanings of @key{DEL} and
31669@kbd{C-h}. Calc always interprets @kbd{C-d} as a synonym for
31670``pop-stack'' regardless of key mapping.
31671
31672If you provide a third argument to @code{calc-eval}, evaluation
31673of the keyboard macro will leave a record in the Trail using
31674that argument as a tag string. Normally the Trail is unaffected.
31675
31676The return value in this case is always @code{nil}.
31677
31678@ifinfo
31679@example
31680
31681@end example
31682@end ifinfo
31683@subsubsection Lisp Evaluation
31684
31685@noindent
31686Finally, if the separator symbol is @code{eval}, then the Lisp
31687@code{eval} function is called on the first argument, which must
31688be a Lisp expression rather than a Calc formula. Remember to
31689quote the expression so that it is not evaluated until inside
31690@code{calc-eval}.
31691
31692The difference from plain @code{eval} is that @code{calc-eval}
31693switches to the Calc buffer before evaluating the expression.
31694For example, @samp{(calc-eval '(setq calc-internal-prec 17) 'eval)}
31695will correctly affect the buffer-local Calc precision variable.
31696
31697An alternative would be @samp{(calc-eval '(calc-precision 17) 'eval)}.
31698This is evaluating a call to the function that is normally invoked
31699by the @kbd{p} key, giving it 17 as its ``numeric prefix argument.''
31700Note that this function will leave a message in the echo area as
31701a side effect. Also, all Calc functions switch to the Calc buffer
31702automatically if not invoked from there, so the above call is
31703also equivalent to @samp{(calc-precision 17)} by itself.
31704In all cases, Calc uses @code{save-excursion} to switch back to
31705your original buffer when it is done.
31706
31707As usual the first argument can be a list that begins with a Lisp
31708expression to use default instead of current mode settings.
31709
31710The result of @code{calc-eval} in this usage is just the result
31711returned by the evaluated Lisp expression.
31712
31713@ifinfo
31714@example
31715
31716@end example
31717@end ifinfo
31718@subsubsection Example
31719
31720@noindent
31721@findex convert-temp
31722Here is a sample Emacs command that uses @code{calc-eval}. Suppose
31723you have a document with lots of references to temperatures on the
31724Fahrenheit scale, say ``98.6 F'', and you wish to convert these
31725references to Centigrade. The following command does this conversion.
31726Place the Emacs cursor right after the letter ``F'' and invoke the
31727command to change ``98.6 F'' to ``37 C''. Or, if the temperature is
31728already in Centigrade form, the command changes it back to Fahrenheit.
31729
31730@example
31731(defun convert-temp ()
31732 (interactive)
31733 (save-excursion
31734 (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
31735 (let* ((top1 (match-beginning 1))
31736 (bot1 (match-end 1))
31737 (number (buffer-substring top1 bot1))
31738 (top2 (match-beginning 2))
31739 (bot2 (match-end 2))
31740 (type (buffer-substring top2 bot2)))
31741 (if (equal type "F")
31742 (setq type "C"
31743 number (calc-eval "($ - 32)*5/9" nil number))
31744 (setq type "F"
31745 number (calc-eval "$*9/5 + 32" nil number)))
31746 (goto-char top2)
31747 (delete-region top2 bot2)
31748 (insert-before-markers type)
31749 (goto-char top1)
31750 (delete-region top1 bot1)
31751 (if (string-match "\\.$" number) ; change "37." to "37"
31752 (setq number (substring number 0 -1)))
31753 (insert number))))
31754@end example
31755
31756Note the use of @code{insert-before-markers} when changing between
31757``F'' and ``C'', so that the character winds up before the cursor
31758instead of after it.
31759
31760@node Internals, , Calling Calc from Your Programs, Lisp Definitions
31761@subsection Calculator Internals
31762
31763@noindent
31764This section describes the Lisp functions defined by the Calculator that
31765may be of use to user-written Calculator programs (as described in the
31766rest of this chapter). These functions are shown by their names as they
31767conventionally appear in @code{defmath}. Their full Lisp names are
31768generally gotten by prepending @samp{calcFunc-} or @samp{math-} to their
31769apparent names. (Names that begin with @samp{calc-} are already in
31770their full Lisp form.) You can use the actual full names instead if you
31771prefer them, or if you are calling these functions from regular Lisp.
31772
31773The functions described here are scattered throughout the various
31774Calc component files. Note that @file{calc.el} includes @code{autoload}s
31775for only a few component files; when Calc wants to call an advanced
31776function it calls @samp{(calc-extensions)} first; this function
31777autoloads @file{calc-ext.el}, which in turn autoloads all the functions
31778in the remaining component files.
31779
31780Because @code{defmath} itself uses the extensions, user-written code
31781generally always executes with the extensions already loaded, so
31782normally you can use any Calc function and be confident that it will
31783be autoloaded for you when necessary. If you are doing something
31784special, check carefully to make sure each function you are using is
31785from @file{calc.el} or its components, and call @samp{(calc-extensions)}
31786before using any function based in @file{calc-ext.el} if you can't
31787prove this file will already be loaded.
31788
31789@menu
31790* Data Type Formats::
31791* Interactive Lisp Functions::
31792* Stack Lisp Functions::
31793* Predicates::
31794* Computational Lisp Functions::
31795* Vector Lisp Functions::
31796* Symbolic Lisp Functions::
31797* Formatting Lisp Functions::
31798* Hooks::
31799@end menu
31800
31801@node Data Type Formats, Interactive Lisp Functions, Internals, Internals
31802@subsubsection Data Type Formats
31803
31804@noindent
31805Integers are stored in either of two ways, depending on their magnitude.
31806Integers less than one million in absolute value are stored as standard
31807Lisp integers. This is the only storage format for Calc data objects
31808which is not a Lisp list.
31809
31810Large integers are stored as lists of the form @samp{(bigpos @var{d0}
31811@var{d1} @var{d2} @dots{})} for positive integers 1000000 or more, or
31812@samp{(bigneg @var{d0} @var{d1} @var{d2} @dots{})} for negative integers
31813@i{-1000000} or less. Each @var{d} is a base-1000 ``digit,'' a Lisp integer
31814from 0 to 999. The least significant digit is @var{d0}; the last digit,
31815@var{dn}, which is always nonzero, is the most significant digit. For
31816example, the integer @i{-12345678} is stored as @samp{(bigneg 678 345 12)}.
31817
31818The distinction between small and large integers is entirely hidden from
31819the user. In @code{defmath} definitions, the Lisp predicate @code{integerp}
31820returns true for either kind of integer, and in general both big and small
31821integers are accepted anywhere the word ``integer'' is used in this manual.
31822If the distinction must be made, native Lisp integers are called @dfn{fixnums}
31823and large integers are called @dfn{bignums}.
31824
31825Fractions are stored as a list of the form, @samp{(frac @var{n} @var{d})}
31826where @var{n} is an integer (big or small) numerator, @var{d} is an
31827integer denominator greater than one, and @var{n} and @var{d} are relatively
31828prime. Note that fractions where @var{d} is one are automatically converted
31829to plain integers by all math routines; fractions where @var{d} is negative
31830are normalized by negating the numerator and denominator.
31831
31832Floating-point numbers are stored in the form, @samp{(float @var{mant}
31833@var{exp})}, where @var{mant} (the ``mantissa'') is an integer less than
31834@samp{10^@var{p}} in absolute value (@var{p} represents the current
31835precision), and @var{exp} (the ``exponent'') is a fixnum. The value of
31836the float is @samp{@var{mant} * 10^@var{exp}}. For example, the number
31837@i{-3.14} is stored as @samp{(float -314 -2) = -314*10^-2}. Other constraints
31838are that the number 0.0 is always stored as @samp{(float 0 0)}, and,
31839except for the 0.0 case, the rightmost base-10 digit of @var{mant} is
31840always nonzero. (If the rightmost digit is zero, the number is
31841rearranged by dividing @var{mant} by ten and incrementing @var{exp}.)@refill
31842
31843Rectangular complex numbers are stored in the form @samp{(cplx @var{re}
31844@var{im})}, where @var{re} and @var{im} are each real numbers, either
31845integers, fractions, or floats. The value is @samp{@var{re} + @var{im}i}.
31846The @var{im} part is nonzero; complex numbers with zero imaginary
31847components are converted to real numbers automatically.@refill
31848
31849Polar complex numbers are stored in the form @samp{(polar @var{r}
31850@var{theta})}, where @var{r} is a positive real value and @var{theta}
31851is a real value or HMS form representing an angle. This angle is
31852usually normalized to lie in the interval @samp{(-180 ..@: 180)} degrees,
31853or @samp{(-pi ..@: pi)} radians, according to the current angular mode.
31854If the angle is 0 the value is converted to a real number automatically.
31855(If the angle is 180 degrees, the value is usually also converted to a
31856negative real number.)@refill
31857
31858Hours-minutes-seconds forms are stored as @samp{(hms @var{h} @var{m}
31859@var{s})}, where @var{h} is an integer or an integer-valued float (i.e.,
31860a float with @samp{@var{exp} >= 0}), @var{m} is an integer or integer-valued
31861float in the range @w{@samp{[0 ..@: 60)}}, and @var{s} is any real number
31862in the range @samp{[0 ..@: 60)}.@refill
31863
31864Date forms are stored as @samp{(date @var{n})}, where @var{n} is
31865a real number that counts days since midnight on the morning of
31866January 1, 1 AD. If @var{n} is an integer, this is a pure date
31867form. If @var{n} is a fraction or float, this is a date/time form.
31868
31869Modulo forms are stored as @samp{(mod @var{n} @var{m})}, where @var{m} is a
31870positive real number or HMS form, and @var{n} is a real number or HMS
31871form in the range @samp{[0 ..@: @var{m})}.
31872
31873Error forms are stored as @samp{(sdev @var{x} @var{sigma})}, where @var{x}
31874is the mean value and @var{sigma} is the standard deviation. Each
31875component is either a number, an HMS form, or a symbolic object
31876(a variable or function call). If @var{sigma} is zero, the value is
31877converted to a plain real number. If @var{sigma} is negative or
31878complex, it is automatically normalized to be a positive real.
31879
31880Interval forms are stored as @samp{(intv @var{mask} @var{lo} @var{hi})},
31881where @var{mask} is one of the integers 0, 1, 2, or 3, and @var{lo} and
31882@var{hi} are real numbers, HMS forms, or symbolic objects. The @var{mask}
31883is a binary integer where 1 represents the fact that the interval is
31884closed on the high end, and 2 represents the fact that it is closed on
31885the low end. (Thus 3 represents a fully closed interval.) The interval
31886@w{@samp{(intv 3 @var{x} @var{x})}} is converted to the plain number @var{x};
31887intervals @samp{(intv @var{mask} @var{x} @var{x})} for any other @var{mask}
31888represent empty intervals. If @var{hi} is less than @var{lo}, the interval
31889is converted to a standard empty interval by replacing @var{hi} with @var{lo}.
31890
31891Vectors are stored as @samp{(vec @var{v1} @var{v2} @dots{})}, where @var{v1}
31892is the first element of the vector, @var{v2} is the second, and so on.
31893An empty vector is stored as @samp{(vec)}. A matrix is simply a vector
31894where all @var{v}'s are themselves vectors of equal lengths. Note that
31895Calc vectors are unrelated to the Emacs Lisp ``vector'' type, which is
31896generally unused by Calc data structures.
31897
31898Variables are stored as @samp{(var @var{name} @var{sym})}, where
31899@var{name} is a Lisp symbol whose print name is used as the visible name
31900of the variable, and @var{sym} is a Lisp symbol in which the variable's
31901value is actually stored. Thus, @samp{(var pi var-pi)} represents the
31902special constant @samp{pi}. Almost always, the form is @samp{(var
31903@var{v} var-@var{v})}. If the variable name was entered with @code{#}
31904signs (which are converted to hyphens internally), the form is
31905@samp{(var @var{u} @var{v})}, where @var{u} is a symbol whose name
31906contains @code{#} characters, and @var{v} is a symbol that contains
31907@code{-} characters instead. The value of a variable is the Calc
31908object stored in its @var{sym} symbol's value cell. If the symbol's
31909value cell is void or if it contains @code{nil}, the variable has no
31910value. Special constants have the form @samp{(special-const
31911@var{value})} stored in their value cell, where @var{value} is a formula
31912which is evaluated when the constant's value is requested. Variables
31913which represent units are not stored in any special way; they are units
31914only because their names appear in the units table. If the value
31915cell contains a string, it is parsed to get the variable's value when
31916the variable is used.@refill
31917
31918A Lisp list with any other symbol as the first element is a function call.
31919The symbols @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^},
31920and @code{|} represent special binary operators; these lists are always
31921of the form @samp{(@var{op} @var{lhs} @var{rhs})} where @var{lhs} is the
31922sub-formula on the lefthand side and @var{rhs} is the sub-formula on the
31923right. The symbol @code{neg} represents unary negation; this list is always
31924of the form @samp{(neg @var{arg})}. Any other symbol @var{func} represents a
31925function that would be displayed in function-call notation; the symbol
31926@var{func} is in general always of the form @samp{calcFunc-@var{name}}.
31927The function cell of the symbol @var{func} should contain a Lisp function
31928for evaluating a call to @var{func}. This function is passed the remaining
31929elements of the list (themselves already evaluated) as arguments; such
31930functions should return @code{nil} or call @code{reject-arg} to signify
31931that they should be left in symbolic form, or they should return a Calc
31932object which represents their value, or a list of such objects if they
31933wish to return multiple values. (The latter case is allowed only for
31934functions which are the outer-level call in an expression whose value is
31935about to be pushed on the stack; this feature is considered obsolete
31936and is not used by any built-in Calc functions.)@refill
31937
31938@node Interactive Lisp Functions, Stack Lisp Functions, Data Type Formats, Internals
31939@subsubsection Interactive Functions
31940
31941@noindent
31942The functions described here are used in implementing interactive Calc
31943commands. Note that this list is not exhaustive! If there is an
31944existing command that behaves similarly to the one you want to define,
31945you may find helpful tricks by checking the source code for that command.
31946
31947@defun calc-set-command-flag flag
31948Set the command flag @var{flag}. This is generally a Lisp symbol, but
31949may in fact be anything. The effect is to add @var{flag} to the list
31950stored in the variable @code{calc-command-flags}, unless it is already
31951there. @xref{Defining Simple Commands}.
31952@end defun
31953
31954@defun calc-clear-command-flag flag
31955If @var{flag} appears among the list of currently-set command flags,
31956remove it from that list.
31957@end defun
31958
31959@defun calc-record-undo rec
31960Add the ``undo record'' @var{rec} to the list of steps to take if the
31961current operation should need to be undone. Stack push and pop functions
31962automatically call @code{calc-record-undo}, so the kinds of undo records
31963you might need to create take the form @samp{(set @var{sym} @var{value})},
31964which says that the Lisp variable @var{sym} was changed and had previously
31965contained @var{value}; @samp{(store @var{var} @var{value})} which says that
31966the Calc variable @var{var} (a string which is the name of the symbol that
31967contains the variable's value) was stored and its previous value was
31968@var{value} (either a Calc data object, or @code{nil} if the variable was
31969previously void); or @samp{(eval @var{undo} @var{redo} @var{args} @dots{})},
31970which means that to undo requires calling the function @samp{(@var{undo}
31971@var{args} @dots{})} and, if the undo is later redone, calling
31972@samp{(@var{redo} @var{args} @dots{})}.@refill
31973@end defun
31974
31975@defun calc-record-why msg args
31976Record the error or warning message @var{msg}, which is normally a string.
31977This message will be replayed if the user types @kbd{w} (@code{calc-why});
31978if the message string begins with a @samp{*}, it is considered important
31979enough to display even if the user doesn't type @kbd{w}. If one or more
31980@var{args} are present, the displayed message will be of the form,
31981@samp{@var{msg}: @var{arg1}, @var{arg2}, @dots{}}, where the arguments are
31982formatted on the assumption that they are either strings or Calc objects of
31983some sort. If @var{msg} is a symbol, it is the name of a Calc predicate
31984(such as @code{integerp} or @code{numvecp}) which the arguments did not
31985satisfy; it is expanded to a suitable string such as ``Expected an
31986integer.'' The @code{reject-arg} function calls @code{calc-record-why}
31987automatically; @pxref{Predicates}.@refill
31988@end defun
31989
31990@defun calc-is-inverse
31991This predicate returns true if the current command is inverse,
31992i.e., if the Inverse (@kbd{I} key) flag was set.
31993@end defun
31994
31995@defun calc-is-hyperbolic
31996This predicate is the analogous function for the @kbd{H} key.
31997@end defun
31998
31999@node Stack Lisp Functions, Predicates, Interactive Lisp Functions, Internals
32000@subsubsection Stack-Oriented Functions
32001
32002@noindent
32003The functions described here perform various operations on the Calc
32004stack and trail. They are to be used in interactive Calc commands.
32005
32006@defun calc-push-list vals n
32007Push the Calc objects in list @var{vals} onto the stack at stack level
32008@var{n}. If @var{n} is omitted it defaults to 1, so that the elements
32009are pushed at the top of the stack. If @var{n} is greater than 1, the
32010elements will be inserted into the stack so that the last element will
32011end up at level @var{n}, the next-to-last at level @var{n}+1, etc.
32012The elements of @var{vals} are assumed to be valid Calc objects, and
32013are not evaluated, rounded, or renormalized in any way. If @var{vals}
32014is an empty list, nothing happens.@refill
32015
32016The stack elements are pushed without any sub-formula selections.
32017You can give an optional third argument to this function, which must
32018be a list the same size as @var{vals} of selections. Each selection
32019must be @code{eq} to some sub-formula of the corresponding formula
32020in @var{vals}, or @code{nil} if that formula should have no selection.
32021@end defun
32022
32023@defun calc-top-list n m
32024Return a list of the @var{n} objects starting at level @var{m} of the
32025stack. If @var{m} is omitted it defaults to 1, so that the elements are
32026taken from the top of the stack. If @var{n} is omitted, it also
32027defaults to 1, so that the top stack element (in the form of a
32028one-element list) is returned. If @var{m} is greater than 1, the
32029@var{m}th stack element will be at the end of the list, the @var{m}+1st
32030element will be next-to-last, etc. If @var{n} or @var{m} are out of
32031range, the command is aborted with a suitable error message. If @var{n}
32032is zero, the function returns an empty list. The stack elements are not
32033evaluated, rounded, or renormalized.@refill
32034
32035If any stack elements contain selections, and selections have not
32036been disabled by the @kbd{j e} (@code{calc-enable-selections}) command,
32037this function returns the selected portions rather than the entire
32038stack elements. It can be given a third ``selection-mode'' argument
32039which selects other behaviors. If it is the symbol @code{t}, then
32040a selection in any of the requested stack elements produces an
32041``illegal operation on selections'' error. If it is the symbol @code{full},
32042the whole stack entry is always returned regardless of selections.
32043If it is the symbol @code{sel}, the selected portion is always returned,
32044or @code{nil} if there is no selection. (This mode ignores the @kbd{j e}
32045command.) If the symbol is @code{entry}, the complete stack entry in
32046list form is returned; the first element of this list will be the whole
32047formula, and the third element will be the selection (or @code{nil}).
32048@end defun
32049
32050@defun calc-pop-stack n m
32051Remove the specified elements from the stack. The parameters @var{n}
32052and @var{m} are defined the same as for @code{calc-top-list}. The return
32053value of @code{calc-pop-stack} is uninteresting.
32054
32055If there are any selected sub-formulas among the popped elements, and
32056@kbd{j e} has not been used to disable selections, this produces an
32057error without changing the stack. If you supply an optional third
32058argument of @code{t}, the stack elements are popped even if they
32059contain selections.
32060@end defun
32061
32062@defun calc-record-list vals tag
32063This function records one or more results in the trail. The @var{vals}
32064are a list of strings or Calc objects. The @var{tag} is the four-character
32065tag string to identify the values. If @var{tag} is omitted, a blank tag
32066will be used.
32067@end defun
32068
32069@defun calc-normalize n
32070This function takes a Calc object and ``normalizes'' it. At the very
32071least this involves re-rounding floating-point values according to the
32072current precision and other similar jobs. Also, unless the user has
32073selected no-simplify mode (@pxref{Simplification Modes}), this involves
32074actually evaluating a formula object by executing the function calls
32075it contains, and possibly also doing algebraic simplification, etc.
32076@end defun
32077
32078@defun calc-top-list-n n m
32079This function is identical to @code{calc-top-list}, except that it calls
32080@code{calc-normalize} on the values that it takes from the stack. They
32081are also passed through @code{check-complete}, so that incomplete
32082objects will be rejected with an error message. All computational
32083commands should use this in preference to @code{calc-top-list}; the only
32084standard Calc commands that operate on the stack without normalizing
32085are stack management commands like @code{calc-enter} and @code{calc-roll-up}.
32086This function accepts the same optional selection-mode argument as
32087@code{calc-top-list}.
32088@end defun
32089
32090@defun calc-top-n m
32091This function is a convenient form of @code{calc-top-list-n} in which only
32092a single element of the stack is taken and returned, rather than a list
32093of elements. This also accepts an optional selection-mode argument.
32094@end defun
32095
32096@defun calc-enter-result n tag vals
32097This function is a convenient interface to most of the above functions.
32098The @var{vals} argument should be either a single Calc object, or a list
32099of Calc objects; the object or objects are normalized, and the top @var{n}
32100stack entries are replaced by the normalized objects. If @var{tag} is
32101non-@code{nil}, the normalized objects are also recorded in the trail.
32102A typical stack-based computational command would take the form,
32103
32104@smallexample
32105(calc-enter-result @var{n} @var{tag} (cons 'calcFunc-@var{func}
32106 (calc-top-list-n @var{n})))
32107@end smallexample
32108
32109If any of the @var{n} stack elements replaced contain sub-formula
32110selections, and selections have not been disabled by @kbd{j e},
32111this function takes one of two courses of action. If @var{n} is
32112equal to the number of elements in @var{vals}, then each element of
32113@var{vals} is spliced into the corresponding selection; this is what
32114happens when you use the @key{TAB} key, or when you use a unary
32115arithmetic operation like @code{sqrt}. If @var{vals} has only one
32116element but @var{n} is greater than one, there must be only one
32117selection among the top @var{n} stack elements; the element from
32118@var{vals} is spliced into that selection. This is what happens when
32119you use a binary arithmetic operation like @kbd{+}. Any other
32120combination of @var{n} and @var{vals} is an error when selections
32121are present.
32122@end defun
32123
32124@defun calc-unary-op tag func arg
32125This function implements a unary operator that allows a numeric prefix
32126argument to apply the operator over many stack entries. If the prefix
32127argument @var{arg} is @code{nil}, this uses @code{calc-enter-result}
32128as outlined above. Otherwise, it maps the function over several stack
32129elements; @pxref{Prefix Arguments}. For example,@refill
32130
32131@smallexample
32132(defun calc-zeta (arg)
32133 (interactive "P")
32134 (calc-unary-op "zeta" 'calcFunc-zeta arg))
32135@end smallexample
32136@end defun
32137
32138@defun calc-binary-op tag func arg ident unary
32139This function implements a binary operator, analogously to
32140@code{calc-unary-op}. The optional @var{ident} and @var{unary}
32141arguments specify the behavior when the prefix argument is zero or
32142one, respectively. If the prefix is zero, the value @var{ident}
32143is pushed onto the stack, if specified, otherwise an error message
32144is displayed. If the prefix is one, the unary function @var{unary}
32145is applied to the top stack element, or, if @var{unary} is not
32146specified, nothing happens. When the argument is two or more,
32147the binary function @var{func} is reduced across the top @var{arg}
32148stack elements; when the argument is negative, the function is
32149mapped between the next-to-top @i{-@var{arg}} stack elements and the
32150top element.@refill
32151@end defun
32152
32153@defun calc-stack-size
32154Return the number of elements on the stack as an integer. This count
32155does not include elements that have been temporarily hidden by stack
32156truncation; @pxref{Truncating the Stack}.
32157@end defun
32158
32159@defun calc-cursor-stack-index n
32160Move the point to the @var{n}th stack entry. If @var{n} is zero, this
32161will be the @samp{.} line. If @var{n} is from 1 to the current stack size,
32162this will be the beginning of the first line of that stack entry's display.
32163If line numbers are enabled, this will move to the first character of the
32164line number, not the stack entry itself.@refill
32165@end defun
32166
32167@defun calc-substack-height n
32168Return the number of lines between the beginning of the @var{n}th stack
32169entry and the bottom of the buffer. If @var{n} is zero, this
32170will be one (assuming no stack truncation). If all stack entries are
32171one line long (i.e., no matrices are displayed), the return value will
32172be equal @var{n}+1 as long as @var{n} is in range. (Note that in Big
32173mode, the return value includes the blank lines that separate stack
32174entries.)@refill
32175@end defun
32176
32177@defun calc-refresh
32178Erase the @code{*Calculator*} buffer and reformat its contents from memory.
32179This must be called after changing any parameter, such as the current
32180display radix, which might change the appearance of existing stack
32181entries. (During a keyboard macro invoked by the @kbd{X} key, refreshing
32182is suppressed, but a flag is set so that the entire stack will be refreshed
32183rather than just the top few elements when the macro finishes.)@refill
32184@end defun
32185
32186@node Predicates, Computational Lisp Functions, Stack Lisp Functions, Internals
32187@subsubsection Predicates
32188
32189@noindent
32190The functions described here are predicates, that is, they return a
32191true/false value where @code{nil} means false and anything else means
32192true. These predicates are expanded by @code{defmath}, for example,
32193from @code{zerop} to @code{math-zerop}. In many cases they correspond
32194to native Lisp functions by the same name, but are extended to cover
32195the full range of Calc data types.
32196
32197@defun zerop x
32198Returns true if @var{x} is numerically zero, in any of the Calc data
32199types. (Note that for some types, such as error forms and intervals,
32200it never makes sense to return true.) In @code{defmath}, the expression
32201@samp{(= x 0)} will automatically be converted to @samp{(math-zerop x)},
32202and @samp{(/= x 0)} will be converted to @samp{(not (math-zerop x))}.
32203@end defun
32204
32205@defun negp x
32206Returns true if @var{x} is negative. This accepts negative real numbers
32207of various types, negative HMS and date forms, and intervals in which
32208all included values are negative. In @code{defmath}, the expression
32209@samp{(< x 0)} will automatically be converted to @samp{(math-negp x)},
32210and @samp{(>= x 0)} will be converted to @samp{(not (math-negp x))}.
32211@end defun
32212
32213@defun posp x
32214Returns true if @var{x} is positive (and non-zero). For complex
32215numbers, none of these three predicates will return true.
32216@end defun
32217
32218@defun looks-negp x
32219Returns true if @var{x} is ``negative-looking.'' This returns true if
32220@var{x} is a negative number, or a formula with a leading minus sign
32221such as @samp{-a/b}. In other words, this is an object which can be
32222made simpler by calling @code{(- @var{x})}.
32223@end defun
32224
32225@defun integerp x
32226Returns true if @var{x} is an integer of any size.
32227@end defun
32228
32229@defun fixnump x
32230Returns true if @var{x} is a native Lisp integer.
32231@end defun
32232
32233@defun natnump x
32234Returns true if @var{x} is a nonnegative integer of any size.
32235@end defun
32236
32237@defun fixnatnump x
32238Returns true if @var{x} is a nonnegative Lisp integer.
32239@end defun
32240
32241@defun num-integerp x
32242Returns true if @var{x} is numerically an integer, i.e., either a
32243true integer or a float with no significant digits to the right of
32244the decimal point.
32245@end defun
32246
32247@defun messy-integerp x
32248Returns true if @var{x} is numerically, but not literally, an integer.
32249A value is @code{num-integerp} if it is @code{integerp} or
32250@code{messy-integerp} (but it is never both at once).
32251@end defun
32252
32253@defun num-natnump x
32254Returns true if @var{x} is numerically a nonnegative integer.
32255@end defun
32256
32257@defun evenp x
32258Returns true if @var{x} is an even integer.
32259@end defun
32260
32261@defun looks-evenp x
32262Returns true if @var{x} is an even integer, or a formula with a leading
32263multiplicative coefficient which is an even integer.
32264@end defun
32265
32266@defun oddp x
32267Returns true if @var{x} is an odd integer.
32268@end defun
32269
32270@defun ratp x
32271Returns true if @var{x} is a rational number, i.e., an integer or a
32272fraction.
32273@end defun
32274
32275@defun realp x
32276Returns true if @var{x} is a real number, i.e., an integer, fraction,
32277or floating-point number.
32278@end defun
32279
32280@defun anglep x
32281Returns true if @var{x} is a real number or HMS form.
32282@end defun
32283
32284@defun floatp x
32285Returns true if @var{x} is a float, or a complex number, error form,
32286interval, date form, or modulo form in which at least one component
32287is a float.
32288@end defun
32289
32290@defun complexp x
32291Returns true if @var{x} is a rectangular or polar complex number
32292(but not a real number).
32293@end defun
32294
32295@defun rect-complexp x
32296Returns true if @var{x} is a rectangular complex number.
32297@end defun
32298
32299@defun polar-complexp x
32300Returns true if @var{x} is a polar complex number.
32301@end defun
32302
32303@defun numberp x
32304Returns true if @var{x} is a real number or a complex number.
32305@end defun
32306
32307@defun scalarp x
32308Returns true if @var{x} is a real or complex number or an HMS form.
32309@end defun
32310
32311@defun vectorp x
32312Returns true if @var{x} is a vector (this simply checks if its argument
32313is a list whose first element is the symbol @code{vec}).
32314@end defun
32315
32316@defun numvecp x
32317Returns true if @var{x} is a number or vector.
32318@end defun
32319
32320@defun matrixp x
32321Returns true if @var{x} is a matrix, i.e., a vector of one or more vectors,
32322all of the same size.
32323@end defun
32324
32325@defun square-matrixp x
32326Returns true if @var{x} is a square matrix.
32327@end defun
32328
32329@defun objectp x
32330Returns true if @var{x} is any numeric Calc object, including real and
32331complex numbers, HMS forms, date forms, error forms, intervals, and
32332modulo forms. (Note that error forms and intervals may include formulas
32333as their components; see @code{constp} below.)
32334@end defun
32335
32336@defun objvecp x
32337Returns true if @var{x} is an object or a vector. This also accepts
32338incomplete objects, but it rejects variables and formulas (except as
32339mentioned above for @code{objectp}).
32340@end defun
32341
32342@defun primp x
32343Returns true if @var{x} is a ``primitive'' or ``atomic'' Calc object,
32344i.e., one whose components cannot be regarded as sub-formulas. This
32345includes variables, and all @code{objectp} types except error forms
32346and intervals.
32347@end defun
32348
32349@defun constp x
32350Returns true if @var{x} is constant, i.e., a real or complex number,
32351HMS form, date form, or error form, interval, or vector all of whose
32352components are @code{constp}.
32353@end defun
32354
32355@defun lessp x y
32356Returns true if @var{x} is numerically less than @var{y}. Returns false
32357if @var{x} is greater than or equal to @var{y}, or if the order is
32358undefined or cannot be determined. Generally speaking, this works
32359by checking whether @samp{@var{x} - @var{y}} is @code{negp}. In
32360@code{defmath}, the expression @samp{(< x y)} will automatically be
32361converted to @samp{(lessp x y)}; expressions involving @code{>}, @code{<=},
32362and @code{>=} are similarly converted in terms of @code{lessp}.@refill
32363@end defun
32364
32365@defun beforep x y
32366Returns true if @var{x} comes before @var{y} in a canonical ordering
32367of Calc objects. If @var{x} and @var{y} are both real numbers, this
32368will be the same as @code{lessp}. But whereas @code{lessp} considers
32369other types of objects to be unordered, @code{beforep} puts any two
32370objects into a definite, consistent order. The @code{beforep}
32371function is used by the @kbd{V S} vector-sorting command, and also
32372by @kbd{a s} to put the terms of a product into canonical order:
32373This allows @samp{x y + y x} to be simplified easily to @samp{2 x y}.
32374@end defun
32375
32376@defun equal x y
32377This is the standard Lisp @code{equal} predicate; it returns true if
32378@var{x} and @var{y} are structurally identical. This is the usual way
32379to compare numbers for equality, but note that @code{equal} will treat
323800 and 0.0 as different.
32381@end defun
32382
32383@defun math-equal x y
32384Returns true if @var{x} and @var{y} are numerically equal, either because
32385they are @code{equal}, or because their difference is @code{zerop}. In
32386@code{defmath}, the expression @samp{(= x y)} will automatically be
32387converted to @samp{(math-equal x y)}.
32388@end defun
32389
32390@defun equal-int x n
32391Returns true if @var{x} and @var{n} are numerically equal, where @var{n}
32392is a fixnum which is not a multiple of 10. This will automatically be
32393used by @code{defmath} in place of the more general @code{math-equal}
32394whenever possible.@refill
32395@end defun
32396
32397@defun nearly-equal x y
32398Returns true if @var{x} and @var{y}, as floating-point numbers, are
32399equal except possibly in the last decimal place. For example,
32400314.159 and 314.166 are considered nearly equal if the current
32401precision is 6 (since they differ by 7 units), but not if the current
32402precision is 7 (since they differ by 70 units). Most functions which
32403use series expansions use @code{with-extra-prec} to evaluate the
32404series with 2 extra digits of precision, then use @code{nearly-equal}
32405to decide when the series has converged; this guards against cumulative
32406error in the series evaluation without doing extra work which would be
32407lost when the result is rounded back down to the current precision.
32408In @code{defmath}, this can be written @samp{(~= @var{x} @var{y})}.
32409The @var{x} and @var{y} can be numbers of any kind, including complex.
32410@end defun
32411
32412@defun nearly-zerop x y
32413Returns true if @var{x} is nearly zero, compared to @var{y}. This
32414checks whether @var{x} plus @var{y} would by be @code{nearly-equal}
32415to @var{y} itself, to within the current precision, in other words,
32416if adding @var{x} to @var{y} would have a negligible effect on @var{y}
32417due to roundoff error. @var{X} may be a real or complex number, but
32418@var{y} must be real.
32419@end defun
32420
32421@defun is-true x
32422Return true if the formula @var{x} represents a true value in
32423Calc, not Lisp, terms. It tests if @var{x} is a non-zero number
32424or a provably non-zero formula.
32425@end defun
32426
32427@defun reject-arg val pred
32428Abort the current function evaluation due to unacceptable argument values.
32429This calls @samp{(calc-record-why @var{pred} @var{val})}, then signals a
32430Lisp error which @code{normalize} will trap. The net effect is that the
32431function call which led here will be left in symbolic form.@refill
32432@end defun
32433
32434@defun inexact-value
32435If Symbolic Mode is enabled, this will signal an error that causes
32436@code{normalize} to leave the formula in symbolic form, with the message
32437``Inexact result.'' (This function has no effect when not in Symbolic Mode.)
32438Note that if your function calls @samp{(sin 5)} in Symbolic Mode, the
32439@code{sin} function will call @code{inexact-value}, which will cause your
32440function to be left unsimplified. You may instead wish to call
32441@samp{(normalize (list 'calcFunc-sin 5))}, which in Symbolic Mode will
32442return the formula @samp{sin(5)} to your function.@refill
32443@end defun
32444
32445@defun overflow
32446This signals an error that will be reported as a floating-point overflow.
32447@end defun
32448
32449@defun underflow
32450This signals a floating-point underflow.
32451@end defun
32452
32453@node Computational Lisp Functions, Vector Lisp Functions, Predicates, Internals
32454@subsubsection Computational Functions
32455
32456@noindent
32457The functions described here do the actual computational work of the
32458Calculator. In addition to these, note that any function described in
32459the main body of this manual may be called from Lisp; for example, if
32460the documentation refers to the @code{calc-sqrt} [@code{sqrt}] command,
32461this means @code{calc-sqrt} is an interactive stack-based square-root
32462command and @code{sqrt} (which @code{defmath} expands to @code{calcFunc-sqrt})
32463is the actual Lisp function for taking square roots.@refill
32464
32465The functions @code{math-add}, @code{math-sub}, @code{math-mul},
32466@code{math-div}, @code{math-mod}, and @code{math-neg} are not included
32467in this list, since @code{defmath} allows you to write native Lisp
32468@code{+}, @code{-}, @code{*}, @code{/}, @code{%}, and unary @code{-},
32469respectively, instead.@refill
32470
32471@defun normalize val
32472(Full form: @code{math-normalize}.)
32473Reduce the value @var{val} to standard form. For example, if @var{val}
32474is a fixnum, it will be converted to a bignum if it is too large, and
32475if @var{val} is a bignum it will be normalized by clipping off trailing
32476(i.e., most-significant) zero digits and converting to a fixnum if it is
32477small. All the various data types are similarly converted to their standard
32478forms. Variables are left alone, but function calls are actually evaluated
32479in formulas. For example, normalizing @samp{(+ 2 (calcFunc-abs -4))} will
32480return 6.@refill
32481
32482If a function call fails, because the function is void or has the wrong
32483number of parameters, or because it returns @code{nil} or calls
32484@code{reject-arg} or @code{inexact-result}, @code{normalize} returns
32485the formula still in symbolic form.@refill
32486
32487If the current Simplification Mode is ``none'' or ``numeric arguments
32488only,'' @code{normalize} will act appropriately. However, the more
32489powerful simplification modes (like algebraic simplification) are
32490not handled by @code{normalize}. They are handled by @code{calc-normalize},
32491which calls @code{normalize} and possibly some other routines, such
32492as @code{simplify} or @code{simplify-units}. Programs generally will
32493never call @code{calc-normalize} except when popping or pushing values
32494on the stack.@refill
32495@end defun
32496
32497@defun evaluate-expr expr
32498Replace all variables in @var{expr} that have values with their values,
32499then use @code{normalize} to simplify the result. This is what happens
32500when you press the @kbd{=} key interactively.@refill
32501@end defun
32502
32503@defmac with-extra-prec n body
32504Evaluate the Lisp forms in @var{body} with precision increased by @var{n}
32505digits. This is a macro which expands to
32506
32507@smallexample
32508(math-normalize
32509 (let ((calc-internal-prec (+ calc-internal-prec @var{n})))
32510 @var{body}))
32511@end smallexample
32512
32513The surrounding call to @code{math-normalize} causes a floating-point
32514result to be rounded down to the original precision afterwards. This
32515is important because some arithmetic operations assume a number's
32516mantissa contains no more digits than the current precision allows.
32517@end defmac
32518
32519@defun make-frac n d
32520Build a fraction @samp{@var{n}:@var{d}}. This is equivalent to calling
32521@samp{(normalize (list 'frac @var{n} @var{d}))}, but more efficient.
32522@end defun
32523
32524@defun make-float mant exp
32525Build a floating-point value out of @var{mant} and @var{exp}, both
32526of which are arbitrary integers. This function will return a
32527properly normalized float value, or signal an overflow or underflow
32528if @var{exp} is out of range.
32529@end defun
32530
32531@defun make-sdev x sigma
32532Build an error form out of @var{x} and the absolute value of @var{sigma}.
32533If @var{sigma} is zero, the result is the number @var{x} directly.
32534If @var{sigma} is negative or complex, its absolute value is used.
32535If @var{x} or @var{sigma} is not a valid type of object for use in
32536error forms, this calls @code{reject-arg}.
32537@end defun
32538
32539@defun make-intv mask lo hi
32540Build an interval form out of @var{mask} (which is assumed to be an
32541integer from 0 to 3), and the limits @var{lo} and @var{hi}. If
32542@var{lo} is greater than @var{hi}, an empty interval form is returned.
32543This calls @code{reject-arg} if @var{lo} or @var{hi} is unsuitable.
32544@end defun
32545
32546@defun sort-intv mask lo hi
32547Build an interval form, similar to @code{make-intv}, except that if
32548@var{lo} is less than @var{hi} they are simply exchanged, and the
32549bits of @var{mask} are swapped accordingly.
32550@end defun
32551
32552@defun make-mod n m
32553Build a modulo form out of @var{n} and the modulus @var{m}. Since modulo
32554forms do not allow formulas as their components, if @var{n} or @var{m}
32555is not a real number or HMS form the result will be a formula which
32556is a call to @code{makemod}, the algebraic version of this function.
32557@end defun
32558
32559@defun float x
32560Convert @var{x} to floating-point form. Integers and fractions are
32561converted to numerically equivalent floats; components of complex
32562numbers, vectors, HMS forms, date forms, error forms, intervals, and
32563modulo forms are recursively floated. If the argument is a variable
32564or formula, this calls @code{reject-arg}.
32565@end defun
32566
32567@defun compare x y
32568Compare the numbers @var{x} and @var{y}, and return @i{-1} if
32569@samp{(lessp @var{x} @var{y})}, 1 if @samp{(lessp @var{y} @var{x})},
325700 if @samp{(math-equal @var{x} @var{y})}, or 2 if the order is
32571undefined or cannot be determined.@refill
32572@end defun
32573
32574@defun numdigs n
32575Return the number of digits of integer @var{n}, effectively
32576@samp{ceil(log10(@var{n}))}, but much more efficient. Zero is
32577considered to have zero digits.
32578@end defun
32579
32580@defun scale-int x n
32581Shift integer @var{x} left @var{n} decimal digits, or right @i{-@var{n}}
32582digits with truncation toward zero.
32583@end defun
32584
32585@defun scale-rounding x n
32586Like @code{scale-int}, except that a right shift rounds to the nearest
32587integer rather than truncating.
32588@end defun
32589
32590@defun fixnum n
32591Return the integer @var{n} as a fixnum, i.e., a native Lisp integer.
32592If @var{n} is outside the permissible range for Lisp integers (usually
3259324 binary bits) the result is undefined.
32594@end defun
32595
32596@defun sqr x
32597Compute the square of @var{x}; short for @samp{(* @var{x} @var{x})}.
32598@end defun
32599
32600@defun quotient x y
32601Divide integer @var{x} by integer @var{y}; return an integer quotient
32602and discard the remainder. If @var{x} or @var{y} is negative, the
32603direction of rounding is undefined.
32604@end defun
32605
32606@defun idiv x y
32607Perform an integer division; if @var{x} and @var{y} are both nonnegative
32608integers, this uses the @code{quotient} function, otherwise it computes
32609@samp{floor(@var{x}/@var{y})}. Thus the result is well-defined but
32610slower than for @code{quotient}.
32611@end defun
32612
32613@defun imod x y
32614Divide integer @var{x} by integer @var{y}; return the integer remainder
32615and discard the quotient. Like @code{quotient}, this works only for
32616integer arguments and is not well-defined for negative arguments.
32617For a more well-defined result, use @samp{(% @var{x} @var{y})}.
32618@end defun
32619
32620@defun idivmod x y
32621Divide integer @var{x} by integer @var{y}; return a cons cell whose
32622@code{car} is @samp{(quotient @var{x} @var{y})} and whose @code{cdr}
32623is @samp{(imod @var{x} @var{y})}.@refill
32624@end defun
32625
32626@defun pow x y
32627Compute @var{x} to the power @var{y}. In @code{defmath} code, this can
32628also be written @samp{(^ @var{x} @var{y})} or
32629@w{@samp{(expt @var{x} @var{y})}}.@refill
32630@end defun
32631
32632@defun abs-approx x
32633Compute a fast approximation to the absolute value of @var{x}. For
32634example, for a rectangular complex number the result is the sum of
32635the absolute values of the components.
32636@end defun
32637
32638@findex two-pi
32639@findex pi-over-2
32640@findex pi-over-4
32641@findex pi-over-180
32642@findex sqrt-two-pi
32643@findex sqrt-e
32644@findex e
32645@findex ln-2
32646@findex ln-10
32647@defun pi
32648The function @samp{(pi)} computes @samp{pi} to the current precision.
32649Other related constant-generating functions are @code{two-pi},
32650@code{pi-over-2}, @code{pi-over-4}, @code{pi-over-180}, @code{sqrt-two-pi},
32651@code{e}, @code{sqrt-e}, @code{ln-2}, and @code{ln-10}. Each function
32652returns a floating-point value in the current precision, and each uses
32653caching so that all calls after the first are essentially free.@refill
32654@end defun
32655
32656@defmac math-defcache @var{func} @var{initial} @var{form}
32657This macro, usually used as a top-level call like @code{defun} or
32658@code{defvar}, defines a new cached constant analogous to @code{pi}, etc.
32659It defines a function @code{func} which returns the requested value;
32660if @var{initial} is non-@code{nil} it must be a @samp{(float @dots{})}
32661form which serves as an initial value for the cache. If @var{func}
32662is called when the cache is empty or does not have enough digits to
32663satisfy the current precision, the Lisp expression @var{form} is evaluated
32664with the current precision increased by four, and the result minus its
32665two least significant digits is stored in the cache. For example,
32666calling @samp{(pi)} with a precision of 30 computes @samp{pi} to 34
32667digits, rounds it down to 32 digits for future use, then rounds it
32668again to 30 digits for use in the present request.@refill
32669@end defmac
32670
32671@findex half-circle
32672@findex quarter-circle
32673@defun full-circle symb
32674If the current angular mode is Degrees or HMS, this function returns the
32675integer 360. In Radians mode, this function returns either the
32676corresponding value in radians to the current precision, or the formula
32677@samp{2*pi}, depending on the Symbolic Mode. There are also similar
32678function @code{half-circle} and @code{quarter-circle}.
32679@end defun
32680
32681@defun power-of-2 n
32682Compute two to the integer power @var{n}, as a (potentially very large)
32683integer. Powers of two are cached, so only the first call for a
32684particular @var{n} is expensive.
32685@end defun
32686
32687@defun integer-log2 n
32688Compute the base-2 logarithm of @var{n}, which must be an integer which
32689is a power of two. If @var{n} is not a power of two, this function will
32690return @code{nil}.
32691@end defun
32692
32693@defun div-mod a b m
32694Divide @var{a} by @var{b}, modulo @var{m}. This returns @code{nil} if
32695there is no solution, or if any of the arguments are not integers.@refill
32696@end defun
32697
32698@defun pow-mod a b m
32699Compute @var{a} to the power @var{b}, modulo @var{m}. If @var{a},
32700@var{b}, and @var{m} are integers, this uses an especially efficient
32701algorithm. Otherwise, it simply computes @samp{(% (^ a b) m)}.
32702@end defun
32703
32704@defun isqrt n
32705Compute the integer square root of @var{n}. This is the square root
32706of @var{n} rounded down toward zero, i.e., @samp{floor(sqrt(@var{n}))}.
32707If @var{n} is itself an integer, the computation is especially efficient.
32708@end defun
32709
32710@defun to-hms a ang
32711Convert the argument @var{a} into an HMS form. If @var{ang} is specified,
32712it is the angular mode in which to interpret @var{a}, either @code{deg}
32713or @code{rad}. Otherwise, the current angular mode is used. If @var{a}
32714is already an HMS form it is returned as-is.
32715@end defun
32716
32717@defun from-hms a ang
32718Convert the HMS form @var{a} into a real number. If @var{ang} is specified,
32719it is the angular mode in which to express the result, otherwise the
32720current angular mode is used. If @var{a} is already a real number, it
32721is returned as-is.
32722@end defun
32723
32724@defun to-radians a
32725Convert the number or HMS form @var{a} to radians from the current
32726angular mode.
32727@end defun
32728
32729@defun from-radians a
32730Convert the number @var{a} from radians to the current angular mode.
32731If @var{a} is a formula, this returns the formula @samp{deg(@var{a})}.
32732@end defun
32733
32734@defun to-radians-2 a
32735Like @code{to-radians}, except that in Symbolic Mode a degrees to
32736radians conversion yields a formula like @samp{@var{a}*pi/180}.
32737@end defun
32738
32739@defun from-radians-2 a
32740Like @code{from-radians}, except that in Symbolic Mode a radians to
32741degrees conversion yields a formula like @samp{@var{a}*180/pi}.
32742@end defun
32743
32744@defun random-digit
32745Produce a random base-1000 digit in the range 0 to 999.
32746@end defun
32747
32748@defun random-digits n
32749Produce a random @var{n}-digit integer; this will be an integer
32750in the interval @samp{[0, 10^@var{n})}.
32751@end defun
32752
32753@defun random-float
32754Produce a random float in the interval @samp{[0, 1)}.
32755@end defun
32756
32757@defun prime-test n iters
32758Determine whether the integer @var{n} is prime. Return a list which has
32759one of these forms: @samp{(nil @var{f})} means the number is non-prime
32760because it was found to be divisible by @var{f}; @samp{(nil)} means it
32761was found to be non-prime by table look-up (so no factors are known);
32762@samp{(nil unknown)} means it is definitely non-prime but no factors
32763are known because @var{n} was large enough that Fermat's probabilistic
32764test had to be used; @samp{(t)} means the number is definitely prime;
32765and @samp{(maybe @var{i} @var{p})} means that Fermat's test, after @var{i}
32766iterations, is @var{p} percent sure that the number is prime. The
32767@var{iters} parameter is the number of Fermat iterations to use, in the
32768case that this is necessary. If @code{prime-test} returns ``maybe,''
32769you can call it again with the same @var{n} to get a greater certainty;
32770@code{prime-test} remembers where it left off.@refill
32771@end defun
32772
32773@defun to-simple-fraction f
32774If @var{f} is a floating-point number which can be represented exactly
32775as a small rational number. return that number, else return @var{f}.
32776For example, 0.75 would be converted to 3:4. This function is very
32777fast.
32778@end defun
32779
32780@defun to-fraction f tol
32781Find a rational approximation to floating-point number @var{f} to within
32782a specified tolerance @var{tol}; this corresponds to the algebraic
32783function @code{frac}, and can be rather slow.
32784@end defun
32785
32786@defun quarter-integer n
32787If @var{n} is an integer or integer-valued float, this function
32788returns zero. If @var{n} is a half-integer (i.e., an integer plus
32789@i{1:2} or 0.5), it returns 2. If @var{n} is a quarter-integer,
32790it returns 1 or 3. If @var{n} is anything else, this function
32791returns @code{nil}.
32792@end defun
32793
32794@node Vector Lisp Functions, Symbolic Lisp Functions, Computational Lisp Functions, Internals
32795@subsubsection Vector Functions
32796
32797@noindent
32798The functions described here perform various operations on vectors and
32799matrices.
32800
32801@defun math-concat x y
32802Do a vector concatenation; this operation is written @samp{@var{x} | @var{y}}
32803in a symbolic formula. @xref{Building Vectors}.
32804@end defun
32805
32806@defun vec-length v
32807Return the length of vector @var{v}. If @var{v} is not a vector, the
32808result is zero. If @var{v} is a matrix, this returns the number of
32809rows in the matrix.
32810@end defun
32811
32812@defun mat-dimens m
32813Determine the dimensions of vector or matrix @var{m}. If @var{m} is not
32814a vector, the result is an empty list. If @var{m} is a plain vector
32815but not a matrix, the result is a one-element list containing the length
32816of the vector. If @var{m} is a matrix with @var{r} rows and @var{c} columns,
32817the result is the list @samp{(@var{r} @var{c})}. Higher-order tensors
32818produce lists of more than two dimensions. Note that the object
32819@samp{[[1, 2, 3], [4, 5]]} is a vector of vectors not all the same size,
32820and is treated by this and other Calc routines as a plain vector of two
32821elements.@refill
32822@end defun
32823
32824@defun dimension-error
32825Abort the current function with a message of ``Dimension error.''
32826The Calculator will leave the function being evaluated in symbolic
32827form; this is really just a special case of @code{reject-arg}.
32828@end defun
32829
32830@defun build-vector args
32831Return a Calc vector with the zero-or-more @var{args} as elements.
32832For example, @samp{(build-vector 1 2 3)} returns the Calc vector
32833@samp{[1, 2, 3]}, stored internally as the list @samp{(vec 1 2 3)}.
32834@end defun
32835
32836@defun make-vec obj dims
32837Return a Calc vector or matrix all of whose elements are equal to
32838@var{obj}. For example, @samp{(make-vec 27 3 4)} returns a 3x4 matrix
32839filled with 27's.
32840@end defun
32841
32842@defun row-matrix v
32843If @var{v} is a plain vector, convert it into a row matrix, i.e.,
32844a matrix whose single row is @var{v}. If @var{v} is already a matrix,
32845leave it alone.
32846@end defun
32847
32848@defun col-matrix v
32849If @var{v} is a plain vector, convert it into a column matrix, i.e., a
32850matrix with each element of @var{v} as a separate row. If @var{v} is
32851already a matrix, leave it alone.
32852@end defun
32853
32854@defun map-vec f v
32855Map the Lisp function @var{f} over the Calc vector @var{v}. For example,
32856@samp{(map-vec 'math-floor v)} returns a vector of the floored components
32857of vector @var{v}.
32858@end defun
32859
32860@defun map-vec-2 f a b
32861Map the Lisp function @var{f} over the two vectors @var{a} and @var{b}.
32862If @var{a} and @var{b} are vectors of equal length, the result is a
32863vector of the results of calling @samp{(@var{f} @var{ai} @var{bi})}
32864for each pair of elements @var{ai} and @var{bi}. If either @var{a} or
32865@var{b} is a scalar, it is matched with each value of the other vector.
32866For example, @samp{(map-vec-2 'math-add v 1)} returns the vector @var{v}
32867with each element increased by one. Note that using @samp{'+} would not
32868work here, since @code{defmath} does not expand function names everywhere,
32869just where they are in the function position of a Lisp expression.@refill
32870@end defun
32871
32872@defun reduce-vec f v
32873Reduce the function @var{f} over the vector @var{v}. For example, if
32874@var{v} is @samp{[10, 20, 30, 40]}, this calls @samp{(f (f (f 10 20) 30) 40)}.
32875If @var{v} is a matrix, this reduces over the rows of @var{v}.
32876@end defun
32877
32878@defun reduce-cols f m
32879Reduce the function @var{f} over the columns of matrix @var{m}. For
32880example, if @var{m} is @samp{[[1, 2], [3, 4], [5, 6]]}, the result
32881is a vector of the two elements @samp{(f (f 1 3) 5)} and @samp{(f (f 2 4) 6)}.
32882@end defun
32883
32884@defun mat-row m n
32885Return the @var{n}th row of matrix @var{m}. This is equivalent to
32886@samp{(elt m n)}. For a slower but safer version, use @code{mrow}.
32887(@xref{Extracting Elements}.)
32888@end defun
32889
32890@defun mat-col m n
32891Return the @var{n}th column of matrix @var{m}, in the form of a vector.
32892The arguments are not checked for correctness.
32893@end defun
32894
32895@defun mat-less-row m n
32896Return a copy of matrix @var{m} with its @var{n}th row deleted. The
32897number @var{n} must be in range from 1 to the number of rows in @var{m}.
32898@end defun
32899
32900@defun mat-less-col m n
32901Return a copy of matrix @var{m} with its @var{n}th column deleted.
32902@end defun
32903
32904@defun transpose m
32905Return the transpose of matrix @var{m}.
32906@end defun
32907
32908@defun flatten-vector v
32909Flatten nested vector @var{v} into a vector of scalars. For example,
32910if @var{v} is @samp{[[1, 2, 3], [4, 5]]} the result is @samp{[1, 2, 3, 4, 5]}.
32911@end defun
32912
32913@defun copy-matrix m
32914If @var{m} is a matrix, return a copy of @var{m}. This maps
32915@code{copy-sequence} over the rows of @var{m}; in Lisp terms, each
32916element of the result matrix will be @code{eq} to the corresponding
32917element of @var{m}, but none of the @code{cons} cells that make up
32918the structure of the matrix will be @code{eq}. If @var{m} is a plain
32919vector, this is the same as @code{copy-sequence}.@refill
32920@end defun
32921
32922@defun swap-rows m r1 r2
32923Exchange rows @var{r1} and @var{r2} of matrix @var{m} in-place. In
32924other words, unlike most of the other functions described here, this
32925function changes @var{m} itself rather than building up a new result
32926matrix. The return value is @var{m}, i.e., @samp{(eq (swap-rows m 1 2) m)}
32927is true, with the side effect of exchanging the first two rows of
32928@var{m}.@refill
32929@end defun
32930
32931@node Symbolic Lisp Functions, Formatting Lisp Functions, Vector Lisp Functions, Internals
32932@subsubsection Symbolic Functions
32933
32934@noindent
32935The functions described here operate on symbolic formulas in the
32936Calculator.
32937
32938@defun calc-prepare-selection num
32939Prepare a stack entry for selection operations. If @var{num} is
32940omitted, the stack entry containing the cursor is used; otherwise,
32941it is the number of the stack entry to use. This function stores
32942useful information about the current stack entry into a set of
32943variables. @code{calc-selection-cache-num} contains the number of
32944the stack entry involved (equal to @var{num} if you specified it);
32945@code{calc-selection-cache-entry} contains the stack entry as a
32946list (such as @code{calc-top-list} would return with @code{entry}
32947as the selection mode); and @code{calc-selection-cache-comp} contains
32948a special ``tagged'' composition (@pxref{Formatting Lisp Functions})
32949which allows Calc to relate cursor positions in the buffer with
32950their corresponding sub-formulas.
32951
32952A slight complication arises in the selection mechanism because
32953formulas may contain small integers. For example, in the vector
32954@samp{[1, 2, 1]} the first and last elements are @code{eq} to each
32955other; selections are recorded as the actual Lisp object that
32956appears somewhere in the tree of the whole formula, but storing
32957@code{1} would falsely select both @code{1}'s in the vector. So
32958@code{calc-prepare-selection} also checks the stack entry and
32959replaces any plain integers with ``complex number'' lists of the form
32960@samp{(cplx @var{n} 0)}. This list will be displayed the same as a
32961plain @var{n} and the change will be completely invisible to the
32962user, but it will guarantee that no two sub-formulas of the stack
32963entry will be @code{eq} to each other. Next time the stack entry
32964is involved in a computation, @code{calc-normalize} will replace
32965these lists with plain numbers again, again invisibly to the user.
32966@end defun
32967
32968@defun calc-encase-atoms x
32969This modifies the formula @var{x} to ensure that each part of the
32970formula is a unique atom, using the @samp{(cplx @var{n} 0)} trick
32971described above. This function may use @code{setcar} to modify
32972the formula in-place.
32973@end defun
32974
32975@defun calc-find-selected-part
32976Find the smallest sub-formula of the current formula that contains
32977the cursor. This assumes @code{calc-prepare-selection} has been
32978called already. If the cursor is not actually on any part of the
32979formula, this returns @code{nil}.
32980@end defun
32981
32982@defun calc-change-current-selection selection
32983Change the currently prepared stack element's selection to
32984@var{selection}, which should be @code{eq} to some sub-formula
32985of the stack element, or @code{nil} to unselect the formula.
32986The stack element's appearance in the Calc buffer is adjusted
32987to reflect the new selection.
32988@end defun
32989
32990@defun calc-find-nth-part expr n
32991Return the @var{n}th sub-formula of @var{expr}. This function is used
32992by the selection commands, and (unless @kbd{j b} has been used) treats
32993sums and products as flat many-element formulas. Thus if @var{expr}
32994is @samp{((a + b) - c) + d}, calling @code{calc-find-nth-part} with
32995@var{n} equal to four will return @samp{d}.
32996@end defun
32997
32998@defun calc-find-parent-formula expr part
32999Return the sub-formula of @var{expr} which immediately contains
33000@var{part}. If @var{expr} is @samp{a*b + (c+1)*d} and @var{part}
33001is @code{eq} to the @samp{c+1} term of @var{expr}, then this function
33002will return @samp{(c+1)*d}. If @var{part} turns out not to be a
33003sub-formula of @var{expr}, the function returns @code{nil}. If
33004@var{part} is @code{eq} to @var{expr}, the function returns @code{t}.
33005This function does not take associativity into account.
33006@end defun
33007
33008@defun calc-find-assoc-parent-formula expr part
33009This is the same as @code{calc-find-parent-formula}, except that
33010(unless @kbd{j b} has been used) it continues widening the selection
33011to contain a complete level of the formula. Given @samp{a} from
33012@samp{((a + b) - c) + d}, @code{calc-find-parent-formula} will
33013return @samp{a + b} but @code{calc-find-assoc-parent-formula} will
33014return the whole expression.
33015@end defun
33016
33017@defun calc-grow-assoc-formula expr part
33018This expands sub-formula @var{part} of @var{expr} to encompass a
33019complete level of the formula. If @var{part} and its immediate
33020parent are not compatible associative operators, or if @kbd{j b}
33021has been used, this simply returns @var{part}.
33022@end defun
33023
33024@defun calc-find-sub-formula expr part
33025This finds the immediate sub-formula of @var{expr} which contains
33026@var{part}. It returns an index @var{n} such that
33027@samp{(calc-find-nth-part @var{expr} @var{n})} would return @var{part}.
33028If @var{part} is not a sub-formula of @var{expr}, it returns @code{nil}.
33029If @var{part} is @code{eq} to @var{expr}, it returns @code{t}. This
33030function does not take associativity into account.
33031@end defun
33032
33033@defun calc-replace-sub-formula expr old new
33034This function returns a copy of formula @var{expr}, with the
33035sub-formula that is @code{eq} to @var{old} replaced by @var{new}.
33036@end defun
33037
33038@defun simplify expr
33039Simplify the expression @var{expr} by applying various algebraic rules.
33040This is what the @w{@kbd{a s}} (@code{calc-simplify}) command uses. This
33041always returns a copy of the expression; the structure @var{expr} points
33042to remains unchanged in memory.
33043
33044More precisely, here is what @code{simplify} does: The expression is
33045first normalized and evaluated by calling @code{normalize}. If any
33046@code{AlgSimpRules} have been defined, they are then applied. Then
33047the expression is traversed in a depth-first, bottom-up fashion; at
33048each level, any simplifications that can be made are made until no
33049further changes are possible. Once the entire formula has been
33050traversed in this way, it is compared with the original formula (from
33051before the call to @code{normalize}) and, if it has changed,
33052the entire procedure is repeated (starting with @code{normalize})
33053until no further changes occur. Usually only two iterations are
33054needed:@: one to simplify the formula, and another to verify that no
33055further simplifications were possible.
33056@end defun
33057
33058@defun simplify-extended expr
33059Simplify the expression @var{expr}, with additional rules enabled that
33060help do a more thorough job, while not being entirely ``safe'' in all
33061circumstances. (For example, this mode will simplify @samp{sqrt(x^2)}
33062to @samp{x}, which is only valid when @var{x} is positive.) This is
33063implemented by temporarily binding the variable @code{math-living-dangerously}
33064to @code{t} (using a @code{let} form) and calling @code{simplify}.
33065Dangerous simplification rules are written to check this variable
33066before taking any action.@refill
33067@end defun
33068
33069@defun simplify-units expr
33070Simplify the expression @var{expr}, treating variable names as units
33071whenever possible. This works by binding the variable
33072@code{math-simplifying-units} to @code{t} while calling @code{simplify}.
33073@end defun
33074
33075@defmac math-defsimplify funcs body
33076Register a new simplification rule; this is normally called as a top-level
33077form, like @code{defun} or @code{defmath}. If @var{funcs} is a symbol
33078(like @code{+} or @code{calcFunc-sqrt}), this simplification rule is
33079applied to the formulas which are calls to the specified function. Or,
33080@var{funcs} can be a list of such symbols; the rule applies to all
33081functions on the list. The @var{body} is written like the body of a
33082function with a single argument called @code{expr}. The body will be
33083executed with @code{expr} bound to a formula which is a call to one of
33084the functions @var{funcs}. If the function body returns @code{nil}, or
33085if it returns a result @code{equal} to the original @code{expr}, it is
33086ignored and Calc goes on to try the next simplification rule that applies.
33087If the function body returns something different, that new formula is
33088substituted for @var{expr} in the original formula.@refill
33089
33090At each point in the formula, rules are tried in the order of the
33091original calls to @code{math-defsimplify}; the search stops after the
33092first rule that makes a change. Thus later rules for that same
33093function will not have a chance to trigger until the next iteration
33094of the main @code{simplify} loop.
33095
33096Note that, since @code{defmath} is not being used here, @var{body} must
33097be written in true Lisp code without the conveniences that @code{defmath}
33098provides. If you prefer, you can have @var{body} simply call another
33099function (defined with @code{defmath}) which does the real work.
33100
33101The arguments of a function call will already have been simplified
33102before any rules for the call itself are invoked. Since a new argument
33103list is consed up when this happens, this means that the rule's body is
33104allowed to rearrange the function's arguments destructively if that is
33105convenient. Here is a typical example of a simplification rule:
33106
33107@smallexample
33108(math-defsimplify calcFunc-arcsinh
33109 (or (and (math-looks-negp (nth 1 expr))
33110 (math-neg (list 'calcFunc-arcsinh
33111 (math-neg (nth 1 expr)))))
33112 (and (eq (car-safe (nth 1 expr)) 'calcFunc-sinh)
33113 (or math-living-dangerously
33114 (math-known-realp (nth 1 (nth 1 expr))))
33115 (nth 1 (nth 1 expr)))))
33116@end smallexample
33117
33118This is really a pair of rules written with one @code{math-defsimplify}
33119for convenience; the first replaces @samp{arcsinh(-x)} with
33120@samp{-arcsinh(x)}, and the second, which is safe only for real @samp{x},
33121replaces @samp{arcsinh(sinh(x))} with @samp{x}.@refill
33122@end defmac
33123
33124@defun common-constant-factor expr
33125Check @var{expr} to see if it is a sum of terms all multiplied by the
33126same rational value. If so, return this value. If not, return @code{nil}.
33127For example, if called on @samp{6x + 9y + 12z}, it would return 3, since
331283 is a common factor of all the terms.
33129@end defun
33130
33131@defun cancel-common-factor expr factor
33132Assuming @var{expr} is a sum with @var{factor} as a common factor,
33133divide each term of the sum by @var{factor}. This is done by
33134destructively modifying parts of @var{expr}, on the assumption that
33135it is being used by a simplification rule (where such things are
33136allowed; see above). For example, consider this built-in rule for
33137square roots:
33138
33139@smallexample
33140(math-defsimplify calcFunc-sqrt
33141 (let ((fac (math-common-constant-factor (nth 1 expr))))
33142 (and fac (not (eq fac 1))
33143 (math-mul (math-normalize (list 'calcFunc-sqrt fac))
33144 (math-normalize
33145 (list 'calcFunc-sqrt
33146 (math-cancel-common-factor
33147 (nth 1 expr) fac)))))))
33148@end smallexample
33149@end defun
33150
33151@defun frac-gcd a b
33152Compute a ``rational GCD'' of @var{a} and @var{b}, which must both be
33153rational numbers. This is the fraction composed of the GCD of the
33154numerators of @var{a} and @var{b}, over the GCD of the denominators.
33155It is used by @code{common-constant-factor}. Note that the standard
33156@code{gcd} function uses the LCM to combine the denominators.@refill
33157@end defun
33158
33159@defun map-tree func expr many
33160Try applying Lisp function @var{func} to various sub-expressions of
33161@var{expr}. Initially, call @var{func} with @var{expr} itself as an
33162argument. If this returns an expression which is not @code{equal} to
33163@var{expr}, apply @var{func} again until eventually it does return
33164@var{expr} with no changes. Then, if @var{expr} is a function call,
33165recursively apply @var{func} to each of the arguments. This keeps going
33166until no changes occur anywhere in the expression; this final expression
33167is returned by @code{map-tree}. Note that, unlike simplification rules,
33168@var{func} functions may @emph{not} make destructive changes to
33169@var{expr}. If a third argument @var{many} is provided, it is an
33170integer which says how many times @var{func} may be applied; the
33171default, as described above, is infinitely many times.@refill
33172@end defun
33173
33174@defun compile-rewrites rules
33175Compile the rewrite rule set specified by @var{rules}, which should
33176be a formula that is either a vector or a variable name. If the latter,
33177the compiled rules are saved so that later @code{compile-rules} calls
33178for that same variable can return immediately. If there are problems
33179with the rules, this function calls @code{error} with a suitable
33180message.
33181@end defun
33182
33183@defun apply-rewrites expr crules heads
33184Apply the compiled rewrite rule set @var{crules} to the expression
33185@var{expr}. This will make only one rewrite and only checks at the
33186top level of the expression. The result @code{nil} if no rules
33187matched, or if the only rules that matched did not actually change
33188the expression. The @var{heads} argument is optional; if is given,
33189it should be a list of all function names that (may) appear in
33190@var{expr}. The rewrite compiler tags each rule with the
33191rarest-looking function name in the rule; if you specify @var{heads},
33192@code{apply-rewrites} can use this information to narrow its search
33193down to just a few rules in the rule set.
33194@end defun
33195
33196@defun rewrite-heads expr
33197Compute a @var{heads} list for @var{expr} suitable for use with
33198@code{apply-rewrites}, as discussed above.
33199@end defun
33200
33201@defun rewrite expr rules many
33202This is an all-in-one rewrite function. It compiles the rule set
33203specified by @var{rules}, then uses @code{map-tree} to apply the
33204rules throughout @var{expr} up to @var{many} (default infinity)
33205times.
33206@end defun
33207
33208@defun match-patterns pat vec not-flag
33209Given a Calc vector @var{vec} and an uncompiled pattern set or
33210pattern set variable @var{pat}, this function returns a new vector
33211of all elements of @var{vec} which do (or don't, if @var{not-flag} is
33212non-@code{nil}) match any of the patterns in @var{pat}.
33213@end defun
33214
33215@defun deriv expr var value symb
33216Compute the derivative of @var{expr} with respect to variable @var{var}
33217(which may actually be any sub-expression). If @var{value} is specified,
33218the derivative is evaluated at the value of @var{var}; otherwise, the
33219derivative is left in terms of @var{var}. If the expression contains
33220functions for which no derivative formula is known, new derivative
33221functions are invented by adding primes to the names; @pxref{Calculus}.
33222However, if @var{symb} is non-@code{nil}, the presence of undifferentiable
33223functions in @var{expr} instead cancels the whole differentiation, and
33224@code{deriv} returns @code{nil} instead.
33225
33226Derivatives of an @var{n}-argument function can be defined by
33227adding a @code{math-derivative-@var{n}} property to the property list
33228of the symbol for the function's derivative, which will be the
33229function name followed by an apostrophe. The value of the property
33230should be a Lisp function; it is called with the same arguments as the
33231original function call that is being differentiated. It should return
33232a formula for the derivative. For example, the derivative of @code{ln}
33233is defined by
33234
33235@smallexample
33236(put 'calcFunc-ln\' 'math-derivative-1
33237 (function (lambda (u) (math-div 1 u))))
33238@end smallexample
33239
33240The two-argument @code{log} function has two derivatives,
33241@smallexample
33242(put 'calcFunc-log\' 'math-derivative-2 ; d(log(x,b)) / dx
33243 (function (lambda (x b) ... )))
33244(put 'calcFunc-log\'2 'math-derivative-2 ; d(log(x,b)) / db
33245 (function (lambda (x b) ... )))
33246@end smallexample
33247@end defun
33248
33249@defun tderiv expr var value symb
33250Compute the total derivative of @var{expr}. This is the same as
33251@code{deriv}, except that variables other than @var{var} are not
33252assumed to be constant with respect to @var{var}.
33253@end defun
33254
33255@defun integ expr var low high
33256Compute the integral of @var{expr} with respect to @var{var}.
33257@xref{Calculus}, for further details.
33258@end defun
33259
33260@defmac math-defintegral funcs body
33261Define a rule for integrating a function or functions of one argument;
33262this macro is very similar in format to @code{math-defsimplify}.
33263The main difference is that here @var{body} is the body of a function
33264with a single argument @code{u} which is bound to the argument to the
33265function being integrated, not the function call itself. Also, the
33266variable of integration is available as @code{math-integ-var}. If
33267evaluation of the integral requires doing further integrals, the body
33268should call @samp{(math-integral @var{x})} to find the integral of
33269@var{x} with respect to @code{math-integ-var}; this function returns
33270@code{nil} if the integral could not be done. Some examples:
33271
33272@smallexample
33273(math-defintegral calcFunc-conj
33274 (let ((int (math-integral u)))
33275 (and int
33276 (list 'calcFunc-conj int))))
33277
33278(math-defintegral calcFunc-cos
33279 (and (equal u math-integ-var)
33280 (math-from-radians-2 (list 'calcFunc-sin u))))
33281@end smallexample
33282
33283In the @code{cos} example, we define only the integral of @samp{cos(x) dx},
33284relying on the general integration-by-substitution facility to handle
33285cosines of more complicated arguments. An integration rule should return
33286@code{nil} if it can't do the integral; if several rules are defined for
33287the same function, they are tried in order until one returns a non-@code{nil}
33288result.@refill
33289@end defmac
33290
33291@defmac math-defintegral-2 funcs body
33292Define a rule for integrating a function or functions of two arguments.
33293This is exactly analogous to @code{math-defintegral}, except that @var{body}
33294is written as the body of a function with two arguments, @var{u} and
33295@var{v}.@refill
33296@end defmac
33297
33298@defun solve-for lhs rhs var full
33299Attempt to solve the equation @samp{@var{lhs} = @var{rhs}} by isolating
33300the variable @var{var} on the lefthand side; return the resulting righthand
33301side, or @code{nil} if the equation cannot be solved. The variable
33302@var{var} must appear at least once in @var{lhs} or @var{rhs}. Note that
33303the return value is a formula which does not contain @var{var}; this is
33304different from the user-level @code{solve} and @code{finv} functions,
33305which return a rearranged equation or a functional inverse, respectively.
33306If @var{full} is non-@code{nil}, a full solution including dummy signs
33307and dummy integers will be produced. User-defined inverses are provided
33308as properties in a manner similar to derivatives:@refill
33309
33310@smallexample
33311(put 'calcFunc-ln 'math-inverse
33312 (function (lambda (x) (list 'calcFunc-exp x))))
33313@end smallexample
33314
33315This function can call @samp{(math-solve-get-sign @var{x})} to create
33316a new arbitrary sign variable, returning @var{x} times that sign, and
33317@samp{(math-solve-get-int @var{x})} to create a new arbitrary integer
33318variable multiplied by @var{x}. These functions simply return @var{x}
33319if the caller requested a non-``full'' solution.
33320@end defun
33321
33322@defun solve-eqn expr var full
33323This version of @code{solve-for} takes an expression which will
33324typically be an equation or inequality. (If it is not, it will be
33325interpreted as the equation @samp{@var{expr} = 0}.) It returns an
33326equation or inequality, or @code{nil} if no solution could be found.
33327@end defun
33328
33329@defun solve-system exprs vars full
33330This function solves a system of equations. Generally, @var{exprs}
33331and @var{vars} will be vectors of equal length.
33332@xref{Solving Systems of Equations}, for other options.
33333@end defun
33334
33335@defun expr-contains expr var
33336Returns a non-@code{nil} value if @var{var} occurs as a subexpression
33337of @var{expr}.
33338
33339This function might seem at first to be identical to
33340@code{calc-find-sub-formula}. The key difference is that
33341@code{expr-contains} uses @code{equal} to test for matches, whereas
33342@code{calc-find-sub-formula} uses @code{eq}. In the formula
33343@samp{f(a, a)}, the two @samp{a}s will be @code{equal} but not
33344@code{eq} to each other.@refill
33345@end defun
33346
33347@defun expr-contains-count expr var
33348Returns the number of occurrences of @var{var} as a subexpression
33349of @var{expr}, or @code{nil} if there are no occurrences.@refill
33350@end defun
33351
33352@defun expr-depends expr var
33353Returns true if @var{expr} refers to any variable the occurs in @var{var}.
33354In other words, it checks if @var{expr} and @var{var} have any variables
33355in common.
33356@end defun
33357
33358@defun expr-contains-vars expr
33359Return true if @var{expr} contains any variables, or @code{nil} if @var{expr}
33360contains only constants and functions with constant arguments.
33361@end defun
33362
33363@defun expr-subst expr old new
33364Returns a copy of @var{expr}, with all occurrences of @var{old} replaced
33365by @var{new}. This treats @code{lambda} forms specially with respect
33366to the dummy argument variables, so that the effect is always to return
33367@var{expr} evaluated at @var{old} = @var{new}.@refill
33368@end defun
33369
33370@defun multi-subst expr old new
33371This is like @code{expr-subst}, except that @var{old} and @var{new}
33372are lists of expressions to be substituted simultaneously. If one
33373list is shorter than the other, trailing elements of the longer list
33374are ignored.
33375@end defun
33376
33377@defun expr-weight expr
33378Returns the ``weight'' of @var{expr}, basically a count of the total
33379number of objects and function calls that appear in @var{expr}. For
33380``primitive'' objects, this will be one.
33381@end defun
33382
33383@defun expr-height expr
33384Returns the ``height'' of @var{expr}, which is the deepest level to
33385which function calls are nested. (Note that @samp{@var{a} + @var{b}}
33386counts as a function call.) For primitive objects, this returns zero.@refill
33387@end defun
33388
33389@defun polynomial-p expr var
33390Check if @var{expr} is a polynomial in variable (or sub-expression)
33391@var{var}. If so, return the degree of the polynomial, that is, the
33392highest power of @var{var} that appears in @var{expr}. For example,
33393for @samp{(x^2 + 3)^3 + 4} this would return 6. This function returns
33394@code{nil} unless @var{expr}, when expanded out by @kbd{a x}
33395(@code{calc-expand}), would consist of a sum of terms in which @var{var}
33396appears only raised to nonnegative integer powers. Note that if
33397@var{var} does not occur in @var{expr}, then @var{expr} is considered
33398a polynomial of degree 0.@refill
33399@end defun
33400
33401@defun is-polynomial expr var degree loose
33402Check if @var{expr} is a polynomial in variable or sub-expression
33403@var{var}, and, if so, return a list representation of the polynomial
33404where the elements of the list are coefficients of successive powers of
33405@var{var}: @samp{@var{a} + @var{b} x + @var{c} x^3} would produce the
33406list @samp{(@var{a} @var{b} 0 @var{c})}, and @samp{(x + 1)^2} would
33407produce the list @samp{(1 2 1)}. The highest element of the list will
33408be non-zero, with the special exception that if @var{expr} is the
33409constant zero, the returned value will be @samp{(0)}. Return @code{nil}
33410if @var{expr} is not a polynomial in @var{var}. If @var{degree} is
33411specified, this will not consider polynomials of degree higher than that
33412value. This is a good precaution because otherwise an input of
33413@samp{(x+1)^1000} will cause a huge coefficient list to be built. If
33414@var{loose} is non-@code{nil}, then a looser definition of a polynomial
33415is used in which coefficients are no longer required not to depend on
33416@var{var}, but are only required not to take the form of polynomials
33417themselves. For example, @samp{sin(x) x^2 + cos(x)} is a loose
33418polynomial with coefficients @samp{((calcFunc-cos x) 0 (calcFunc-sin
33419x))}. The result will never be @code{nil} in loose mode, since any
33420expression can be interpreted as a ``constant'' loose polynomial.@refill
33421@end defun
33422
33423@defun polynomial-base expr pred
33424Check if @var{expr} is a polynomial in any variable that occurs in it;
33425if so, return that variable. (If @var{expr} is a multivariate polynomial,
33426this chooses one variable arbitrarily.) If @var{pred} is specified, it should
33427be a Lisp function which is called as @samp{(@var{pred} @var{subexpr})},
33428and which should return true if @code{mpb-top-expr} (a global name for
33429the original @var{expr}) is a suitable polynomial in @var{subexpr}.
33430The default predicate uses @samp{(polynomial-p mpb-top-expr @var{subexpr})};
33431you can use @var{pred} to specify additional conditions. Or, you could
33432have @var{pred} build up a list of every suitable @var{subexpr} that
33433is found.@refill
33434@end defun
33435
33436@defun poly-simplify poly
33437Simplify polynomial coefficient list @var{poly} by (destructively)
33438clipping off trailing zeros.
33439@end defun
33440
33441@defun poly-mix a ac b bc
33442Mix two polynomial lists @var{a} and @var{b} (in the form returned by
33443@code{is-polynomial}) in a linear combination with coefficient expressions
33444@var{ac} and @var{bc}. The result is a (not necessarily simplified)
33445polynomial list representing @samp{@var{ac} @var{a} + @var{bc} @var{b}}.@refill
33446@end defun
33447
33448@defun poly-mul a b
33449Multiply two polynomial coefficient lists @var{a} and @var{b}. The
33450result will be in simplified form if the inputs were simplified.
33451@end defun
33452
33453@defun build-polynomial-expr poly var
33454Construct a Calc formula which represents the polynomial coefficient
33455list @var{poly} applied to variable @var{var}. The @kbd{a c}
33456(@code{calc-collect}) command uses @code{is-polynomial} to turn an
33457expression into a coefficient list, then @code{build-polynomial-expr}
33458to turn the list back into an expression in regular form.@refill
33459@end defun
33460
33461@defun check-unit-name var
33462Check if @var{var} is a variable which can be interpreted as a unit
33463name. If so, return the units table entry for that unit. This
33464will be a list whose first element is the unit name (not counting
33465prefix characters) as a symbol and whose second element is the
33466Calc expression which defines the unit. (Refer to the Calc sources
33467for details on the remaining elements of this list.) If @var{var}
33468is not a variable or is not a unit name, return @code{nil}.
33469@end defun
33470
33471@defun units-in-expr-p expr sub-exprs
33472Return true if @var{expr} contains any variables which can be
33473interpreted as units. If @var{sub-exprs} is @code{t}, the entire
33474expression is searched. If @var{sub-exprs} is @code{nil}, this
33475checks whether @var{expr} is directly a units expression.@refill
33476@end defun
33477
33478@defun single-units-in-expr-p expr
33479Check whether @var{expr} contains exactly one units variable. If so,
33480return the units table entry for the variable. If @var{expr} does
33481not contain any units, return @code{nil}. If @var{expr} contains
33482two or more units, return the symbol @code{wrong}.
33483@end defun
33484
33485@defun to-standard-units expr which
33486Convert units expression @var{expr} to base units. If @var{which}
33487is @code{nil}, use Calc's native base units. Otherwise, @var{which}
33488can specify a units system, which is a list of two-element lists,
33489where the first element is a Calc base symbol name and the second
33490is an expression to substitute for it.@refill
33491@end defun
33492
33493@defun remove-units expr
33494Return a copy of @var{expr} with all units variables replaced by ones.
33495This expression is generally normalized before use.
33496@end defun
33497
33498@defun extract-units expr
33499Return a copy of @var{expr} with everything but units variables replaced
33500by ones.
33501@end defun
33502
33503@node Formatting Lisp Functions, Hooks, Symbolic Lisp Functions, Internals
33504@subsubsection I/O and Formatting Functions
33505
33506@noindent
33507The functions described here are responsible for parsing and formatting
33508Calc numbers and formulas.
33509
33510@defun calc-eval str sep arg1 arg2 @dots{}
33511This is the simplest interface to the Calculator from another Lisp program.
33512@xref{Calling Calc from Your Programs}.
33513@end defun
33514
33515@defun read-number str
33516If string @var{str} contains a valid Calc number, either integer,
33517fraction, float, or HMS form, this function parses and returns that
33518number. Otherwise, it returns @code{nil}.
33519@end defun
33520
33521@defun read-expr str
33522Read an algebraic expression from string @var{str}. If @var{str} does
33523not have the form of a valid expression, return a list of the form
33524@samp{(error @var{pos} @var{msg})} where @var{pos} is an integer index
33525into @var{str} of the general location of the error, and @var{msg} is
33526a string describing the problem.@refill
33527@end defun
33528
33529@defun read-exprs str
33530Read a list of expressions separated by commas, and return it as a
33531Lisp list. If an error occurs in any expressions, an error list as
33532shown above is returned instead.
33533@end defun
33534
33535@defun calc-do-alg-entry initial prompt no-norm
33536Read an algebraic formula or formulas using the minibuffer. All
33537conventions of regular algebraic entry are observed. The return value
33538is a list of Calc formulas; there will be more than one if the user
33539entered a list of values separated by commas. The result is @code{nil}
33540if the user presses Return with a blank line. If @var{initial} is
33541given, it is a string which the minibuffer will initially contain.
33542If @var{prompt} is given, it is the prompt string to use; the default
33543is ``Algebraic:''. If @var{no-norm} is @code{t}, the formulas will
33544be returned exactly as parsed; otherwise, they will be passed through
33545@code{calc-normalize} first.@refill
33546
33547To support the use of @kbd{$} characters in the algebraic entry, use
33548@code{let} to bind @code{calc-dollar-values} to a list of the values
33549to be substituted for @kbd{$}, @kbd{$$}, and so on, and bind
33550@code{calc-dollar-used} to 0. Upon return, @code{calc-dollar-used}
33551will have been changed to the highest number of consecutive @kbd{$}s
33552that actually appeared in the input.@refill
33553@end defun
33554
33555@defun format-number a
33556Convert the real or complex number or HMS form @var{a} to string form.
33557@end defun
33558
33559@defun format-flat-expr a prec
33560Convert the arbitrary Calc number or formula @var{a} to string form,
33561in the style used by the trail buffer and the @code{calc-edit} command.
33562This is a simple format designed
33563mostly to guarantee the string is of a form that can be re-parsed by
33564@code{read-expr}. Most formatting modes, such as digit grouping,
33565complex number format, and point character, are ignored to ensure the
33566result will be re-readable. The @var{prec} parameter is normally 0; if
33567you pass a large integer like 1000 instead, the expression will be
33568surrounded by parentheses unless it is a plain number or variable name.@refill
33569@end defun
33570
33571@defun format-nice-expr a width
33572This is like @code{format-flat-expr} (with @var{prec} equal to 0),
33573except that newlines will be inserted to keep lines down to the
33574specified @var{width}, and vectors that look like matrices or rewrite
33575rules are written in a pseudo-matrix format. The @code{calc-edit}
33576command uses this when only one stack entry is being edited.
33577@end defun
33578
33579@defun format-value a width
33580Convert the Calc number or formula @var{a} to string form, using the
33581format seen in the stack buffer. Beware the the string returned may
33582not be re-readable by @code{read-expr}, for example, because of digit
33583grouping. Multi-line objects like matrices produce strings that
33584contain newline characters to separate the lines. The @var{w}
33585parameter, if given, is the target window size for which to format
33586the expressions. If @var{w} is omitted, the width of the Calculator
33587window is used.@refill
33588@end defun
33589
33590@defun compose-expr a prec
33591Format the Calc number or formula @var{a} according to the current
33592language mode, returning a ``composition.'' To learn about the
33593structure of compositions, see the comments in the Calc source code.
33594You can specify the format of a given type of function call by putting
33595a @code{math-compose-@var{lang}} property on the function's symbol,
33596whose value is a Lisp function that takes @var{a} and @var{prec} as
33597arguments and returns a composition. Here @var{lang} is a language
33598mode name, one of @code{normal}, @code{big}, @code{c}, @code{pascal},
33599@code{fortran}, @code{tex}, @code{eqn}, @code{math}, or @code{maple}.
33600In Big mode, Calc actually tries @code{math-compose-big} first, then
33601tries @code{math-compose-normal}. If this property does not exist,
33602or if the function returns @code{nil}, the function is written in the
33603normal function-call notation for that language.
33604@end defun
33605
33606@defun composition-to-string c w
33607Convert a composition structure returned by @code{compose-expr} into
33608a string. Multi-line compositions convert to strings containing
33609newline characters. The target window size is given by @var{w}.
33610The @code{format-value} function basically calls @code{compose-expr}
33611followed by @code{composition-to-string}.
33612@end defun
33613
33614@defun comp-width c
33615Compute the width in characters of composition @var{c}.
33616@end defun
33617
33618@defun comp-height c
33619Compute the height in lines of composition @var{c}.
33620@end defun
33621
33622@defun comp-ascent c
33623Compute the portion of the height of composition @var{c} which is on or
33624above the baseline. For a one-line composition, this will be one.
33625@end defun
33626
33627@defun comp-descent c
33628Compute the portion of the height of composition @var{c} which is below
33629the baseline. For a one-line composition, this will be zero.
33630@end defun
33631
33632@defun comp-first-char c
33633If composition @var{c} is a ``flat'' composition, return the first
33634(leftmost) character of the composition as an integer. Otherwise,
33635return @code{nil}.@refill
33636@end defun
33637
33638@defun comp-last-char c
33639If composition @var{c} is a ``flat'' composition, return the last
33640(rightmost) character, otherwise return @code{nil}.
33641@end defun
33642
33643@comment @node Lisp Variables, Hooks, Formatting Lisp Functions, Internals
33644@comment @subsubsection Lisp Variables
33645@comment
33646@comment @noindent
33647@comment (This section is currently unfinished.)
33648
33649@node Hooks, , Formatting Lisp Functions, Internals
33650@subsubsection Hooks
33651
33652@noindent
33653Hooks are variables which contain Lisp functions (or lists of functions)
33654which are called at various times. Calc defines a number of hooks
33655that help you to customize it in various ways. Calc uses the Lisp
33656function @code{run-hooks} to invoke the hooks shown below. Several
33657other customization-related variables are also described here.
33658
33659@defvar calc-load-hook
33660This hook is called at the end of @file{calc.el}, after the file has
33661been loaded, before any functions in it have been called, but after
33662@code{calc-mode-map} and similar variables have been set up.
33663@end defvar
33664
33665@defvar calc-ext-load-hook
33666This hook is called at the end of @file{calc-ext.el}.
33667@end defvar
33668
33669@defvar calc-start-hook
33670This hook is called as the last step in a @kbd{M-x calc} command.
33671At this point, the Calc buffer has been created and initialized if
33672necessary, the Calc window and trail window have been created,
33673and the ``Welcome to Calc'' message has been displayed.
33674@end defvar
33675
33676@defvar calc-mode-hook
33677This hook is called when the Calc buffer is being created. Usually
33678this will only happen once per Emacs session. The hook is called
33679after Emacs has switched to the new buffer, the mode-settings file
33680has been read if necessary, and all other buffer-local variables
33681have been set up. After this hook returns, Calc will perform a
33682@code{calc-refresh} operation, set up the mode line display, then
33683evaluate any deferred @code{calc-define} properties that have not
33684been evaluated yet.
33685@end defvar
33686
33687@defvar calc-trail-mode-hook
33688This hook is called when the Calc Trail buffer is being created.
33689It is called as the very last step of setting up the Trail buffer.
33690Like @code{calc-mode-hook}, this will normally happen only once
33691per Emacs session.
33692@end defvar
33693
33694@defvar calc-end-hook
33695This hook is called by @code{calc-quit}, generally because the user
33696presses @kbd{q} or @kbd{M-# c} while in Calc. The Calc buffer will
33697be the current buffer. The hook is called as the very first
33698step, before the Calc window is destroyed.
33699@end defvar
33700
33701@defvar calc-window-hook
33702If this hook exists, it is called to create the Calc window.
33703Upon return, this new Calc window should be the current window.
33704(The Calc buffer will already be the current buffer when the
33705hook is called.) If the hook is not defined, Calc will
33706generally use @code{split-window}, @code{set-window-buffer},
33707and @code{select-window} to create the Calc window.
33708@end defvar
33709
33710@defvar calc-trail-window-hook
33711If this hook exists, it is called to create the Calc Trail window.
33712The variable @code{calc-trail-buffer} will contain the buffer
33713which the window should use. Unlike @code{calc-window-hook},
33714this hook must @emph{not} switch into the new window.
33715@end defvar
33716
33717@defvar calc-edit-mode-hook
33718This hook is called by @code{calc-edit} (and the other ``edit''
33719commands) when the temporary editing buffer is being created.
33720The buffer will have been selected and set up to be in
33721@code{calc-edit-mode}, but will not yet have been filled with
33722text. (In fact it may still have leftover text from a previous
33723@code{calc-edit} command.)
33724@end defvar
33725
33726@defvar calc-mode-save-hook
33727This hook is called by the @code{calc-save-modes} command,
33728after Calc's own mode features have been inserted into the
33729@file{.emacs} buffer and just before the ``End of mode settings''
33730message is inserted.
33731@end defvar
33732
33733@defvar calc-reset-hook
33734This hook is called after @kbd{M-# 0} (@code{calc-reset}) has
33735reset all modes. The Calc buffer will be the current buffer.
33736@end defvar
33737
33738@defvar calc-other-modes
33739This variable contains a list of strings. The strings are
33740concatenated at the end of the modes portion of the Calc
33741mode line (after standard modes such as ``Deg'', ``Inv'' and
33742``Hyp''). Each string should be a short, single word followed
33743by a space. The variable is @code{nil} by default.
33744@end defvar
33745
33746@defvar calc-mode-map
33747This is the keymap that is used by Calc mode. The best time
33748to adjust it is probably in a @code{calc-mode-hook}. If the
33749Calc extensions package (@file{calc-ext.el}) has not yet been
33750loaded, many of these keys will be bound to @code{calc-missing-key},
33751which is a command that loads the extensions package and
33752``retypes'' the key. If your @code{calc-mode-hook} rebinds
33753one of these keys, it will probably be overridden when the
33754extensions are loaded.
33755@end defvar
33756
33757@defvar calc-digit-map
33758This is the keymap that is used during numeric entry. Numeric
33759entry uses the minibuffer, but this map binds every non-numeric
33760key to @code{calcDigit-nondigit} which generally calls
33761@code{exit-minibuffer} and ``retypes'' the key.
33762@end defvar
33763
33764@defvar calc-alg-ent-map
33765This is the keymap that is used during algebraic entry. This is
33766mostly a copy of @code{minibuffer-local-map}.
33767@end defvar
33768
33769@defvar calc-store-var-map
33770This is the keymap that is used during entry of variable names for
33771commands like @code{calc-store} and @code{calc-recall}. This is
33772mostly a copy of @code{minibuffer-local-completion-map}.
33773@end defvar
33774
33775@defvar calc-edit-mode-map
33776This is the (sparse) keymap used by @code{calc-edit} and other
33777temporary editing commands. It binds @key{RET}, @key{LFD},
33778and @kbd{C-c C-c} to @code{calc-edit-finish}.
33779@end defvar
33780
33781@defvar calc-mode-var-list
33782This is a list of variables which are saved by @code{calc-save-modes}.
33783Each entry is a list of two items, the variable (as a Lisp symbol)
33784and its default value. When modes are being saved, each variable
33785is compared with its default value (using @code{equal}) and any
33786non-default variables are written out.
33787@end defvar
33788
33789@defvar calc-local-var-list
33790This is a list of variables which should be buffer-local to the
33791Calc buffer. Each entry is a variable name (as a Lisp symbol).
33792These variables also have their default values manipulated by
33793the @code{calc} and @code{calc-quit} commands; @pxref{Multiple Calculators}.
33794Since @code{calc-mode-hook} is called after this list has been
33795used the first time, your hook should add a variable to the
33796list and also call @code{make-local-variable} itself.
33797@end defvar
33798
33799@node Installation, Reporting Bugs, Programming, Top
33800@appendix Installation
33801
33802@noindent
33803Calc 2.02 comes as a set of GNU Emacs Lisp files, with names like
33804@file{calc.el} and @file{calc-ext.el}, and also as a @file{calc.texinfo}
33805file which can be used to generate both on-line and printed
33806documentation.@refill
33807
33808To install Calc, just follow these simple steps. If you want more
33809information, each step is discussed at length in the sections below.
33810
33811@enumerate
33812@item
33813Change (@samp{cd}) to the Calc ``home'' directory. This directory was
33814created when you unbundled the Calc @file{.tar} or @file{.shar} file.
33815
33816@item
33817Type @samp{make} to install Calc privately for your own use, or type
33818@samp{make install} to install Calc system-wide. This will compile all
33819the Calc component files, modify your @file{.emacs} or the system-wide
33820@file{lisp/default} file to install Calc as appropriate, and format
33821the on-line Calc manual.
33822
33823@noindent
33824Both variants are shorthand for the following three steps:
33825@itemize @bullet
33826@item
33827@pindex calc-compile
33828@samp{make compile} to run the byte-compiler.
33829
33830@item
33831@samp{make private} or @samp{make public}, corresponding to
33832@samp{make} and @samp{make install}, respectively. (If @samp{make public}
33833fails because your system doesn't already have a @file{default} or
33834@file{default.el} file, use Emacs or the Unix @code{touch} command
33835to create a zero-sized one first.)
33836
33837@item
33838@samp{make info} to format the on-line Calc manual. This first tries
33839to use the @file{makeinfo} program; if that program is not present, it
33840uses the Emacs @code{texinfo-format-buffer} command instead.
33841@end itemize
33842@noindent
33843The Unix @code{make} utility looks in the file @file{Makefile} in the
33844current directory to see what Unix commands correspond to the various
33845``targets'' like @code{install} or @code{public}. If your system
33846doesn't have @code{make}, you will have to examine the @file{Makefile}
33847and type in the corresponding commands by hand.
33848
33849@item
33850If you ever move Calc to a new home directory, just give the
33851@samp{make private} or @samp{make public} command again in the new
33852directory.
33853
33854@item
33855Test your installation as described at the end of these instructions.
33856
33857@item
33858(Optional.) To print a hardcopy of the Calc manual (over 500 pages)
33859or just the Calc Summary (about 20 pages), follow the instructions under
33860``Printed Documentation'' below.
33861@end enumerate
33862
33863@noindent
33864Calc is now installed and ready to go!
33865@example
33866
33867@end example
33868@iftex
33869@node Installation 2, foo, bar, spam
33870@end iftex
33871
33872@appendixsec Upgrading from Calc 1.07
33873
33874@noindent
33875If you have Calc version 1.07 or earlier, you will find that Calc 2.00
33876is organized quite differently. For one, Calc 2.00 is now distributed
33877already split into many parts; formerly this was done as part of the
33878installation procedure. Also, some new functions must be autoloaded
33879and the @kbd{M-#} key must be bound to @code{calc-dispatch} instead
33880of to @code{calc}.
33881
33882The easiest way to upgrade is to delete your old Calc files and then
33883install Calc 2.00 from scratch using the above instructions. You should
33884then go into your @file{.emacs} or @file{default} file and remove the
33885old @code{autoload} and @code{global-set-key} commands for Calc, since
33886@samp{make public}/@samp{make private} has added new, better ones.
33887
33888See the @file{README} and @file{README.prev} files in the Calc
33889distribution for more information about what has changed since version
338901.07. (@file{README.prev} describes changes before 2.00, and is
33891present only in the FTP and tape versions of the distribution.)
33892
33893@ifinfo
33894@example
33895
33896@end example
33897@end ifinfo
33898@appendixsec The @samp{make public} Command
33899
33900@noindent
33901If you are not the regular Emacs administrator on your system, your
33902account may not be allowed to execute the @samp{make public} command,
33903since the system-wide @file{default} file may be write-protected.
33904If this is the case, you will have to ask your Emacs installer to
33905execute this command. (Just @code{cd} to the Calc home directory
33906and type @samp{make public}.)
33907
33908The @samp{make private} command adds exactly the same set of commands
33909to your @file{.emacs} file as @samp{make public} adds to @file{default}.
33910If your Emacs installer is concerned about typing this command out of
33911the blue, you can ask her/him instead to copy the necessary text from
33912your @file{.emacs} file. (It will be marked by a comment that says
33913``Commands added by @code{calc-private-autoloads} on (date and time).'')
33914
33915@ifinfo
33916@example
33917
33918@end example
33919@end ifinfo
33920@appendixsec Compilation
33921
33922@noindent
33923Calc is written in a way that maximizes performance when its code has been
33924byte-compiled; a side effect is that performance is seriously degraded if
33925it @emph{isn't} compiled. Thus, it is essential to compile the Calculator
33926before trying to use it. The function @samp{calc-compile} in the file
33927@file{calc-maint.el} runs the Emacs byte-compiler on all the Calc source
33928files. (Specifically, it runs @kbd{M-x byte-compile-file} on all files
33929in the current directory with names of the form @file{calc*.el}, and also
33930on the file @file{macedit.el}.)
33931
33932If @code{calc-compile} finds that certain files have already been
33933compiled and have not been changed since, then it will not bother to
33934recompile those files.
33935
33936The @code{calc-compile} command also pre-builds certain tables, such as
33937the units table (@pxref{The Units Table}) and the built-in rewrite rules
33938(@pxref{Rearranging with Selections}) which Calc would otherwise
33939need to rebuild every time those features were used.
33940
33941The @samp{make compile} shell command is simply a convenient way to
33942start an Emacs and give it a @code{calc-compile} command.
33943
33944@ifinfo
33945@example
33946
33947@end example
33948@end ifinfo
33949@appendixsec Auto-loading
33950
33951@noindent
33952To teach Emacs how to load in Calc when you type @kbd{M-#} for the
33953first time, add these lines to your @file{.emacs} file (if you are
33954installing Calc just for your own use), or the system's @file{lisp/default}
33955file (if you are installing Calc publicly). The @samp{make private}
33956and @samp{make public} commands, respectively, take care of this.
33957(Note that @samp{make} runs @samp{make private}, and @samp{make install}
33958runs @samp{make public}.)
33959
33960@smallexample
33961(autoload 'calc-dispatch "calc" "Calculator Options" t)
33962(autoload 'full-calc "calc" "Full-screen Calculator" t)
33963(autoload 'full-calc-keypad "calc" "Full-screen X Calculator" t)
33964(autoload 'calc-eval "calc" "Use Calculator from Lisp")
33965(autoload 'defmath "calc" nil t t)
33966(autoload 'calc "calc" "Calculator Mode" t)
33967(autoload 'quick-calc "calc" "Quick Calculator" t)
33968(autoload 'calc-keypad "calc" "X windows Calculator" t)
33969(autoload 'calc-embedded "calc" "Use Calc from any buffer" t)
33970(autoload 'calc-embedded-activate "calc" "Activate =>'s in buffer" t)
33971(autoload 'calc-grab-region "calc" "Grab region of Calc data" t)
33972(autoload 'calc-grab-rectangle "calc" "Grab rectangle of data" t)
33973@end smallexample
33974
33975@vindex load-path
33976Unless you have installed the Calc files in Emacs' main @file{lisp/}
33977directory, you will also have to add a command that looks like the
33978following to tell Emacs where to find them. In this example, we
33979have put the files in directory @file{/usr/gnu/src/calc-2.00}.
33980
33981@smallexample
33982(setq load-path (append load-path (list "/usr/gnu/src/calc-2.00")))
33983@end smallexample
33984
33985@noindent
33986The @samp{make public} and @samp{make private} commands also do this
33987(they use the then-current directory as the name to add to the path).
33988If you move Calc to a new location, just repeat the @samp{make public}
33989or @samp{make private} command to have this new location added to
33990the @code{load-path}.@refill
33991
33992The @code{autoload} command for @code{calc-dispatch} is what loads
33993@file{calc.elc} when you type @kbd{M-#}. It is the only @code{autoload}
33994that is absolutely necessary for Calc to work. The others are for
33995commands and features that you may wish to use before typing
33996@kbd{M-#} for the first time. In particular, @code{full-calc} and
33997@code{full-calc-keypad} are autoloaded to support ``standalone''
33998operation (@pxref{Standalone Operation}), @code{calc-eval} and
33999@code{defmath} are autoloaded to allow other Emacs Lisp programs to
34000use Calc facilities (@pxref{Calling Calc from Your Programs}), and
34001@code{calc-embedded-activate} is autoloaded because some Embedded
34002Mode files may call it as soon as they are read into Emacs
34003(@pxref{Assignments in Embedded Mode}).
34004
34005@ifinfo
34006@example
34007
34008@end example
34009@end ifinfo
34010@appendixsec Finding Component Files
34011
34012@noindent
34013There is no need to write @code{autoload} commands that point to all
34014the various Calc component files like @file{calc-misc.elc} and
34015@file{calc-alg.elc}. The main file, @file{calc.elc}, contains all
34016the necessary @code{autoload} commands for these files.
34017
34018(Actually, to conserve space @file{calc.elc} only autoloads a few of
34019the component files, plus @file{calc-ext.elc}, which in turn autoloads
34020the rest of the components. This allows Calc to load a little faster
34021in the beginning, but the net effect is the same.)
34022
34023This autoloading mechanism assumes that all the component files can
34024be found on the @code{load-path}. The @samp{make public} and
34025@samp{make private} commands take care of this, but Calc has a few
34026other strategies in case you have installed it in an unusual way.
34027
34028If, when Calc is loaded, it is unable to find its components on the
34029@code{load-path} it is given, it checks the file name in the original
34030@code{autoload} command for @code{calc-dispatch}. If that name
34031included directory information, Calc adds that directory to the
34032@code{load-path}:
34033
34034@example
34035(autoload 'calc-dispatch "calc-2.00/calc" "Calculator" t)
34036@end example
34037
34038@noindent
34039Suppose the directory @file{/usr/gnu/src/emacs/lisp} is on the path, and
34040the above @code{autoload} allows Emacs to find Calc under the name
34041@file{/usr/gnu/src/emacs/lisp/calc-2.00/calc.elc}. Then when Calc
34042starts up it will add @file{/usr/gnu/src/emacs/lisp/calc-2.00}
34043to the path so that it will later be able to find its component files.
34044
34045@vindex calc-autoload-directory
34046If the above strategy does not locate the component files, Calc
34047examines the variable @code{calc-autoload-directory}. This is
34048initially @code{nil}, but you can store the name of Calc's home
34049directory in it as a sure-fire way of getting Calc to find its
34050components.
34051
34052@ifinfo
34053@example
34054
34055@end example
34056@end ifinfo
34057@appendixsec Merging Source Files
34058
34059@noindent
34060If the @code{autoload} mechanism is not managing to load each part
34061of Calc when it is needed, you can concatenate all the @file{.el}
34062files into one big file. The order should be @file{calc.el}, then
34063@file{calc-ext.el}, then all the other files in any order.
34064Byte-compile the resulting big file. This merged Calculator ought
34065to work just like Calc normally does, though it will be @emph{substantially}
34066slower to load.@refill
34067
34068@ifinfo
34069@example
34070
34071@end example
34072@end ifinfo
34073@appendixsec Key Bindings
34074
34075@noindent
34076Calc is normally bound to the @kbd{M-#} key. To set up this key
34077binding, include the following command in your @file{.emacs} or
34078@file{lisp/default} file. (This is done automatically by
34079@samp{make private} or @samp{make public}, respectively.)
34080
34081@smallexample
34082(global-set-key "\e#" 'calc-dispatch)
34083@end smallexample
34084
34085Note that @code{calc-dispatch} actually works as a prefix for various
34086two-key sequences. If you have a convenient unused function key on
34087your keyboard, you may wish to bind @code{calc-dispatch} to that as
34088well. You may even wish to bind other specific Calc functions like
34089@code{calc} or @code{quick-calc} to other handy function keys.
34090
34091Even if you bind @code{calc-dispatch} to other keys, it is best to
34092bind it to @kbd{M-#} as well if you possibly can: There are references
34093to @kbd{M-#} all throughout the Calc manual which would confuse novice
34094users if they didn't work as advertised.
34095
34096@vindex calc-scan-for-dels
34097Another key binding issue is the @key{DEL} key. Some installations
34098use a different key (such as backspace) for this purpose. Calc
34099normally scans the entire keymap and maps all keys defined like
34100@key{DEL} to the @code{calc-pop} command. However, this may be
34101slow. You can set the variable @code{calc-scan-for-dels} to
34102@code{nil} to cause only the actual @key{DEL} key to be mapped to
34103@code{calc-pop}; this will speed loading of Calc.
34104
34105@ifinfo
34106@example
34107
34108@end example
34109@end ifinfo
34110@appendixsec The @file{macedit} Package
34111
34112@noindent
34113The file @file{macedit.el} contains another useful Emacs extension
34114called @code{edit-kbd-macro}. It allows you to edit a keyboard macro
34115in human-readable form. The @kbd{Z E} command in Calc knows how to
34116use it to edit user commands that have been defined by keyboard macros.
34117To autoload it, you will want to include the commands,
34118
34119@smallexample
34120(autoload 'edit-kbd-macro "macedit" "Edit Keyboard Macro" t)
34121(autoload 'edit-last-kbd-macro "macedit" "Edit Keyboard Macro" t)
34122(autoload 'read-kbd-macro "macedit" "Read Keyboard Macro" t)
34123@end smallexample
34124
34125@noindent
34126The @samp{make public} and @samp{make private} commands do this.
34127
34128@ifinfo
34129@example
34130
34131@end example
34132@end ifinfo
34133@appendixsec The GNUPLOT Program
34134
34135@noindent
34136Calc's graphing commands use the GNUPLOT program. If you have GNUPLOT
34137but you must type some command other than @file{gnuplot} to get it,
34138you should add a command to set the Lisp variable @code{calc-gnuplot-name}
34139to the appropriate file name. You may also need to change the variables
34140@code{calc-gnuplot-plot-command} and @code{calc-gnuplot-print-command} in
34141order to get correct displays and hardcopies, respectively, of your
34142plots.@refill
34143
34144@ifinfo
34145@example
34146
34147@end example
34148@end ifinfo
34149@appendixsec On-Line Documentation
34150
34151@noindent
34152The documentation for Calc (this manual) comes in a file called
34153@file{calc.texinfo}. To format this for use as an on-line manual,
34154type @samp{make info} (to use the @code{makeinfo} program), or
34155@samp{make texinfo} (to use the @code{texinfmt.el} program which runs
34156inside of Emacs). The former command is recommended if it works
34157on your system; it is faster and produces nicer-looking output.
34158
34159The @code{makeinfo} program will report inconsistencies involving
34160the nodes ``Copying'' and ``Interactive Tutorial''; these
34161messages should be ignored.
34162
34163The result will be a collection of files whose names begin with
34164@file{calc.info}. You may wish to add a reference to the first
34165of these, @file{calc.info} itself, to your Info system's @file{dir}
34166file. (This is optional since the @kbd{M-# i} command can access
34167@file{calc.info} whether or not it appears in the @file{dir} file.)
34168
34169@vindex calc-info-filename
34170There is a Lisp variable called @code{calc-info-filename} which holds
34171the name of the Info file containing Calc's on-line documentation.
34172Its default value is @code{"calc.info"}, which will work correctly if
34173the Info files are stored in Emacs' main @file{info/} directory, or if
34174they are in any of the directories listed in the @code{load-path}. If
34175you keep them elsewhere, you will want to put a command of the form,
34176
34177@smallexample
34178(setq calc-info-filename ".../calc.info")
34179@end smallexample
34180
34181@noindent
34182in your @file{.emacs} or @file{lisp/default} file, where @file{...}
34183represents the directory containing the Info files. This will not
34184be necessary if you follow the normal installation procedures.
34185
34186The @samp{make info} and @samp{make texinfo} commands compare the dates
34187on the files @file{calc.texinfo} and @file{calc.info}, and run the
34188appropriate program only if the latter file is older or does not exist.
34189
34190@ifinfo
34191@example
34192
34193@end example
34194@end ifinfo
34195@appendixsec Printed Documentation
34196
34197@noindent
34198Because the Calc manual is so large, you should only make a printed
34199copy if you really need it. To print the manual, you will need the
34200@TeX{} typesetting program (this is a free program by Donald Knuth
34201at Stanford University) as well as the @file{texindex} program and
34202@file{texinfo.tex} file, both of which can be obtained from the FSF
34203as part of the @code{texinfo2} package.@refill
34204
34205To print the Calc manual in one huge 550 page tome, type @samp{make tex}.
34206This will take care of running the manual through @TeX{} twice so that
34207references to later parts of the manual will have correct page numbers.
34208(Don't worry if you get some ``overfull box'' warnings.)
34209
34210The result will be a device-independent output file called
34211@file{calc.dvi}, which you must print in whatever way is right
34212for your system. On many systems, the command is
34213
34214@example
34215lpr -d calc.dvi
34216@end example
34217
34218@cindex Marginal notes, adjusting
34219Marginal notes for each function and key sequence normally alternate
34220between the left and right sides of the page, which is correct if the
34221manual is going to be bound as double-sided pages. Near the top of
34222the file @file{calc.texinfo} you will find alternate definitions of
34223the @code{\bumpoddpages} macro that put the marginal notes always on
34224the same side, best if you plan to be binding single-sided pages.
34225
34226@pindex calc-split-manual
34227Some people find the Calc manual to be too large to handle easily.
34228In fact, some versions of @TeX{} have too little memory to print it.
34229So Calc includes a @code{calc-split-manual} command that splits
34230@file{calc.texinfo} into two volumes, the Calc Tutorial and the
34231Calc Reference. The easiest way to use it is to type @samp{make tex2}
34232instead of @samp{make tex}. The result will be two smaller files,
34233@file{calctut.dvi} and @file{calcref.dvi}. The former contains the
34234tutorial part of the manual; the latter contains the reference part.
34235Both volumes include copies of the ``Getting Started'' chapter and
34236licensing information.
34237
34238To save disk space, you may wish to delete @file{calctut.*} and
34239@file{calcref.*} after you're done. Don't delete @file{calc.texinfo},
34240because you will need it to install future patches to Calc.
34241The @samp{make tex2} command takes care of all of this for you.
34242
34243The @samp{make textut} command formats only the Calc Tutorial volume,
34244producing @file{calctut.dvi} but not @file{calcref.dvi}. Likewise,
34245@samp{make texref} formats only the Calc Reference volume.
34246
34247@pindex calc-split-summary
34248Finally, there is a @code{calc-split-summary} command that splits off
34249just the Calc Summary appendix suitable for printing by itself.
34250Type @samp{make summary} instead of @samp{make tex}. The resulting
34251@file{calcsum.dvi} file will print in less than 20 pages. If the
34252Key Index file @file{calc.ky} is present, left over from a previous
34253@samp{make tex} command, then @samp{make summary} will insert a
34254column of page numbers into the summary using that information.
34255
34256The @samp{make isummary} command is like @samp{make summary}, but it
34257prints a summary that is designed to be substituted into the regular
34258manual. (The two summaries will be identical except for the
34259additional column of page numbers.) To make a complete manual, run
34260@samp{make tex} and @samp{make isummary}, print the two resulting
34261@file{.dvi} files, then discard the Summary pages that came from
34262@file{calc.dvi} and insert the ones from @file{calcsum.dvi} in their
34263place. Also, remember that the table of contents prints at the end
34264of the manual but should generally be moved to the front (after the
34265title and copyright pages).
34266
34267If you don't have @TeX{}, you can print the summary as a plain text
34268file by going to the ``Summary'' node in Calc's Info file, then
34269typing @kbd{M-x print-buffer} (@pxref{Summary}).
34270
34271@ifinfo
34272@example
34273
34274@end example
34275@end ifinfo
34276@appendixsec Settings File
34277
34278@noindent
34279@vindex calc-settings-file
34280Another variable you might want to set is @code{calc-settings-file},
34281which holds the file name in which commands like @kbd{m m} and @kbd{Z P}
34282store ``permanent'' definitions. The default value for this variable
34283is @code{"~/.emacs"}. If @code{calc-settings-file} does not contain
34284@code{".emacs"} as a substring, and if the variable
34285@code{calc-loaded-settings-file} is @code{nil}, then Calc will
34286automatically load your settings file (if it exists) the first time
34287Calc is invoked.@refill
34288
34289@ifinfo
34290@example
34291
34292@end example
34293@end ifinfo
34294@appendixsec Testing the Installation
34295
34296@noindent
34297To test your installation of Calc, start a new Emacs and type @kbd{M-# c}
34298to make sure the autoloads and key bindings work. Type @kbd{M-# i}
34299to make sure Calc can find its Info documentation. Press @kbd{q} to
34300exit the Info system and @kbd{M-# c} to re-enter the Calculator.
34301Type @kbd{20 S} to compute the sine of 20 degrees; this will test the
34302autoloading of the extensions modules. The result should be
343030.342020143326. Finally, press @kbd{M-# c} again to make sure the
34304Calculator can exit.
34305
34306You may also wish to test the GNUPLOT interface; to plot a sine wave,
34307type @kbd{' [0 ..@: 360], sin(x) RET g f}. Type @kbd{g q} when you
34308are done viewing the plot.
34309
34310Calc is now ready to use. If you wish to go through the Calc Tutorial,
34311press @kbd{M-# t} to begin.
34312@example
34313
34314@end example
34315
34316@noindent
34317(The above text is included in both the Calc documentation and the
34318file INSTALL in the Calc distribution directory.)
34319
34320@node Reporting Bugs, Summary, Installation, Top
34321@appendix Reporting Bugs
34322
34323@noindent
34324If you find a bug in Calc, send e-mail to Dave Gillespie,
34325
34326@example
34327daveg@@synaptics.com @r{or}
34328daveg@@csvax.cs.caltech.edu
34329@end example
34330
34331@noindent
34332While I cannot guarantee that I will have time to work on your bug,
34333I do try to fix bugs quickly whenever I can.
34334
34335You can obtain a current version of Calc from anonymous FTP on
34336@samp{csvax.cs.caltech.edu} in @samp{pub/calc-@var{version}.tar.Z}.
34337Calc is also available on the GNU machine, @samp{prep.ai.mit.edu}.
34338Patches are posted to the @samp{comp.sources.misc} Usenet group,
34339and are also available on @code{csvax}.
34340
34341There is an automatic @kbd{M-x report-calc-bug} command which helps
34342you to report bugs. This command prompts you for a brief subject
34343line, then leaves you in a mail editing buffer. Type @kbd{C-c C-c} to
34344send your mail. Make sure your subject line indicates that you are
34345reporting a Calc bug; this command sends mail to my regular mailbox.
34346
34347If you have suggestions for additional features for Calc, I would
34348love to hear them. Some have dared to suggest that Calc is already
34349top-heavy with features; I really don't see what they're talking
34350about, so, if you have ideas, send them right in. (I may even have
34351time to implement them!)
34352
34353At the front of the source file, @file{calc.el}, is a list of ideas for
34354future work which I have not had time to do. If any enthusiastic souls
34355wish to take it upon themselves to work on these, I would be delighted.
34356Please let me know if you plan to contribute to Calc so I can coordinate
34357your efforts with mine and those of others. I will do my best to help
34358you in whatever way I can.
34359
34360@c [summary]
34361@node Summary, Key Index, Reporting Bugs, Top
34362@appendix Calc Summary
34363
34364@noindent
34365This section includes a complete list of Calc 2.02 keystroke commands.
34366Each line lists the stack entries used by the command (top-of-stack
34367last), the keystrokes themselves, the prompts asked by the command,
34368and the result of the command (also with top-of-stack last).
34369The result is expressed using the equivalent algebraic function.
34370Commands which put no results on the stack show the full @kbd{M-x}
34371command name in that position. Numbers preceding the result or
34372command name refer to notes at the end.
34373
34374Algebraic functions and @kbd{M-x} commands that don't have corresponding
34375keystrokes are not listed in this summary.
34376@xref{Command Index}. @xref{Function Index}.
34377
34378@iftex
34379@begingroup
34380@tex
34381\vskip-2\baselineskip \null
34382\gdef\sumrow#1{\sumrowx#1\relax}%
34383\gdef\sumrowx#1\:#2\:#3\:#4\:#5\:#6\relax{%
34384\leavevmode%
34385\hbox to5em{\indsl\hss#1}%
34386\hbox to5em{\ninett#2\hss}%
34387\hbox to4em{\indsl#3\hss}%
34388\hbox to5em{\indrm\hss#4}%
34389\thinspace%
34390{\ninett#5}%
34391{\indsl#6}%
34392}%
34393\gdef\sumlpar{{\indrm(}}%
34394\gdef\sumrpar{{\indrm)}}%
34395\gdef\sumcomma{{\indrm,\thinspace}}%
34396\gdef\sumexcl{{\indrm!}}%
34397\gdef\sumbreak{\vskip-2.5\baselineskip\goodbreak}%
34398\gdef\minus#1{{\tt-}}%
34399@end tex
34400@let@:=@sumsep
34401@let@r=@sumrow
34402@catcode`@(=@active @let(=@sumlpar
34403@catcode`@)=@active @let)=@sumrpar
34404@catcode`@,=@active @let,=@sumcomma
34405@catcode`@!=@active @let!=@sumexcl
34406@end iftex
34407@format
34408@iftex
34409@advance@baselineskip-2.5pt
34410@let@tt@ninett
34411@let@c@sumbreak
34412@end iftex
34413@r{ @: M-# a @: @: 33 @:calc-embedded-activate@:}
34414@r{ @: M-# b @: @: @:calc-big-or-small@:}
34415@r{ @: M-# c @: @: @:calc@:}
34416@r{ @: M-# d @: @: @:calc-embedded-duplicate@:}
34417@r{ @: M-# e @: @: 34 @:calc-embedded@:}
34418@r{ @: M-# f @:formula @: @:calc-embedded-new-formula@:}
34419@r{ @: M-# g @: @: 35 @:calc-grab-region@:}
34420@r{ @: M-# i @: @: @:calc-info@:}
34421@r{ @: M-# j @: @: @:calc-embedded-select@:}
34422@r{ @: M-# k @: @: @:calc-keypad@:}
34423@r{ @: M-# l @: @: @:calc-load-everything@:}
34424@r{ @: M-# m @: @: @:read-kbd-macro@:}
34425@r{ @: M-# n @: @: 4 @:calc-embedded-next@:}
34426@r{ @: M-# o @: @: @:calc-other-window@:}
34427@r{ @: M-# p @: @: 4 @:calc-embedded-previous@:}
34428@r{ @: M-# q @:formula @: @:quick-calc@:}
34429@r{ @: M-# r @: @: 36 @:calc-grab-rectangle@:}
34430@r{ @: M-# s @: @: @:calc-info-summary@:}
34431@r{ @: M-# t @: @: @:calc-tutorial@:}
34432@r{ @: M-# u @: @: @:calc-embedded-update@:}
34433@r{ @: M-# w @: @: @:calc-embedded-word@:}
34434@r{ @: M-# x @: @: @:calc-quit@:}
34435@r{ @: M-# y @: @:1,28,49 @:calc-copy-to-buffer@:}
34436@r{ @: M-# z @: @: @:calc-user-invocation@:}
34437@r{ @: M-# : @: @: 36 @:calc-grab-sum-down@:}
34438@r{ @: M-# _ @: @: 36 @:calc-grab-sum-across@:}
34439@r{ @: M-# ` @:editing @: 30 @:calc-embedded-edit@:}
34440@r{ @: M-# 0 @:(zero) @: @:calc-reset@:}
34441
34442@c
34443@r{ @: 0-9 @:number @: @:@:number}
34444@r{ @: . @:number @: @:@:0.number}
34445@r{ @: _ @:number @: @:-@:number}
34446@r{ @: e @:number @: @:@:1e number}
34447@r{ @: # @:number @: @:@:current-radix@t{#}number}
34448@r{ @: P @:(in number) @: @:+/-@:}
34449@r{ @: M @:(in number) @: @:mod@:}
34450@r{ @: @@ ' " @: (in number)@: @:@:HMS form}
34451@r{ @: h m s @: (in number)@: @:@:HMS form}
34452
34453@c
34454@r{ @: ' @:formula @: 37,46 @:@:formula}
34455@r{ @: $ @:formula @: 37,46 @:$@:formula}
34456@r{ @: " @:string @: 37,46 @:@:string}
34457
34458@c
34459@r{ a b@: + @: @: 2 @:add@:(a,b) a+b}
34460@r{ a b@: - @: @: 2 @:sub@:(a,b) a@minus{}b}
34461@r{ a b@: * @: @: 2 @:mul@:(a,b) a b, a*b}
34462@r{ a b@: / @: @: 2 @:div@:(a,b) a/b}
34463@r{ a b@: ^ @: @: 2 @:pow@:(a,b) a^b}
34464@r{ a b@: I ^ @: @: 2 @:nroot@:(a,b) a^(1/b)}
34465@r{ a b@: % @: @: 2 @:mod@:(a,b) a%b}
34466@r{ a b@: \ @: @: 2 @:idiv@:(a,b) a\b}
34467@r{ a b@: : @: @: 2 @:fdiv@:(a,b)}
34468@r{ a b@: | @: @: 2 @:vconcat@:(a,b) a|b}
34469@r{ a b@: I | @: @: @:vconcat@:(b,a) b|a}
34470@r{ a b@: H | @: @: 2 @:append@:(a,b)}
34471@r{ a b@: I H | @: @: @:append@:(b,a)}
34472@r{ a@: & @: @: 1 @:inv@:(a) 1/a}
34473@r{ a@: ! @: @: 1 @:fact@:(a) a!}
34474@r{ a@: = @: @: 1 @:evalv@:(a)}
34475@r{ a@: M-% @: @: @:percent@:(a) a%}
34476
34477@c
34478@r{ ... a@: RET @: @: 1 @:@:... a a}
34479@r{ ... a@: SPC @: @: 1 @:@:... a a}
34480@r{... a b@: TAB @: @: 3 @:@:... b a}
34481@r{. a b c@: M-TAB @: @: 3 @:@:... b c a}
34482@r{... a b@: LFD @: @: 1 @:@:... a b a}
34483@r{ ... a@: DEL @: @: 1 @:@:...}
34484@r{... a b@: M-DEL @: @: 1 @:@:... b}
34485@r{ @: M-RET @: @: 4 @:calc-last-args@:}
34486@r{ a@: ` @:editing @: 1,30 @:calc-edit@:}
34487
34488@c
34489@r{ ... a@: C-d @: @: 1 @:@:...}
34490@r{ @: C-k @: @: 27 @:calc-kill@:}
34491@r{ @: C-w @: @: 27 @:calc-kill-region@:}
34492@r{ @: C-y @: @: @:calc-yank@:}
34493@r{ @: C-_ @: @: 4 @:calc-undo@:}
34494@r{ @: M-k @: @: 27 @:calc-copy-as-kill@:}
34495@r{ @: M-w @: @: 27 @:calc-copy-region-as-kill@:}
34496
34497@c
34498@r{ @: [ @: @: @:@:[...}
34499@r{[.. a b@: ] @: @: @:@:[a,b]}
34500@r{ @: ( @: @: @:@:(...}
34501@r{(.. a b@: ) @: @: @:@:(a,b)}
34502@r{ @: , @: @: @:@:vector or rect complex}
34503@r{ @: ; @: @: @:@:matrix or polar complex}
34504@r{ @: .. @: @: @:@:interval}
34505
34506@c
34507@r{ @: ~ @: @: @:calc-num-prefix@:}
34508@r{ @: < @: @: 4 @:calc-scroll-left@:}
34509@r{ @: > @: @: 4 @:calc-scroll-right@:}
34510@r{ @: @{ @: @: 4 @:calc-scroll-down@:}
34511@r{ @: @} @: @: 4 @:calc-scroll-up@:}
34512@r{ @: ? @: @: @:calc-help@:}
34513
34514@c
34515@r{ a@: n @: @: 1 @:neg@:(a) @minus{}a}
34516@r{ @: o @: @: 4 @:calc-realign@:}
34517@r{ @: p @:precision @: 31 @:calc-precision@:}
34518@r{ @: q @: @: @:calc-quit@:}
34519@r{ @: w @: @: @:calc-why@:}
34520@r{ @: x @:command @: @:M-x calc-@:command}
34521@r{ a@: y @: @:1,28,49 @:calc-copy-to-buffer@:}
34522
34523@c
34524@r{ a@: A @: @: 1 @:abs@:(a)}
34525@r{ a b@: B @: @: 2 @:log@:(a,b)}
34526@r{ a b@: I B @: @: 2 @:alog@:(a,b) b^a}
34527@r{ a@: C @: @: 1 @:cos@:(a)}
34528@r{ a@: I C @: @: 1 @:arccos@:(a)}
34529@r{ a@: H C @: @: 1 @:cosh@:(a)}
34530@r{ a@: I H C @: @: 1 @:arccosh@:(a)}
34531@r{ @: D @: @: 4 @:calc-redo@:}
34532@r{ a@: E @: @: 1 @:exp@:(a)}
34533@r{ a@: H E @: @: 1 @:exp10@:(a) 10.^a}
34534@r{ a@: F @: @: 1,11 @:floor@:(a,d)}
34535@r{ a@: I F @: @: 1,11 @:ceil@:(a,d)}
34536@r{ a@: H F @: @: 1,11 @:ffloor@:(a,d)}
34537@r{ a@: I H F @: @: 1,11 @:fceil@:(a,d)}
34538@r{ a@: G @: @: 1 @:arg@:(a)}
34539@r{ @: H @:command @: 32 @:@:Hyperbolic}
34540@r{ @: I @:command @: 32 @:@:Inverse}
34541@r{ a@: J @: @: 1 @:conj@:(a)}
34542@r{ @: K @:command @: 32 @:@:Keep-args}
34543@r{ a@: L @: @: 1 @:ln@:(a)}
34544@r{ a@: H L @: @: 1 @:log10@:(a)}
34545@r{ @: M @: @: @:calc-more-recursion-depth@:}
34546@r{ @: I M @: @: @:calc-less-recursion-depth@:}
34547@r{ a@: N @: @: 5 @:evalvn@:(a)}
34548@r{ @: P @: @: @:@:pi}
34549@r{ @: I P @: @: @:@:gamma}
34550@r{ @: H P @: @: @:@:e}
34551@r{ @: I H P @: @: @:@:phi}
34552@r{ a@: Q @: @: 1 @:sqrt@:(a)}
34553@r{ a@: I Q @: @: 1 @:sqr@:(a) a^2}
34554@r{ a@: R @: @: 1,11 @:round@:(a,d)}
34555@r{ a@: I R @: @: 1,11 @:trunc@:(a,d)}
34556@r{ a@: H R @: @: 1,11 @:fround@:(a,d)}
34557@r{ a@: I H R @: @: 1,11 @:ftrunc@:(a,d)}
34558@r{ a@: S @: @: 1 @:sin@:(a)}
34559@r{ a@: I S @: @: 1 @:arcsin@:(a)}
34560@r{ a@: H S @: @: 1 @:sinh@:(a)}
34561@r{ a@: I H S @: @: 1 @:arcsinh@:(a)}
34562@r{ a@: T @: @: 1 @:tan@:(a)}
34563@r{ a@: I T @: @: 1 @:arctan@:(a)}
34564@r{ a@: H T @: @: 1 @:tanh@:(a)}
34565@r{ a@: I H T @: @: 1 @:arctanh@:(a)}
34566@r{ @: U @: @: 4 @:calc-undo@:}
34567@r{ @: X @: @: 4 @:calc-call-last-kbd-macro@:}
34568
34569@c
34570@r{ a b@: a = @: @: 2 @:eq@:(a,b) a=b}
34571@r{ a b@: a # @: @: 2 @:neq@:(a,b) a!=b}
34572@r{ a b@: a < @: @: 2 @:lt@:(a,b) a<b}
34573@r{ a b@: a > @: @: 2 @:gt@:(a,b) a>b}
34574@r{ a b@: a [ @: @: 2 @:leq@:(a,b) a<=b}
34575@r{ a b@: a ] @: @: 2 @:geq@:(a,b) a>=b}
34576@r{ a b@: a @{ @: @: 2 @:in@:(a,b)}
34577@r{ a b@: a & @: @: 2,45 @:land@:(a,b) a&&b}
34578@r{ a b@: a | @: @: 2,45 @:lor@:(a,b) a||b}
34579@r{ a@: a ! @: @: 1,45 @:lnot@:(a) !a}
34580@r{ a b c@: a : @: @: 45 @:if@:(a,b,c) a?b:c}
34581@r{ a@: a . @: @: 1 @:rmeq@:(a)}
34582@r{ a@: a " @: @: 7,8 @:calc-expand-formula@:}
34583
34584@c
34585@r{ a@: a + @:i, l, h @: 6,38 @:sum@:(a,i,l,h)}
34586@r{ a@: a - @:i, l, h @: 6,38 @:asum@:(a,i,l,h)}
34587@r{ a@: a * @:i, l, h @: 6,38 @:prod@:(a,i,l,h)}
34588@r{ a b@: a _ @: @: 2 @:subscr@:(a,b) a_b}
34589
34590@c
34591@r{ a b@: a \ @: @: 2 @:pdiv@:(a,b)}
34592@r{ a b@: a % @: @: 2 @:prem@:(a,b)}
34593@r{ a b@: a / @: @: 2 @:pdivrem@:(a,b) [q,r]}
34594@r{ a b@: H a / @: @: 2 @:pdivide@:(a,b) q+r/b}
34595
34596@c
34597@r{ a@: a a @: @: 1 @:apart@:(a)}
34598@r{ a@: a b @:old, new @: 38 @:subst@:(a,old,new)}
34599@r{ a@: a c @:v @: 38 @:collect@:(a,v)}
34600@r{ a@: a d @:v @: 4,38 @:deriv@:(a,v)}
34601@r{ a@: H a d @:v @: 4,38 @:tderiv@:(a,v)}
34602@r{ a@: a e @: @: @:esimplify@:(a)}
34603@r{ a@: a f @: @: 1 @:factor@:(a)}
34604@r{ a@: H a f @: @: 1 @:factors@:(a)}
34605@r{ a b@: a g @: @: 2 @:pgcd@:(a,b)}
34606@r{ a@: a i @:v @: 38 @:integ@:(a,v)}
34607@r{ a@: a m @:pats @: 38 @:match@:(a,pats)}
34608@r{ a@: I a m @:pats @: 38 @:matchnot@:(a,pats)}
34609@r{ data x@: a p @: @: 28 @:polint@:(data,x)}
34610@r{ data x@: H a p @: @: 28 @:ratint@:(data,x)}
34611@r{ a@: a n @: @: 1 @:nrat@:(a)}
34612@r{ a@: a r @:rules @:4,8,38 @:rewrite@:(a,rules,n)}
34613@r{ a@: a s @: @: @:simplify@:(a)}
34614@r{ a@: a t @:v, n @: 31,39 @:taylor@:(a,v,n)}
34615@r{ a@: a v @: @: 7,8 @:calc-alg-evaluate@:}
34616@r{ a@: a x @: @: 4,8 @:expand@:(a)}
34617
34618@c
34619@r{ data@: a F @:model, vars @: 48 @:fit@:(m,iv,pv,data)}
34620@r{ data@: I a F @:model, vars @: 48 @:xfit@:(m,iv,pv,data)}
34621@r{ data@: H a F @:model, vars @: 48 @:efit@:(m,iv,pv,data)}
34622@r{ a@: a I @:v, l, h @: 38 @:ninteg@:(a,v,l,h)}
34623@r{ a b@: a M @:op @: 22 @:mapeq@:(op,a,b)}
34624@r{ a b@: I a M @:op @: 22 @:mapeqr@:(op,a,b)}
34625@r{ a b@: H a M @:op @: 22 @:mapeqp@:(op,a,b)}
34626@r{ a g@: a N @:v @: 38 @:minimize@:(a,v,g)}
34627@r{ a g@: H a N @:v @: 38 @:wminimize@:(a,v,g)}
34628@r{ a@: a P @:v @: 38 @:roots@:(a,v)}
34629@r{ a g@: a R @:v @: 38 @:root@:(a,v,g)}
34630@r{ a g@: H a R @:v @: 38 @:wroot@:(a,v,g)}
34631@r{ a@: a S @:v @: 38 @:solve@:(a,v)}
34632@r{ a@: I a S @:v @: 38 @:finv@:(a,v)}
34633@r{ a@: H a S @:v @: 38 @:fsolve@:(a,v)}
34634@r{ a@: I H a S @:v @: 38 @:ffinv@:(a,v)}
34635@r{ a@: a T @:i, l, h @: 6,38 @:table@:(a,i,l,h)}
34636@r{ a g@: a X @:v @: 38 @:maximize@:(a,v,g)}
34637@r{ a g@: H a X @:v @: 38 @:wmaximize@:(a,v,g)}
34638
34639@c
34640@r{ a b@: b a @: @: 9 @:and@:(a,b,w)}
34641@r{ a@: b c @: @: 9 @:clip@:(a,w)}
34642@r{ a b@: b d @: @: 9 @:diff@:(a,b,w)}
34643@r{ a@: b l @: @: 10 @:lsh@:(a,n,w)}
34644@r{ a n@: H b l @: @: 9 @:lsh@:(a,n,w)}
34645@r{ a@: b n @: @: 9 @:not@:(a,w)}
34646@r{ a b@: b o @: @: 9 @:or@:(a,b,w)}
34647@r{ v@: b p @: @: 1 @:vpack@:(v)}
34648@r{ a@: b r @: @: 10 @:rsh@:(a,n,w)}
34649@r{ a n@: H b r @: @: 9 @:rsh@:(a,n,w)}
34650@r{ a@: b t @: @: 10 @:rot@:(a,n,w)}
34651@r{ a n@: H b t @: @: 9 @:rot@:(a,n,w)}
34652@r{ a@: b u @: @: 1 @:vunpack@:(a)}
34653@r{ @: b w @:w @: 9,50 @:calc-word-size@:}
34654@r{ a b@: b x @: @: 9 @:xor@:(a,b,w)}
34655
34656@c
34657@r{c s l p@: b D @: @: @:ddb@:(c,s,l,p)}
34658@r{ r n p@: b F @: @: @:fv@:(r,n,p)}
34659@r{ r n p@: I b F @: @: @:fvb@:(r,n,p)}
34660@r{ r n p@: H b F @: @: @:fvl@:(r,n,p)}
34661@r{ v@: b I @: @: 19 @:irr@:(v)}
34662@r{ v@: I b I @: @: 19 @:irrb@:(v)}
34663@r{ a@: b L @: @: 10 @:ash@:(a,n,w)}
34664@r{ a n@: H b L @: @: 9 @:ash@:(a,n,w)}
34665@r{ r n a@: b M @: @: @:pmt@:(r,n,a)}
34666@r{ r n a@: I b M @: @: @:pmtb@:(r,n,a)}
34667@r{ r n a@: H b M @: @: @:pmtl@:(r,n,a)}
34668@r{ r v@: b N @: @: 19 @:npv@:(r,v)}
34669@r{ r v@: I b N @: @: 19 @:npvb@:(r,v)}
34670@r{ r n p@: b P @: @: @:pv@:(r,n,p)}
34671@r{ r n p@: I b P @: @: @:pvb@:(r,n,p)}
34672@r{ r n p@: H b P @: @: @:pvl@:(r,n,p)}
34673@r{ a@: b R @: @: 10 @:rash@:(a,n,w)}
34674@r{ a n@: H b R @: @: 9 @:rash@:(a,n,w)}
34675@r{ c s l@: b S @: @: @:sln@:(c,s,l)}
34676@r{ n p a@: b T @: @: @:rate@:(n,p,a)}
34677@r{ n p a@: I b T @: @: @:rateb@:(n,p,a)}
34678@r{ n p a@: H b T @: @: @:ratel@:(n,p,a)}
34679@r{c s l p@: b Y @: @: @:syd@:(c,s,l,p)}
34680
34681@r{ r p a@: b # @: @: @:nper@:(r,p,a)}
34682@r{ r p a@: I b # @: @: @:nperb@:(r,p,a)}
34683@r{ r p a@: H b # @: @: @:nperl@:(r,p,a)}
34684@r{ a b@: b % @: @: @:relch@:(a,b)}
34685
34686@c
34687@r{ a@: c c @: @: 5 @:pclean@:(a,p)}
34688@r{ a@: c 0-9 @: @: @:pclean@:(a,p)}
34689@r{ a@: H c c @: @: 5 @:clean@:(a,p)}
34690@r{ a@: H c 0-9 @: @: @:clean@:(a,p)}
34691@r{ a@: c d @: @: 1 @:deg@:(a)}
34692@r{ a@: c f @: @: 1 @:pfloat@:(a)}
34693@r{ a@: H c f @: @: 1 @:float@:(a)}
34694@r{ a@: c h @: @: 1 @:hms@:(a)}
34695@r{ a@: c p @: @: @:polar@:(a)}
34696@r{ a@: I c p @: @: @:rect@:(a)}
34697@r{ a@: c r @: @: 1 @:rad@:(a)}
34698
34699@c
34700@r{ a@: c F @: @: 5 @:pfrac@:(a,p)}
34701@r{ a@: H c F @: @: 5 @:frac@:(a,p)}
34702
34703@c
34704@r{ a@: c % @: @: @:percent@:(a*100)}
34705
34706@c
34707@r{ @: d . @:char @: 50 @:calc-point-char@:}
34708@r{ @: d , @:char @: 50 @:calc-group-char@:}
34709@r{ @: d < @: @: 13,50 @:calc-left-justify@:}
34710@r{ @: d = @: @: 13,50 @:calc-center-justify@:}
34711@r{ @: d > @: @: 13,50 @:calc-right-justify@:}
34712@r{ @: d @{ @:label @: 50 @:calc-left-label@:}
34713@r{ @: d @} @:label @: 50 @:calc-right-label@:}
34714@r{ @: d [ @: @: 4 @:calc-truncate-up@:}
34715@r{ @: d ] @: @: 4 @:calc-truncate-down@:}
34716@r{ @: d " @: @: 12,50 @:calc-display-strings@:}
34717@r{ @: d SPC @: @: @:calc-refresh@:}
34718@r{ @: d RET @: @: 1 @:calc-refresh-top@:}
34719
34720@c
34721@r{ @: d 0 @: @: 50 @:calc-decimal-radix@:}
34722@r{ @: d 2 @: @: 50 @:calc-binary-radix@:}
34723@r{ @: d 6 @: @: 50 @:calc-hex-radix@:}
34724@r{ @: d 8 @: @: 50 @:calc-octal-radix@:}
34725
34726@c
34727@r{ @: d b @: @:12,13,50 @:calc-line-breaking@:}
34728@r{ @: d c @: @: 50 @:calc-complex-notation@:}
34729@r{ @: d d @:format @: 50 @:calc-date-notation@:}
34730@r{ @: d e @: @: 5,50 @:calc-eng-notation@:}
34731@r{ @: d f @:num @: 31,50 @:calc-fix-notation@:}
34732@r{ @: d g @: @:12,13,50 @:calc-group-digits@:}
34733@r{ @: d h @:format @: 50 @:calc-hms-notation@:}
34734@r{ @: d i @: @: 50 @:calc-i-notation@:}
34735@r{ @: d j @: @: 50 @:calc-j-notation@:}
34736@r{ @: d l @: @: 12,50 @:calc-line-numbering@:}
34737@r{ @: d n @: @: 5,50 @:calc-normal-notation@:}
34738@r{ @: d o @:format @: 50 @:calc-over-notation@:}
34739@r{ @: d p @: @: 12,50 @:calc-show-plain@:}
34740@r{ @: d r @:radix @: 31,50 @:calc-radix@:}
34741@r{ @: d s @: @: 5,50 @:calc-sci-notation@:}
34742@r{ @: d t @: @: 27 @:calc-truncate-stack@:}
34743@r{ @: d w @: @: 12,13 @:calc-auto-why@:}
34744@r{ @: d z @: @: 12,50 @:calc-leading-zeros@:}
34745
34746@c
34747@r{ @: d B @: @: 50 @:calc-big-language@:}
34748@r{ @: d C @: @: 50 @:calc-c-language@:}
34749@r{ @: d E @: @: 50 @:calc-eqn-language@:}
34750@r{ @: d F @: @: 50 @:calc-fortran-language@:}
34751@r{ @: d M @: @: 50 @:calc-mathematica-language@:}
34752@r{ @: d N @: @: 50 @:calc-normal-language@:}
34753@r{ @: d O @: @: 50 @:calc-flat-language@:}
34754@r{ @: d P @: @: 50 @:calc-pascal-language@:}
34755@r{ @: d T @: @: 50 @:calc-tex-language@:}
34756@r{ @: d U @: @: 50 @:calc-unformatted-language@:}
34757@r{ @: d W @: @: 50 @:calc-maple-language@:}
34758
34759@c
34760@r{ a@: f [ @: @: 4 @:decr@:(a,n)}
34761@r{ a@: f ] @: @: 4 @:incr@:(a,n)}
34762
34763@c
34764@r{ a b@: f b @: @: 2 @:beta@:(a,b)}
34765@r{ a@: f e @: @: 1 @:erf@:(a)}
34766@r{ a@: I f e @: @: 1 @:erfc@:(a)}
34767@r{ a@: f g @: @: 1 @:gamma@:(a)}
34768@r{ a b@: f h @: @: 2 @:hypot@:(a,b)}
34769@r{ a@: f i @: @: 1 @:im@:(a)}
34770@r{ n a@: f j @: @: 2 @:besJ@:(n,a)}
34771@r{ a b@: f n @: @: 2 @:min@:(a,b)}
34772@r{ a@: f r @: @: 1 @:re@:(a)}
34773@r{ a@: f s @: @: 1 @:sign@:(a)}
34774@r{ a b@: f x @: @: 2 @:max@:(a,b)}
34775@r{ n a@: f y @: @: 2 @:besY@:(n,a)}
34776
34777@c
34778@r{ a@: f A @: @: 1 @:abssqr@:(a)}
34779@r{ x a b@: f B @: @: @:betaI@:(x,a,b)}
34780@r{ x a b@: H f B @: @: @:betaB@:(x,a,b)}
34781@r{ a@: f E @: @: 1 @:expm1@:(a)}
34782@r{ a x@: f G @: @: 2 @:gammaP@:(a,x)}
34783@r{ a x@: I f G @: @: 2 @:gammaQ@:(a,x)}
34784@r{ a x@: H f G @: @: 2 @:gammag@:(a,x)}
34785@r{ a x@: I H f G @: @: 2 @:gammaG@:(a,x)}
34786@r{ a b@: f I @: @: 2 @:ilog@:(a,b)}
34787@r{ a b@: I f I @: @: 2 @:alog@:(a,b) b^a}
34788@r{ a@: f L @: @: 1 @:lnp1@:(a)}
34789@r{ a@: f M @: @: 1 @:mant@:(a)}
34790@r{ a@: f Q @: @: 1 @:isqrt@:(a)}
34791@r{ a@: I f Q @: @: 1 @:sqr@:(a) a^2}
34792@r{ a n@: f S @: @: 2 @:scf@:(a,n)}
34793@r{ y x@: f T @: @: @:arctan2@:(y,x)}
34794@r{ a@: f X @: @: 1 @:xpon@:(a)}
34795
34796@c
34797@r{ x y@: g a @: @: 28,40 @:calc-graph-add@:}
34798@r{ @: g b @: @: 12 @:calc-graph-border@:}
34799@r{ @: g c @: @: @:calc-graph-clear@:}
34800@r{ @: g d @: @: 41 @:calc-graph-delete@:}
34801@r{ x y@: g f @: @: 28,40 @:calc-graph-fast@:}
34802@r{ @: g g @: @: 12 @:calc-graph-grid@:}
34803@r{ @: g h @:title @: @:calc-graph-header@:}
34804@r{ @: g j @: @: 4 @:calc-graph-juggle@:}
34805@r{ @: g k @: @: 12 @:calc-graph-key@:}
34806@r{ @: g l @: @: 12 @:calc-graph-log-x@:}
34807@r{ @: g n @:name @: @:calc-graph-name@:}
34808@r{ @: g p @: @: 42 @:calc-graph-plot@:}
34809@r{ @: g q @: @: @:calc-graph-quit@:}
34810@r{ @: g r @:range @: @:calc-graph-range-x@:}
34811@r{ @: g s @: @: 12,13 @:calc-graph-line-style@:}
34812@r{ @: g t @:title @: @:calc-graph-title-x@:}
34813@r{ @: g v @: @: @:calc-graph-view-commands@:}
34814@r{ @: g x @:display @: @:calc-graph-display@:}
34815@r{ @: g z @: @: 12 @:calc-graph-zero-x@:}
34816
34817@c
34818@r{ x y z@: g A @: @: 28,40 @:calc-graph-add-3d@:}
34819@r{ @: g C @:command @: @:calc-graph-command@:}
34820@r{ @: g D @:device @: 43,44 @:calc-graph-device@:}
34821@r{ x y z@: g F @: @: 28,40 @:calc-graph-fast-3d@:}
34822@r{ @: g H @: @: 12 @:calc-graph-hide@:}
34823@r{ @: g K @: @: @:calc-graph-kill@:}
34824@r{ @: g L @: @: 12 @:calc-graph-log-y@:}
34825@r{ @: g N @:number @: 43,51 @:calc-graph-num-points@:}
34826@r{ @: g O @:filename @: 43,44 @:calc-graph-output@:}
34827@r{ @: g P @: @: 42 @:calc-graph-print@:}
34828@r{ @: g R @:range @: @:calc-graph-range-y@:}
34829@r{ @: g S @: @: 12,13 @:calc-graph-point-style@:}
34830@r{ @: g T @:title @: @:calc-graph-title-y@:}
34831@r{ @: g V @: @: @:calc-graph-view-trail@:}
34832@r{ @: g X @:format @: @:calc-graph-geometry@:}
34833@r{ @: g Z @: @: 12 @:calc-graph-zero-y@:}
34834
34835@c
34836@r{ @: g C-l @: @: 12 @:calc-graph-log-z@:}
34837@r{ @: g C-r @:range @: @:calc-graph-range-z@:}
34838@r{ @: g C-t @:title @: @:calc-graph-title-z@:}
34839
34840@c
34841@r{ @: h b @: @: @:calc-describe-bindings@:}
34842@r{ @: h c @:key @: @:calc-describe-key-briefly@:}
34843@r{ @: h f @:function @: @:calc-describe-function@:}
34844@r{ @: h h @: @: @:calc-full-help@:}
34845@r{ @: h i @: @: @:calc-info@:}
34846@r{ @: h k @:key @: @:calc-describe-key@:}
34847@r{ @: h n @: @: @:calc-view-news@:}
34848@r{ @: h s @: @: @:calc-info-summary@:}
34849@r{ @: h t @: @: @:calc-tutorial@:}
34850@r{ @: h v @:var @: @:calc-describe-variable@:}
34851
34852@c
34853@r{ @: j 1-9 @: @: @:calc-select-part@:}
34854@r{ @: j RET @: @: 27 @:calc-copy-selection@:}
34855@r{ @: j DEL @: @: 27 @:calc-del-selection@:}
34856@r{ @: j ' @:formula @: 27 @:calc-enter-selection@:}
34857@r{ @: j ` @:editing @: 27,30 @:calc-edit-selection@:}
34858@r{ @: j " @: @: 7,27 @:calc-sel-expand-formula@:}
34859
34860@c
34861@r{ @: j + @:formula @: 27 @:calc-sel-add-both-sides@:}
34862@r{ @: j - @:formula @: 27 @:calc-sel-sub-both-sides@:}
34863@r{ @: j * @:formula @: 27 @:calc-sel-mul-both-sides@:}
34864@r{ @: j / @:formula @: 27 @:calc-sel-div-both-sides@:}
34865@r{ @: j & @: @: 27 @:calc-sel-invert@:}
34866
34867@c
34868@r{ @: j a @: @: 27 @:calc-select-additional@:}
34869@r{ @: j b @: @: 12 @:calc-break-selections@:}
34870@r{ @: j c @: @: @:calc-clear-selections@:}
34871@r{ @: j d @: @: 12,50 @:calc-show-selections@:}
34872@r{ @: j e @: @: 12 @:calc-enable-selections@:}
34873@r{ @: j l @: @: 4,27 @:calc-select-less@:}
34874@r{ @: j m @: @: 4,27 @:calc-select-more@:}
34875@r{ @: j n @: @: 4 @:calc-select-next@:}
34876@r{ @: j o @: @: 4,27 @:calc-select-once@:}
34877@r{ @: j p @: @: 4 @:calc-select-previous@:}
34878@r{ @: j r @:rules @:4,8,27 @:calc-rewrite-selection@:}
34879@r{ @: j s @: @: 4,27 @:calc-select-here@:}
34880@r{ @: j u @: @: 27 @:calc-unselect@:}
34881@r{ @: j v @: @: 7,27 @:calc-sel-evaluate@:}
34882
34883@c
34884@r{ @: j C @: @: 27 @:calc-sel-commute@:}
34885@r{ @: j D @: @: 4,27 @:calc-sel-distribute@:}
34886@r{ @: j E @: @: 27 @:calc-sel-jump-equals@:}
34887@r{ @: j I @: @: 27 @:calc-sel-isolate@:}
34888@r{ @: H j I @: @: 27 @:calc-sel-isolate@: (full)}
34889@r{ @: j L @: @: 4,27 @:calc-commute-left@:}
34890@r{ @: j M @: @: 27 @:calc-sel-merge@:}
34891@r{ @: j N @: @: 27 @:calc-sel-negate@:}
34892@r{ @: j O @: @: 4,27 @:calc-select-once-maybe@:}
34893@r{ @: j R @: @: 4,27 @:calc-commute-right@:}
34894@r{ @: j S @: @: 4,27 @:calc-select-here-maybe@:}
34895@r{ @: j U @: @: 27 @:calc-sel-unpack@:}
34896
34897@c
34898@r{ @: k a @: @: @:calc-random-again@:}
34899@r{ n@: k b @: @: 1 @:bern@:(n)}
34900@r{ n x@: H k b @: @: 2 @:bern@:(n,x)}
34901@r{ n m@: k c @: @: 2 @:choose@:(n,m)}
34902@r{ n m@: H k c @: @: 2 @:perm@:(n,m)}
34903@r{ n@: k d @: @: 1 @:dfact@:(n) n!!}
34904@r{ n@: k e @: @: 1 @:euler@:(n)}
34905@r{ n x@: H k e @: @: 2 @:euler@:(n,x)}
34906@r{ n@: k f @: @: 4 @:prfac@:(n)}
34907@r{ n m@: k g @: @: 2 @:gcd@:(n,m)}
34908@r{ m n@: k h @: @: 14 @:shuffle@:(n,m)}
34909@r{ n m@: k l @: @: 2 @:lcm@:(n,m)}
34910@r{ n@: k m @: @: 1 @:moebius@:(n)}
34911@r{ n@: k n @: @: 4 @:nextprime@:(n)}
34912@r{ n@: I k n @: @: 4 @:prevprime@:(n)}
34913@r{ n@: k p @: @: 4,28 @:calc-prime-test@:}
34914@r{ m@: k r @: @: 14 @:random@:(m)}
34915@r{ n m@: k s @: @: 2 @:stir1@:(n,m)}
34916@r{ n m@: H k s @: @: 2 @:stir2@:(n,m)}
34917@r{ n@: k t @: @: 1 @:totient@:(n)}
34918
34919@c
34920@r{ n p x@: k B @: @: @:utpb@:(x,n,p)}
34921@r{ n p x@: I k B @: @: @:ltpb@:(x,n,p)}
34922@r{ v x@: k C @: @: @:utpc@:(x,v)}
34923@r{ v x@: I k C @: @: @:ltpc@:(x,v)}
34924@r{ n m@: k E @: @: @:egcd@:(n,m)}
34925@r{v1 v2 x@: k F @: @: @:utpf@:(x,v1,v2)}
34926@r{v1 v2 x@: I k F @: @: @:ltpf@:(x,v1,v2)}
34927@r{ m s x@: k N @: @: @:utpn@:(x,m,s)}
34928@r{ m s x@: I k N @: @: @:ltpn@:(x,m,s)}
34929@r{ m x@: k P @: @: @:utpp@:(x,m)}
34930@r{ m x@: I k P @: @: @:ltpp@:(x,m)}
34931@r{ v x@: k T @: @: @:utpt@:(x,v)}
34932@r{ v x@: I k T @: @: @:ltpt@:(x,v)}
34933
34934@c
34935@r{ @: m a @: @: 12,13 @:calc-algebraic-mode@:}
34936@r{ @: m d @: @: @:calc-degrees-mode@:}
34937@r{ @: m f @: @: 12 @:calc-frac-mode@:}
34938@r{ @: m g @: @: 52 @:calc-get-modes@:}
34939@r{ @: m h @: @: @:calc-hms-mode@:}
34940@r{ @: m i @: @: 12,13 @:calc-infinite-mode@:}
34941@r{ @: m m @: @: @:calc-save-modes@:}
34942@r{ @: m p @: @: 12 @:calc-polar-mode@:}
34943@r{ @: m r @: @: @:calc-radians-mode@:}
34944@r{ @: m s @: @: 12 @:calc-symbolic-mode@:}
34945@r{ @: m t @: @: 12 @:calc-total-algebraic-mode@:}
34946@r{ @: m v @: @: 12,13 @:calc-matrix-mode@:}
34947@r{ @: m w @: @: 13 @:calc-working@:}
34948@r{ @: m x @: @: @:calc-always-load-extensions@:}
34949
34950@c
34951@r{ @: m A @: @: 12 @:calc-alg-simplify-mode@:}
34952@r{ @: m B @: @: 12 @:calc-bin-simplify-mode@:}
34953@r{ @: m C @: @: 12 @:calc-auto-recompute@:}
34954@r{ @: m D @: @: @:calc-default-simplify-mode@:}
34955@r{ @: m E @: @: 12 @:calc-ext-simplify-mode@:}
34956@r{ @: m F @:filename @: 13 @:calc-settings-file-name@:}
34957@r{ @: m N @: @: 12 @:calc-num-simplify-mode@:}
34958@r{ @: m O @: @: 12 @:calc-no-simplify-mode@:}
34959@r{ @: m R @: @: 12,13 @:calc-mode-record-mode@:}
34960@r{ @: m S @: @: 12 @:calc-shift-prefix@:}
34961@r{ @: m U @: @: 12 @:calc-units-simplify-mode@:}
34962
34963@c
34964@r{ @: s c @:var1, var2 @: 29 @:calc-copy-variable@:}
34965@r{ @: s d @:var, decl @: @:calc-declare-variable@:}
34966@r{ @: s e @:var, editing @: 29,30 @:calc-edit-variable@:}
34967@r{ @: s i @:buffer @: @:calc-insert-variables@:}
34968@r{ a b@: s l @:var @: 29 @:@:a (letting var=b)}
34969@r{ a ...@: s m @:op, var @: 22,29 @:calc-store-map@:}
34970@r{ @: s n @:var @: 29,47 @:calc-store-neg@: (v/-1)}
34971@r{ @: s p @:var @: 29 @:calc-permanent-variable@:}
34972@r{ @: s r @:var @: 29 @:@:v (recalled value)}
34973@r{ @: r 0-9 @: @: @:calc-recall-quick@:}
34974@r{ a@: s s @:var @: 28,29 @:calc-store@:}
34975@r{ a@: s 0-9 @: @: @:calc-store-quick@:}
34976@r{ a@: s t @:var @: 29 @:calc-store-into@:}
34977@r{ a@: t 0-9 @: @: @:calc-store-into-quick@:}
34978@r{ @: s u @:var @: 29 @:calc-unstore@:}
34979@r{ a@: s x @:var @: 29 @:calc-store-exchange@:}
34980
34981@c
34982@r{ @: s A @:editing @: 30 @:calc-edit-AlgSimpRules@:}
34983@r{ @: s D @:editing @: 30 @:calc-edit-Decls@:}
34984@r{ @: s E @:editing @: 30 @:calc-edit-EvalRules@:}
34985@r{ @: s F @:editing @: 30 @:calc-edit-FitRules@:}
34986@r{ @: s G @:editing @: 30 @:calc-edit-GenCount@:}
34987@r{ @: s H @:editing @: 30 @:calc-edit-Holidays@:}
34988@r{ @: s I @:editing @: 30 @:calc-edit-IntegLimit@:}
34989@r{ @: s L @:editing @: 30 @:calc-edit-LineStyles@:}
34990@r{ @: s P @:editing @: 30 @:calc-edit-PointStyles@:}
34991@r{ @: s R @:editing @: 30 @:calc-edit-PlotRejects@:}
34992@r{ @: s T @:editing @: 30 @:calc-edit-TimeZone@:}
34993@r{ @: s U @:editing @: 30 @:calc-edit-Units@:}
34994@r{ @: s X @:editing @: 30 @:calc-edit-ExtSimpRules@:}
34995
34996@c
34997@r{ a@: s + @:var @: 29,47 @:calc-store-plus@: (v+a)}
34998@r{ a@: s - @:var @: 29,47 @:calc-store-minus@: (v-a)}
34999@r{ a@: s * @:var @: 29,47 @:calc-store-times@: (v*a)}
35000@r{ a@: s / @:var @: 29,47 @:calc-store-div@: (v/a)}
35001@r{ a@: s ^ @:var @: 29,47 @:calc-store-power@: (v^a)}
35002@r{ a@: s | @:var @: 29,47 @:calc-store-concat@: (v|a)}
35003@r{ @: s & @:var @: 29,47 @:calc-store-inv@: (v^-1)}
35004@r{ @: s [ @:var @: 29,47 @:calc-store-decr@: (v-1)}
35005@r{ @: s ] @:var @: 29,47 @:calc-store-incr@: (v-(-1))}
35006@r{ a b@: s : @: @: 2 @:assign@:(a,b) a @t{:=} b}
35007@r{ a@: s = @: @: 1 @:evalto@:(a,b) a @t{=>}}
35008
35009@c
35010@r{ @: t [ @: @: 4 @:calc-trail-first@:}
35011@r{ @: t ] @: @: 4 @:calc-trail-last@:}
35012@r{ @: t < @: @: 4 @:calc-trail-scroll-left@:}
35013@r{ @: t > @: @: 4 @:calc-trail-scroll-right@:}
35014@r{ @: t . @: @: 12 @:calc-full-trail-vectors@:}
35015
35016@c
35017@r{ @: t b @: @: 4 @:calc-trail-backward@:}
35018@r{ @: t d @: @: 12,50 @:calc-trail-display@:}
35019@r{ @: t f @: @: 4 @:calc-trail-forward@:}
35020@r{ @: t h @: @: @:calc-trail-here@:}
35021@r{ @: t i @: @: @:calc-trail-in@:}
35022@r{ @: t k @: @: 4 @:calc-trail-kill@:}
35023@r{ @: t m @:string @: @:calc-trail-marker@:}
35024@r{ @: t n @: @: 4 @:calc-trail-next@:}
35025@r{ @: t o @: @: @:calc-trail-out@:}
35026@r{ @: t p @: @: 4 @:calc-trail-previous@:}
35027@r{ @: t r @:string @: @:calc-trail-isearch-backward@:}
35028@r{ @: t s @:string @: @:calc-trail-isearch-forward@:}
35029@r{ @: t y @: @: 4 @:calc-trail-yank@:}
35030
35031@c
35032@r{ d@: t C @:oz, nz @: @:tzconv@:(d,oz,nz)}
35033@r{d oz nz@: t C @:$ @: @:tzconv@:(d,oz,nz)}
35034@r{ d@: t D @: @: 15 @:date@:(d)}
35035@r{ d@: t I @: @: 4 @:incmonth@:(d,n)}
35036@r{ d@: t J @: @: 16 @:julian@:(d,z)}
35037@r{ d@: t M @: @: 17 @:newmonth@:(d,n)}
35038@r{ @: t N @: @: 16 @:now@:(z)}
35039@r{ d@: t P @:1 @: 31 @:year@:(d)}
35040@r{ d@: t P @:2 @: 31 @:month@:(d)}
35041@r{ d@: t P @:3 @: 31 @:day@:(d)}
35042@r{ d@: t P @:4 @: 31 @:hour@:(d)}
35043@r{ d@: t P @:5 @: 31 @:minute@:(d)}
35044@r{ d@: t P @:6 @: 31 @:second@:(d)}
35045@r{ d@: t P @:7 @: 31 @:weekday@:(d)}
35046@r{ d@: t P @:8 @: 31 @:yearday@:(d)}
35047@r{ d@: t P @:9 @: 31 @:time@:(d)}
35048@r{ d@: t U @: @: 16 @:unixtime@:(d,z)}
35049@r{ d@: t W @: @: 17 @:newweek@:(d,w)}
35050@r{ d@: t Y @: @: 17 @:newyear@:(d,n)}
35051
35052@c
35053@r{ a b@: t + @: @: 2 @:badd@:(a,b)}
35054@r{ a b@: t - @: @: 2 @:bsub@:(a,b)}
35055
35056@c
35057@r{ @: u a @: @: 12 @:calc-autorange-units@:}
35058@r{ a@: u b @: @: @:calc-base-units@:}
35059@r{ a@: u c @:units @: 18 @:calc-convert-units@:}
35060@r{ defn@: u d @:unit, descr @: @:calc-define-unit@:}
35061@r{ @: u e @: @: @:calc-explain-units@:}
35062@r{ @: u g @:unit @: @:calc-get-unit-definition@:}
35063@r{ @: u p @: @: @:calc-permanent-units@:}
35064@r{ a@: u r @: @: @:calc-remove-units@:}
35065@r{ a@: u s @: @: @:usimplify@:(a)}
35066@r{ a@: u t @:units @: 18 @:calc-convert-temperature@:}
35067@r{ @: u u @:unit @: @:calc-undefine-unit@:}
35068@r{ @: u v @: @: @:calc-enter-units-table@:}
35069@r{ a@: u x @: @: @:calc-extract-units@:}
35070@r{ a@: u 0-9 @: @: @:calc-quick-units@:}
35071
35072@c
35073@r{ v1 v2@: u C @: @: 20 @:vcov@:(v1,v2)}
35074@r{ v1 v2@: I u C @: @: 20 @:vpcov@:(v1,v2)}
35075@r{ v1 v2@: H u C @: @: 20 @:vcorr@:(v1,v2)}
35076@r{ v@: u G @: @: 19 @:vgmean@:(v)}
35077@r{ a b@: H u G @: @: 2 @:agmean@:(a,b)}
35078@r{ v@: u M @: @: 19 @:vmean@:(v)}
35079@r{ v@: I u M @: @: 19 @:vmeane@:(v)}
35080@r{ v@: H u M @: @: 19 @:vmedian@:(v)}
35081@r{ v@: I H u M @: @: 19 @:vhmean@:(v)}
35082@r{ v@: u N @: @: 19 @:vmin@:(v)}
35083@r{ v@: u S @: @: 19 @:vsdev@:(v)}
35084@r{ v@: I u S @: @: 19 @:vpsdev@:(v)}
35085@r{ v@: H u S @: @: 19 @:vvar@:(v)}
35086@r{ v@: I H u S @: @: 19 @:vpvar@:(v)}
35087@r{ @: u V @: @: @:calc-view-units-table@:}
35088@r{ v@: u X @: @: 19 @:vmax@:(v)}
35089
35090@c
35091@r{ v@: u + @: @: 19 @:vsum@:(v)}
35092@r{ v@: u * @: @: 19 @:vprod@:(v)}
35093@r{ v@: u # @: @: 19 @:vcount@:(v)}
35094
35095@c
35096@r{ @: V ( @: @: 50 @:calc-vector-parens@:}
35097@r{ @: V @{ @: @: 50 @:calc-vector-braces@:}
35098@r{ @: V [ @: @: 50 @:calc-vector-brackets@:}
35099@r{ @: V ] @:ROCP @: 50 @:calc-matrix-brackets@:}
35100@r{ @: V , @: @: 50 @:calc-vector-commas@:}
35101@r{ @: V < @: @: 50 @:calc-matrix-left-justify@:}
35102@r{ @: V = @: @: 50 @:calc-matrix-center-justify@:}
35103@r{ @: V > @: @: 50 @:calc-matrix-right-justify@:}
35104@r{ @: V / @: @: 12,50 @:calc-break-vectors@:}
35105@r{ @: V . @: @: 12,50 @:calc-full-vectors@:}
35106
35107@c
35108@r{ s t@: V ^ @: @: 2 @:vint@:(s,t)}
35109@r{ s t@: V - @: @: 2 @:vdiff@:(s,t)}
35110@r{ s@: V ~ @: @: 1 @:vcompl@:(s)}
35111@r{ s@: V # @: @: 1 @:vcard@:(s)}
35112@r{ s@: V : @: @: 1 @:vspan@:(s)}
35113@r{ s@: V + @: @: 1 @:rdup@:(s)}
35114
35115@c
35116@r{ m@: V & @: @: 1 @:inv@:(m) 1/m}
35117
35118@c
35119@r{ v@: v a @:n @: @:arrange@:(v,n)}
35120@r{ a@: v b @:n @: @:cvec@:(a,n)}
35121@r{ v@: v c @:n >0 @: 21,31 @:mcol@:(v,n)}
35122@r{ v@: v c @:n <0 @: 31 @:mrcol@:(v,-n)}
35123@r{ m@: v c @:0 @: 31 @:getdiag@:(m)}
35124@r{ v@: v d @: @: 25 @:diag@:(v,n)}
35125@r{ v m@: v e @: @: 2 @:vexp@:(v,m)}
35126@r{ v m f@: H v e @: @: 2 @:vexp@:(v,m,f)}
35127@r{ v a@: v f @: @: 26 @:find@:(v,a,n)}
35128@r{ v@: v h @: @: 1 @:head@:(v)}
35129@r{ v@: I v h @: @: 1 @:tail@:(v)}
35130@r{ v@: H v h @: @: 1 @:rhead@:(v)}
35131@r{ v@: I H v h @: @: 1 @:rtail@:(v)}
35132@r{ @: v i @:n @: 31 @:idn@:(1,n)}
35133@r{ @: v i @:0 @: 31 @:idn@:(1)}
35134@r{ h t@: v k @: @: 2 @:cons@:(h,t)}
35135@r{ h t@: H v k @: @: 2 @:rcons@:(h,t)}
35136@r{ v@: v l @: @: 1 @:vlen@:(v)}
35137@r{ v@: H v l @: @: 1 @:mdims@:(v)}
35138@r{ v m@: v m @: @: 2 @:vmask@:(v,m)}
35139@r{ v@: v n @: @: 1 @:rnorm@:(v)}
35140@r{ a b c@: v p @: @: 24 @:calc-pack@:}
35141@r{ v@: v r @:n >0 @: 21,31 @:mrow@:(v,n)}
35142@r{ v@: v r @:n <0 @: 31 @:mrrow@:(v,-n)}
35143@r{ m@: v r @:0 @: 31 @:getdiag@:(m)}
35144@r{ v i j@: v s @: @: @:subvec@:(v,i,j)}
35145@r{ v i j@: I v s @: @: @:rsubvec@:(v,i,j)}
35146@r{ m@: v t @: @: 1 @:trn@:(m)}
35147@r{ v@: v u @: @: 24 @:calc-unpack@:}
35148@r{ v@: v v @: @: 1 @:rev@:(v)}
35149@r{ @: v x @:n @: 31 @:index@:(n)}
35150@r{ n s i@: C-u v x @: @: @:index@:(n,s,i)}
35151
35152@c
35153@r{ v@: V A @:op @: 22 @:apply@:(op,v)}
35154@r{ v1 v2@: V C @: @: 2 @:cross@:(v1,v2)}
35155@r{ m@: V D @: @: 1 @:det@:(m)}
35156@r{ s@: V E @: @: 1 @:venum@:(s)}
35157@r{ s@: V F @: @: 1 @:vfloor@:(s)}
35158@r{ v@: V G @: @: @:grade@:(v)}
35159@r{ v@: I V G @: @: @:rgrade@:(v)}
35160@r{ v@: V H @:n @: 31 @:histogram@:(v,n)}
35161@r{ v w@: H V H @:n @: 31 @:histogram@:(v,w,n)}
35162@r{ v1 v2@: V I @:mop aop @: 22 @:inner@:(mop,aop,v1,v2)}
35163@r{ m@: V J @: @: 1 @:ctrn@:(m)}
35164@r{ m@: V L @: @: 1 @:lud@:(m)}
35165@r{ v@: V M @:op @: 22,23 @:map@:(op,v)}
35166@r{ v@: V N @: @: 1 @:cnorm@:(v)}
35167@r{ v1 v2@: V O @:op @: 22 @:outer@:(op,v1,v2)}
35168@r{ v@: V R @:op @: 22,23 @:reduce@:(op,v)}
35169@r{ v@: I V R @:op @: 22,23 @:rreduce@:(op,v)}
35170@r{ a n@: H V R @:op @: 22 @:nest@:(op,a,n)}
35171@r{ a@: I H V R @:op @: 22 @:fixp@:(op,a)}
35172@r{ v@: V S @: @: @:sort@:(v)}
35173@r{ v@: I V S @: @: @:rsort@:(v)}
35174@r{ m@: V T @: @: 1 @:tr@:(m)}
35175@r{ v@: V U @:op @: 22 @:accum@:(op,v)}
35176@r{ v@: I V U @:op @: 22 @:raccum@:(op,v)}
35177@r{ a n@: H V U @:op @: 22 @:anest@:(op,a,n)}
35178@r{ a@: I H V U @:op @: 22 @:afixp@:(op,a)}
35179@r{ s t@: V V @: @: 2 @:vunion@:(s,t)}
35180@r{ s t@: V X @: @: 2 @:vxor@:(s,t)}
35181
35182@c
35183@r{ @: Y @: @: @:@:user commands}
35184
35185@c
35186@r{ @: z @: @: @:@:user commands}
35187
35188@c
35189@r{ c@: Z [ @: @: 45 @:calc-kbd-if@:}
35190@r{ c@: Z | @: @: 45 @:calc-kbd-else-if@:}
35191@r{ @: Z : @: @: @:calc-kbd-else@:}
35192@r{ @: Z ] @: @: @:calc-kbd-end-if@:}
35193
35194@c
35195@r{ @: Z @{ @: @: 4 @:calc-kbd-loop@:}
35196@r{ c@: Z / @: @: 45 @:calc-kbd-break@:}
35197@r{ @: Z @} @: @: @:calc-kbd-end-loop@:}
35198@r{ n@: Z < @: @: @:calc-kbd-repeat@:}
35199@r{ @: Z > @: @: @:calc-kbd-end-repeat@:}
35200@r{ n m@: Z ( @: @: @:calc-kbd-for@:}
35201@r{ s@: Z ) @: @: @:calc-kbd-end-for@:}
35202
35203@c
35204@r{ @: Z C-g @: @: @:@:cancel if/loop command}
35205
35206@c
35207@r{ @: Z ` @: @: @:calc-kbd-push@:}
35208@r{ @: Z ' @: @: @:calc-kbd-pop@:}
35209@r{ a@: Z = @:message @: 28 @:calc-kbd-report@:}
35210@r{ @: Z # @:prompt @: @:calc-kbd-query@:}
35211
35212@c
35213@r{ comp@: Z C @:func, args @: 50 @:calc-user-define-composition@:}
35214@r{ @: Z D @:key, command @: @:calc-user-define@:}
35215@r{ @: Z E @:key, editing @: 30 @:calc-user-define-edit@:}
35216@r{ defn@: Z F @:k, c, f, a, n@: 28 @:calc-user-define-formula@:}
35217@r{ @: Z G @:key @: @:calc-get-user-defn@:}
35218@r{ @: Z I @: @: @:calc-user-define-invocation@:}
35219@r{ @: Z K @:key, command @: @:calc-user-define-kbd-macro@:}
35220@r{ @: Z P @:key @: @:calc-user-define-permanent@:}
35221@r{ @: Z S @: @: 30 @:calc-edit-user-syntax@:}
35222@r{ @: Z T @: @: 12 @:calc-timing@:}
35223@r{ @: Z U @:key @: @:calc-user-undefine@:}
35224
35225@end format
35226
35227@noindent
35228NOTES
35229
35230@enumerate
35231@c 1
35232@item
35233Positive prefix arguments apply to @cite{n} stack entries.
35234Negative prefix arguments apply to the @cite{-n}th stack entry.
35235A prefix of zero applies to the entire stack. (For @key{LFD} and
35236@kbd{M-DEL}, the meaning of the sign is reversed.)
35237
35238@c 2
35239@item
35240Positive prefix arguments apply to @cite{n} stack entries.
35241Negative prefix arguments apply to the top stack entry
35242and the next @cite{-n} stack entries.
35243
35244@c 3
35245@item
35246Positive prefix arguments rotate top @cite{n} stack entries by one.
35247Negative prefix arguments rotate the entire stack by @cite{-n}.
35248A prefix of zero reverses the entire stack.
35249
35250@c 4
35251@item
35252Prefix argument specifies a repeat count or distance.
35253
35254@c 5
35255@item
35256Positive prefix arguments specify a precision @cite{p}.
35257Negative prefix arguments reduce the current precision by @cite{-p}.
35258
35259@c 6
35260@item
35261A prefix argument is interpreted as an additional step-size parameter.
35262A plain @kbd{C-u} prefix means to prompt for the step size.
35263
35264@c 7
35265@item
35266A prefix argument specifies simplification level and depth.
352671=Default, 2=like @kbd{a s}, 3=like @kbd{a e}.
35268
35269@c 8
35270@item
35271A negative prefix operates only on the top level of the input formula.
35272
35273@c 9
35274@item
35275Positive prefix arguments specify a word size of @cite{w} bits, unsigned.
35276Negative prefix arguments specify a word size of @cite{w} bits, signed.
35277
35278@c 10
35279@item
35280Prefix arguments specify the shift amount @cite{n}. The @cite{w} argument
35281cannot be specified in the keyboard version of this command.
35282
35283@c 11
35284@item
35285From the keyboard, @cite{d} is omitted and defaults to zero.
35286
35287@c 12
35288@item
35289Mode is toggled; a positive prefix always sets the mode, and a negative
35290prefix always clears the mode.
35291
35292@c 13
35293@item
35294Some prefix argument values provide special variations of the mode.
35295
35296@c 14
35297@item
35298A prefix argument, if any, is used for @cite{m} instead of taking
35299@cite{m} from the stack. @cite{M} may take any of these values:
35300@iftex
35301{@advance@tableindent10pt
35302@end iftex
35303@table @asis
35304@item Integer
35305Random integer in the interval @cite{[0 .. m)}.
35306@item Float
35307Random floating-point number in the interval @cite{[0 .. m)}.
35308@item 0.0
35309Gaussian with mean 1 and standard deviation 0.
35310@item Error form
35311Gaussian with specified mean and standard deviation.
35312@item Interval
35313Random integer or floating-point number in that interval.
35314@item Vector
35315Random element from the vector.
35316@end table
35317@iftex
35318}
35319@end iftex
35320
35321@c 15
35322@item
35323A prefix argument from 1 to 6 specifies number of date components
35324to remove from the stack. @xref{Date Conversions}.
35325
35326@c 16
35327@item
35328A prefix argument specifies a time zone; @kbd{C-u} says to take the
35329time zone number or name from the top of the stack. @xref{Time Zones}.
35330
35331@c 17
35332@item
35333A prefix argument specifies a day number (0-6, 0-31, or 0-366).
35334
35335@c 18
35336@item
35337If the input has no units, you will be prompted for both the old and
35338the new units.
35339
35340@c 19
35341@item
35342With a prefix argument, collect that many stack entries to form the
35343input data set. Each entry may be a single value or a vector of values.
35344
35345@c 20
35346@item
35347With a prefix argument of 1, take a single @c{$N\times2$}
35348@asis{Nx2} matrix from the
35349stack instead of two separate data vectors.
35350
35351@c 21
35352@item
35353The row or column number @cite{n} may be given as a numeric prefix
35354argument instead. A plain @kbd{C-u} prefix says to take @cite{n}
35355from the top of the stack. If @cite{n} is a vector or interval,
35356a subvector/submatrix of the input is created.
35357
35358@c 22
35359@item
35360The @cite{op} prompt can be answered with the key sequence for the
35361desired function, or with @kbd{x} or @kbd{z} followed by a function name,
35362or with @kbd{$} to take a formula from the top of the stack, or with
35363@kbd{'} and a typed formula. In the last two cases, the formula may
35364be a nameless function like @samp{<#1+#2>} or @samp{<x, y : x+y>}, or it
35365may include @kbd{$}, @kbd{$$}, etc. (where @kbd{$} will correspond to the
35366last argument of the created function), or otherwise you will be
35367prompted for an argument list. The number of vectors popped from the
35368stack by @kbd{V M} depends on the number of arguments of the function.
35369
35370@c 23
35371@item
35372One of the mapping direction keys @kbd{_} (horizontal, i.e., map
35373by rows or reduce across), @kbd{:} (vertical, i.e., map by columns or
35374reduce down), or @kbd{=} (map or reduce by rows) may be used before
35375entering @cite{op}; these modify the function name by adding the letter
35376@code{r} for ``rows,'' @code{c} for ``columns,'' @code{a} for ``across,''
35377or @code{d} for ``down.''
35378
35379@c 24
35380@item
35381The prefix argument specifies a packing mode. A nonnegative mode
35382is the number of items (for @kbd{v p}) or the number of levels
35383(for @kbd{v u}). A negative mode is as described below. With no
35384prefix argument, the mode is taken from the top of the stack and
35385may be an integer or a vector of integers.
35386@iftex
35387{@advance@tableindent-20pt
35388@end iftex
35389@table @cite
35390@item -1
35391@var{(2)} Rectangular complex number.
35392@item -2
35393@var{(2)} Polar complex number.
35394@item -3
35395@var{(3)} HMS form.
35396@item -4
35397@var{(2)} Error form.
35398@item -5
35399@var{(2)} Modulo form.
35400@item -6
35401@var{(2)} Closed interval.
35402@item -7
35403@var{(2)} Closed .. open interval.
35404@item -8
35405@var{(2)} Open .. closed interval.
35406@item -9
35407@var{(2)} Open interval.
35408@item -10
35409@var{(2)} Fraction.
35410@item -11
35411@var{(2)} Float with integer mantissa.
35412@item -12
35413@var{(2)} Float with mantissa in @cite{[1 .. 10)}.
35414@item -13
35415@var{(1)} Date form (using date numbers).
35416@item -14
35417@var{(3)} Date form (using year, month, day).
35418@item -15
35419@var{(6)} Date form (using year, month, day, hour, minute, second).
35420@end table
35421@iftex
35422}
35423@end iftex
35424
35425@c 25
35426@item
35427A prefix argument specifies the size @cite{n} of the matrix. With no
35428prefix argument, @cite{n} is omitted and the size is inferred from
35429the input vector.
35430
35431@c 26
35432@item
35433The prefix argument specifies the starting position @cite{n} (default 1).
35434
35435@c 27
35436@item
35437Cursor position within stack buffer affects this command.
35438
35439@c 28
35440@item
35441Arguments are not actually removed from the stack by this command.
35442
35443@c 29
35444@item
35445Variable name may be a single digit or a full name.
35446
35447@c 30
35448@item
35449Editing occurs in a separate buffer. Press @kbd{M-# M-#} (or @kbd{C-c C-c},
35450@key{LFD}, or in some cases @key{RET}) to finish the edit, or press
35451@kbd{M-# x} to cancel the edit. The @key{LFD} key prevents evaluation
35452of the result of the edit.
35453
35454@c 31
35455@item
35456The number prompted for can also be provided as a prefix argument.
35457
35458@c 32
35459@item
35460Press this key a second time to cancel the prefix.
35461
35462@c 33
35463@item
35464With a negative prefix, deactivate all formulas. With a positive
35465prefix, deactivate and then reactivate from scratch.
35466
35467@c 34
35468@item
35469Default is to scan for nearest formula delimiter symbols. With a
35470prefix of zero, formula is delimited by mark and point. With a
35471non-zero prefix, formula is delimited by scanning forward or
35472backward by that many lines.
35473
35474@c 35
35475@item
35476Parse the region between point and mark as a vector. A nonzero prefix
35477parses @var{n} lines before or after point as a vector. A zero prefix
35478parses the current line as a vector. A @kbd{C-u} prefix parses the
35479region between point and mark as a single formula.
35480
35481@c 36
35482@item
35483Parse the rectangle defined by point and mark as a matrix. A positive
35484prefix @var{n} divides the rectangle into columns of width @var{n}.
35485A zero or @kbd{C-u} prefix parses each line as one formula. A negative
35486prefix suppresses special treatment of bracketed portions of a line.
35487
35488@c 37
35489@item
35490A numeric prefix causes the current language mode to be ignored.
35491
35492@c 38
35493@item
35494Responding to a prompt with a blank line answers that and all
35495later prompts by popping additional stack entries.
35496
35497@c 39
35498@item
35499Answer for @cite{v} may also be of the form @cite{v = v_0} or
35500@cite{v - v_0}.
35501
35502@c 40
35503@item
35504With a positive prefix argument, stack contains many @cite{y}'s and one
35505common @cite{x}. With a zero prefix, stack contains a vector of
35506@cite{y}s and a common @cite{x}. With a negative prefix, stack
35507contains many @cite{[x,y]} vectors. (For 3D plots, substitute
35508@cite{z} for @cite{y} and @cite{x,y} for @cite{x}.)
35509
35510@c 41
35511@item
35512With any prefix argument, all curves in the graph are deleted.
35513
35514@c 42
35515@item
35516With a positive prefix, refines an existing plot with more data points.
35517With a negative prefix, forces recomputation of the plot data.
35518
35519@c 43
35520@item
35521With any prefix argument, set the default value instead of the
35522value for this graph.
35523
35524@c 44
35525@item
35526With a negative prefix argument, set the value for the printer.
35527
35528@c 45
35529@item
35530Condition is considered ``true'' if it is a nonzero real or complex
35531number, or a formula whose value is known to be nonzero; it is ``false''
35532otherwise.
35533
35534@c 46
35535@item
35536Several formulas separated by commas are pushed as multiple stack
35537entries. Trailing @kbd{)}, @kbd{]}, @kbd{@}}, @kbd{>}, and @kbd{"}
35538delimiters may be omitted. The notation @kbd{$$$} refers to the value
35539in stack level three, and causes the formula to replace the top three
35540stack levels. The notation @kbd{$3} refers to stack level three without
35541causing that value to be removed from the stack. Use @key{LFD} in place
35542of @key{RET} to prevent evaluation; use @kbd{M-=} in place of @key{RET}
35543to evaluate variables.@refill
35544
35545@c 47
35546@item
35547The variable is replaced by the formula shown on the right. The
35548Inverse flag reverses the order of the operands, e.g., @kbd{I s - x}
35549assigns @c{$x \coloneq a-x$}
35550@cite{x := a-x}.
35551
35552@c 48
35553@item
35554Press @kbd{?} repeatedly to see how to choose a model. Answer the
35555variables prompt with @cite{iv} or @cite{iv;pv} to specify
35556independent and parameter variables. A positive prefix argument
35557takes @i{N+1} vectors from the stack; a zero prefix takes a matrix
35558and a vector from the stack.
35559
35560@c 49
35561@item
35562With a plain @kbd{C-u} prefix, replace the current region of the
35563destination buffer with the yanked text instead of inserting.
35564
35565@c 50
35566@item
35567All stack entries are reformatted; the @kbd{H} prefix inhibits this.
35568The @kbd{I} prefix sets the mode temporarily, redraws the top stack
35569entry, then restores the original setting of the mode.
35570
35571@c 51
35572@item
35573A negative prefix sets the default 3D resolution instead of the
35574default 2D resolution.
35575
35576@c 52
35577@item
35578This grabs a vector of the form [@var{prec}, @var{wsize}, @var{ssize},
35579@var{radix}, @var{flfmt}, @var{ang}, @var{frac}, @var{symb}, @var{polar},
35580@var{matrix}, @var{simp}, @var{inf}]. A prefix argument from 1 to 12
35581grabs the @var{n}th mode value only.
35582@end enumerate
35583
35584@iftex
35585(Space is provided below for you to keep your own written notes.)
35586@page
35587@endgroup
35588@end iftex
35589
35590
35591@c [end-summary]
35592
35593@node Key Index, Command Index, Summary, Top
35594@unnumbered Index of Key Sequences
35595
35596@printindex ky
35597
35598@node Command Index, Function Index, Key Index, Top
35599@unnumbered Index of Calculator Commands
35600
35601Since all Calculator commands begin with the prefix @samp{calc-}, the
35602@kbd{x} key has been provided as a variant of @kbd{M-x} which automatically
35603types @samp{calc-} for you. Thus, @kbd{x last-args} is short for
35604@kbd{M-x calc-last-args}.
35605
35606@printindex pg
35607
35608@node Function Index, Concept Index, Command Index, Top
35609@unnumbered Index of Algebraic Functions
35610
35611This is a list of built-in functions and operators usable in algebraic
35612expressions. Their full Lisp names are derived by adding the prefix
35613@samp{calcFunc-}, as in @code{calcFunc-sqrt}.
35614@iftex
35615All functions except those noted with ``*'' have corresponding
35616Calc keystrokes and can also be found in the Calc Summary.
35617@end iftex
35618
35619@printindex tp
35620
35621@node Concept Index, Variable Index, Function Index, Top
35622@unnumbered Concept Index
35623
35624@printindex cp
35625
35626@node Variable Index, Lisp Function Index, Concept Index, Top
35627@unnumbered Index of Variables
35628
35629The variables in this list that do not contain dashes are accessible
35630as Calc variables. Add a @samp{var-} prefix to get the name of the
35631corresponding Lisp variable.
35632
35633The remaining variables are Lisp variables suitable for @code{setq}ing
35634in your @file{.emacs} file.
35635
35636@printindex vr
35637
35638@node Lisp Function Index, , Variable Index, Top
35639@unnumbered Index of Lisp Math Functions
35640
35641The following functions are meant to be used with @code{defmath}, not
35642@code{defun} definitions. For names that do not start with @samp{calc-},
35643the corresponding full Lisp name is derived by adding a prefix of
35644@samp{math-}.
35645
35646@printindex fn
35647
35648@summarycontents
35649
35650@c [end]
35651
35652@contents
35653@bye
35654
35655