1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header (This is for running Texinfo on a region.)
6 @settitle GNU Emacs Calc 2.02 Manual
7 @comment %**end of header (This is for running Texinfo on a region.)
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.
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}
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.
28 % Redefine @c{tex-stuff} \n @whatever{info-stuff}.
29 \gdef\c{\futurelet\next\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
37 \gdef\mycxxy#1#2{#1\Etex\mycxxz}
41 @c Fix some things to make math mode work properly.
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
55 @c Fix some other things specifically for this manual.
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
62 \gdef\coloneq{\mathrel{\mathord:\mathord=}}
64 \global\parskip=12pt % Standard parskip looks a bit too large
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}$}
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}%
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}
87 \gdef\printindex{\parsearg\calcprintindex}
88 \gdef\calcprintindex#1{%
91 \ifeof1{\let\s=\indexskip \csname indexsize#1\endcsname}\fi
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}
100 \gdef\indexsizefn{\s\s}
101 \gdef\langle#1\rangle{\it XXX} % Avoid length mismatch with true expansion
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}
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{%
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{}%
126 \futurelet\next\calcindexerxxx
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
133 \global\calcpageno=\pageno
135 \advance\dimen0 by2\baselineskip
136 \ifdim\dimen0>\pagegoal
137 \global\advance\calcpageno by 1
138 \vfill\eject\noindent
141 \gdef\calcindexershow#1{\smash{#1}\advance\kyvpos by 11pt}
142 \gdef\calcindexernoshow#1{}
143 \global\let\calcindexersh=\calcindexershow
144 \gdef\calcindexerxxx{%
146 \ifx\next\kindex \global\let\calcindexersh=\calcindexernoshow \fi
147 \ifx\next\tindex \global\let\calcindexersh=\calcindexernoshow \fi
151 \gdef\calcindexerxxxx#1{\next}
152 \gdef\indexstarxx{\thinspace{\rm *}}
153 \gdef\starindex{\global\let\indexstar=\indexstarxx}
155 \kyhpos=\leftskip\kyvpos=0pt\clubpenalty=\calcclubpenalty
156 \calcclubpenalty=1000\relax
158 \gdef\idots{{\indrm...}}
160 @newdimen@kyvpos @kyvpos=0pt
161 @newdimen@kyhpos @kyhpos=0pt
162 @newcount@calcclubpenalty @calcclubpenalty=1000
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
170 \catcode`\@=0 @catcode`@\=@active
175 * Calc: (calc). Scientific, financial, and symbolic calculator
179 This file documents Calc, the GNU Emacs calculator.
181 Copyright (C) 1990, 1991 Free Software Foundation, Inc.
183 Permission is granted to make and distribute verbatim copies of this
184 manual provided the copyright notice and this permission notice are
185 preserved on all copies.
188 Permission is granted to process this file through TeX and print the
189 results, provided the printed document carries copying permission notice
190 identical to this one except for the removal of this paragraph (this
191 paragraph not being relevant to the printed manual).
194 Permission is granted to copy and distribute modified versions of this
195 manual under the conditions for verbatim copying, provided also that the
196 section entitled ``GNU General Public License'' is included exactly as
197 in the original, and provided that the entire resulting derived work is
198 distributed under the terms of a permission notice identical to this one.
200 Permission is granted to copy and distribute translations of this manual
201 into another language, under the above conditions for modified versions,
202 except that the section entitled ``GNU General Public License'' may be
203 included in a translation approved by the author instead of in the
209 @center @titlefont{Calc Manual}
211 @center GNU Emacs Calc Version 2.02
216 @center Dave Gillespie
217 @center daveg@@synaptics.com
220 @vskip 0pt plus 1filll
221 Copyright @copyright{} 1990, 1991 Free Software Foundation, Inc.
223 Permission is granted to make and distribute verbatim copies of
224 this manual provided the copyright notice and this permission notice
225 are preserved on all copies.
228 Permission is granted to process this file through TeX and print the
229 results, provided the printed document carries copying permission notice
230 identical to this one except for the removal of this paragraph (this
231 paragraph not being relevant to the printed manual).
234 Permission is granted to copy and distribute modified versions of this
235 manual under the conditions for verbatim copying, provided also that the
236 section entitled ``GNU General Public License'' is included exactly as
237 in the original, and provided that the entire resulting derived work is
238 distributed under the terms of a permission notice identical to this one.
240 Permission is granted to copy and distribute translations of this manual
241 into another language, under the above conditions for modified versions,
242 except that the section entitled ``GNU General Public License'' may be
243 included in a translation approved by the author instead of in the
249 @node Top, Copying,, (dir)
250 @chapter The GNU Emacs Calculator
253 @dfn{Calc 2.02} is an advanced desk calculator and mathematical tool
254 that runs as part of the GNU Emacs environment.
256 This manual is divided into three major parts: "Getting Started," the
257 "Calc Tutorial," and the "Calc Reference." The Tutorial introduces all
258 the major aspects of Calculator use in an easy, hands-on way. The
259 remainder of the manual is a complete reference to the features of the
262 For help in the Emacs Info system (which you are using to read this
263 file), type @kbd{?}. (You can also type @kbd{h} to run through a
264 longer Info tutorial.)
268 * Copying:: How you can copy and share Calc.
270 * Getting Started:: General description and overview.
272 * Interactive Tutorial:: Same as tutorial.
274 * Tutorial:: A step-by-step introduction for beginners.
276 * Introduction:: Introduction to the Calc reference manual.
277 * Data Types:: Types of objects manipulated by Calc.
278 * Stack and Trail:: Manipulating the stack and trail buffers.
279 * Mode Settings:: Adjusting display format and other modes.
280 * Arithmetic:: Basic arithmetic functions.
281 * Scientific Functions:: Transcendentals and other scientific functions.
282 * Matrix Functions:: Operations on vectors and matrices.
283 * Algebra:: Manipulating expressions algebraically.
284 * Units:: Operations on numbers with units.
285 * Store and Recall:: Storing and recalling variables.
286 * Graphics:: Commands for making graphs of data.
287 * Kill and Yank:: Moving data into and out of Calc.
288 * Embedded Mode:: Working with formulas embedded in a file.
289 * Programming:: Calc as a programmable calculator.
291 * Installation:: Installing Calc as a part of GNU Emacs.
292 * Reporting Bugs:: How to report bugs and make suggestions.
294 * Summary:: Summary of Calc commands and functions.
296 * Key Index:: The standard Calc key sequences.
297 * Command Index:: The interactive Calc commands.
298 * Function Index:: Functions (in algebraic formulas).
299 * Concept Index:: General concepts.
300 * Variable Index:: Variables used by Calc (both user and internal).
301 * Lisp Function Index:: Internal Lisp math functions.
304 @node Copying, Getting Started, Top, Top
305 @unnumbered GNU GENERAL PUBLIC LICENSE
306 @center Version 1, February 1989
309 Copyright @copyright{} 1989 Free Software Foundation, Inc.
310 675 Mass Ave, Cambridge, MA 02139, USA
312 Everyone is permitted to copy and distribute verbatim copies
313 of this license document, but changing it is not allowed.
316 @unnumberedsec Preamble
318 The license agreements of most software companies try to keep users
319 at the mercy of those companies. By contrast, our General Public
320 License is intended to guarantee your freedom to share and change free
321 software---to make sure the software is free for all its users. The
322 General Public License applies to the Free Software Foundation's
323 software and to any other program whose authors commit to using it.
324 You can use it for your programs, too.
326 When we speak of free software, we are referring to freedom, not
327 price. Specifically, the General Public License is designed to make
328 sure that you have the freedom to give away or sell copies of free
329 software, that you receive source code or can get it if you want it,
330 that you can change the software or use pieces of it in new free
331 programs; and that you know you can do these things.
333 To protect your rights, we need to make restrictions that forbid
334 anyone to deny you these rights or to ask you to surrender the rights.
335 These restrictions translate to certain responsibilities for you if you
336 distribute copies of the software, or if you modify it.
338 For example, if you distribute copies of a such a program, whether
339 gratis or for a fee, you must give the recipients all the rights that
340 you have. You must make sure that they, too, receive or can get the
341 source code. And you must tell them their rights.
343 We protect your rights with two steps: (1) copyright the software, and
344 (2) offer you this license which gives you legal permission to copy,
345 distribute and/or modify the software.
347 Also, for each author's protection and ours, we want to make certain
348 that everyone understands that there is no warranty for this free
349 software. If the software is modified by someone else and passed on, we
350 want its recipients to know that what they have is not the original, so
351 that any problems introduced by others will not reflect on the original
352 authors' reputations.
354 The precise terms and conditions for copying, distribution and
358 @unnumberedsec TERMS AND CONDITIONS
361 @center TERMS AND CONDITIONS
366 This License Agreement applies to any program or other work which
367 contains a notice placed by the copyright holder saying it may be
368 distributed under the terms of this General Public License. The
369 ``Program'', below, refers to any such program or work, and a ``work based
370 on the Program'' means either the Program or any work containing the
371 Program or a portion of it, either verbatim or with modifications. Each
372 licensee is addressed as ``you''.
375 You may copy and distribute verbatim copies of the Program's source
376 code as you receive it, in any medium, provided that you conspicuously and
377 appropriately publish on each copy an appropriate copyright notice and
378 disclaimer of warranty; keep intact all the notices that refer to this
379 General Public License and to the absence of any warranty; and give any
380 other recipients of the Program a copy of this General Public License
381 along with the Program. You may charge a fee for the physical act of
385 You may modify your copy or copies of the Program or any portion of
386 it, and copy and distribute such modifications under the terms of Paragraph
387 1 above, provided that you also do the following:
391 cause the modified files to carry prominent notices stating that
392 you changed the files and the date of any change; and
395 cause the whole of any work that you distribute or publish, that
396 in whole or in part contains the Program or any part thereof, either
397 with or without modifications, to be licensed at no charge to all
398 third parties under the terms of this General Public License (except
399 that you may choose to grant warranty protection to some or all
400 third parties, at your option).
403 If the modified program normally reads commands interactively when
404 run, you must cause it, when started running for such interactive use
405 in the simplest and most usual way, to print or display an
406 announcement including an appropriate copyright notice and a notice
407 that there is no warranty (or else, saying that you provide a
408 warranty) and that users may redistribute the program under these
409 conditions, and telling the user how to view a copy of this General
413 You may charge a fee for the physical act of transferring a
414 copy, and you may at your option offer warranty protection in
418 Mere aggregation of another independent work with the Program (or its
419 derivative) on a volume of a storage or distribution medium does not bring
420 the other work under the scope of these terms.
423 You may copy and distribute the Program (or a portion or derivative of
424 it, under Paragraph 2) in object code or executable form under the terms of
425 Paragraphs 1 and 2 above provided that you also do one of the following:
429 accompany it with the complete corresponding machine-readable
430 source code, which must be distributed under the terms of
431 Paragraphs 1 and 2 above; or,
434 accompany it with a written offer, valid for at least three
435 years, to give any third party free (except for a nominal charge
436 for the cost of distribution) a complete machine-readable copy of the
437 corresponding source code, to be distributed under the terms of
438 Paragraphs 1 and 2 above; or,
441 accompany it with the information you received as to where the
442 corresponding source code may be obtained. (This alternative is
443 allowed only for noncommercial distribution and only if you
444 received the program in object code or executable form alone.)
447 Source code for a work means the preferred form of the work for making
448 modifications to it. For an executable file, complete source code means
449 all the source code for all modules it contains; but, as a special
450 exception, it need not include source code for modules which are standard
451 libraries that accompany the operating system on which the executable
452 file runs, or for standard header files or definitions files that
453 accompany that operating system.
456 You may not copy, modify, sublicense, distribute or transfer the
457 Program except as expressly provided under this General Public License.
458 Any attempt otherwise to copy, modify, sublicense, distribute or transfer
459 the Program is void, and will automatically terminate your rights to use
460 the Program under this License. However, parties who have received
461 copies, or rights to use copies, from you under this General Public
462 License will not have their licenses terminated so long as such parties
463 remain in full compliance.
466 By copying, distributing or modifying the Program (or any work based
467 on the Program) you indicate your acceptance of this license to do so,
468 and all its terms and conditions.
471 Each time you redistribute the Program (or any work based on the
472 Program), the recipient automatically receives a license from the original
473 licensor to copy, distribute or modify the Program subject to these
474 terms and conditions. You may not impose any further restrictions on the
475 recipients' exercise of the rights granted herein.
478 The Free Software Foundation may publish revised and/or new versions
479 of the General Public License from time to time. Such new versions will
480 be similar in spirit to the present version, but may differ in detail to
481 address new problems or concerns.
483 Each version is given a distinguishing version number. If the Program
484 specifies a version number of the license which applies to it and ``any
485 later version'', you have the option of following the terms and conditions
486 either of that version or of any later version published by the Free
487 Software Foundation. If the Program does not specify a version number of
488 the license, you may choose any version ever published by the Free Software
492 If you wish to incorporate parts of the Program into other free
493 programs whose distribution conditions are different, write to the author
494 to ask for permission. For software which is copyrighted by the Free
495 Software Foundation, write to the Free Software Foundation; we sometimes
496 make exceptions for this. Our decision will be guided by the two goals
497 of preserving the free status of all derivatives of our free software and
498 of promoting the sharing and reuse of software generally.
508 BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
509 FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
510 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
511 PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
512 OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
513 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
514 TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
515 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
516 REPAIR OR CORRECTION.
519 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
520 ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
521 REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
522 INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
523 ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT
524 LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES
525 SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
526 WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
527 ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
530 @node Getting Started, Tutorial, Copying, Top
531 @chapter Getting Started
534 This chapter provides a general overview of Calc, the GNU Emacs
535 Calculator: What it is, how to start it and how to exit from it,
536 and what are the various ways that it can be used.
540 * About This Manual::
541 * Notations Used in This Manual::
543 * Demonstration of Calc::
544 * History and Acknowledgements::
547 @node What is Calc, About This Manual, Getting Started, Getting Started
548 @section What is Calc?
551 @dfn{Calc} is an advanced calculator and mathematical tool that runs as
552 part of the GNU Emacs environment. Very roughly based on the HP-28/48
553 series of calculators, its many features include:
557 Choice of algebraic or RPN (stack-based) entry of calculations.
560 Arbitrary precision integers and floating-point numbers.
563 Arithmetic on rational numbers, complex numbers (rectangular and polar),
564 error forms with standard deviations, open and closed intervals, vectors
565 and matrices, dates and times, infinities, sets, quantities with units,
566 and algebraic formulas.
569 Mathematical operations such as logarithms and trigonometric functions.
572 Programmer's features (bitwise operations, non-decimal numbers).
575 Financial functions such as future value and internal rate of return.
578 Number theoretical features such as prime factorization and arithmetic
579 modulo @i{M} for any @i{M}.
582 Algebraic manipulation features, including symbolic calculus.
585 Moving data to and from regular editing buffers.
588 ``Embedded mode'' for manipulating Calc formulas and data directly
589 inside any editing buffer.
592 Graphics using GNUPLOT, a versatile (and free) plotting program.
595 Easy programming using keyboard macros, algebraic formulas,
596 algebraic rewrite rules, or extended Emacs Lisp.
599 Calc tries to include a little something for everyone; as a result it is
600 large and might be intimidating to the first-time user. If you plan to
601 use Calc only as a traditional desk calculator, all you really need to
602 read is the ``Getting Started'' chapter of this manual and possibly the
603 first few sections of the tutorial. As you become more comfortable with
604 the program you can learn its additional features. In terms of efficiency,
605 scope and depth, Calc cannot replace a powerful tool like Mathematica.
606 @c Removed this per RMS' request:
607 @c Mathematica@c{\trademark} @asis{ (tm)}.
608 But Calc has the advantages of convenience, portability, and availability
609 of the source code. And, of course, it's free!
611 @node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
612 @section About This Manual
615 This document serves as a complete description of the GNU Emacs
616 Calculator. It works both as an introduction for novices, and as
617 a reference for experienced users. While it helps to have some
618 experience with GNU Emacs in order to get the most out of Calc,
619 this manual ought to be readable even if you don't know or use Emacs
623 The manual is divided into three major parts:@: the ``Getting
624 Started'' chapter you are reading now, the Calc tutorial (chapter 2),
625 and the Calc reference manual (the remaining chapters and appendices).
628 The manual is divided into three major parts:@: the ``Getting
629 Started'' chapter you are reading now, the Calc tutorial (chapter 2),
630 and the Calc reference manual (the remaining chapters and appendices).
632 @c This manual has been printed in two volumes, the @dfn{Tutorial} and the
633 @c @dfn{Reference}. Both volumes include a copy of the ``Getting Started''
637 If you are in a hurry to use Calc, there is a brief ``demonstration''
638 below which illustrates the major features of Calc in just a couple of
639 pages. If you don't have time to go through the full tutorial, this
640 will show you everything you need to know to begin.
641 @xref{Demonstration of Calc}.
643 The tutorial chapter walks you through the various parts of Calc
644 with lots of hands-on examples and explanations. If you are new
645 to Calc and you have some time, try going through at least the
646 beginning of the tutorial. The tutorial includes about 70 exercises
647 with answers. These exercises give you some guided practice with
648 Calc, as well as pointing out some interesting and unusual ways
651 The reference section discusses Calc in complete depth. You can read
652 the reference from start to finish if you want to learn every aspect
653 of Calc. Or, you can look in the table of contents or the Concept
654 Index to find the parts of the manual that discuss the things you
657 @cindex Marginal notes
658 Every Calc keyboard command is listed in the Calc Summary, and also
659 in the Key Index. Algebraic functions, @kbd{M-x} commands, and
660 variables also have their own indices. @c{Each}
661 @asis{In the printed manual, each}
662 paragraph that is referenced in the Key or Function Index is marked
663 in the margin with its index entry.
665 @c [fix-ref Help Commands]
666 You can access this manual on-line at any time within Calc by
667 pressing the @kbd{h i} key sequence. Outside of the Calc window,
668 you can press @kbd{M-# i} to read the manual on-line. Also, you
669 can jump directly to the Tutorial by pressing @kbd{h t} or @kbd{M-# t},
670 or to the Summary by pressing @kbd{h s} or @kbd{M-# s}. Within Calc,
671 you can also go to the part of the manual describing any Calc key,
672 function, or variable using @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v},
673 respectively. @xref{Help Commands}.
675 Printed copies of this manual are also available from the Free Software
678 @node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
679 @section Notations Used in This Manual
682 This section describes the various notations that are used
683 throughout the Calc manual.
685 In keystroke sequences, uppercase letters mean you must hold down
686 the shift key while typing the letter. Keys pressed with Control
687 held down are shown as @kbd{C-x}. Keys pressed with Meta held down
688 are shown as @kbd{M-x}. Other notations are @key{RET} for the
689 Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
690 @key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
692 (If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
693 the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
694 If you don't have a Meta key, look for Alt or Extend Char. You can
695 also press @key{ESC} or @key{C-[} first to get the same effect, so
696 that @kbd{M-x}, @kbd{ESC x}, and @kbd{C-[ x} are all equivalent.)
698 Sometimes the @key{RET} key is not shown when it is ``obvious''
699 that you must press @kbd{RET} to proceed. For example, the @key{RET}
700 is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
702 Commands are generally shown like this: @kbd{p} (@code{calc-precision})
703 or @kbd{M-# k} (@code{calc-keypad}). This means that the command is
704 normally used by pressing the @kbd{p} key or @kbd{M-# k} key sequence,
705 but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
707 Commands that correspond to functions in algebraic notation
708 are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means
709 the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
710 the corresponding function in an algebraic-style formula would
711 be @samp{cos(@var{x})}.
713 A few commands don't have key equivalents: @code{calc-sincos}
714 [@code{sincos}].@refill
716 @node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
717 @section A Demonstration of Calc
720 @cindex Demonstration of Calc
721 This section will show some typical small problems being solved with
722 Calc. The focus is more on demonstration than explanation, but
723 everything you see here will be covered more thoroughly in the
726 To begin, start Emacs if necessary (usually the command @code{emacs}
727 does this), and type @kbd{M-# c} (or @kbd{ESC # c}) to start the
728 Calculator. (@xref{Starting Calc}, if this doesn't work for you.)
730 Be sure to type all the sample input exactly, especially noting the
731 difference between lower-case and upper-case letters. Remember,
732 @kbd{RET}, @kbd{TAB}, @kbd{DEL}, and @kbd{SPC} are the Return, Tab,
733 Delete, and Space keys.
735 @strong{RPN calculation.} In RPN, you type the input number(s) first,
736 then the command to operate on the numbers.
739 Type @kbd{2 RET 3 + Q} to compute @c{$\sqrt{2+3} = 2.2360679775$}
740 @asis{the square root of 2+3, which is 2.2360679775}.
743 Type @kbd{P 2 ^} to compute @c{$\pi^2 = 9.86960440109$}
744 @asis{the value of `pi' squared, 9.86960440109}.
747 Type @kbd{TAB} to exchange the order of these two results.
750 Type @kbd{- I H S} to subtract these results and compute the Inverse
751 Hyperbolic sine of the difference, 2.72996136574.
754 Type @kbd{DEL} to erase this result.
756 @strong{Algebraic calculation.} You can also enter calculations using
757 conventional ``algebraic'' notation. To enter an algebraic formula,
758 use the apostrophe key.
761 Type @kbd{' sqrt(2+3) RET} to compute @c{$\sqrt{2+3}$}
762 @asis{the square root of 2+3}.
765 Type @kbd{' pi^2 RET} to enter @c{$\pi^2$}
766 @asis{`pi' squared}. To evaluate this symbolic
767 formula as a number, type @kbd{=}.
770 Type @kbd{' arcsinh($ - $$) RET} to subtract the second-most-recent
771 result from the most-recent and compute the Inverse Hyperbolic sine.
773 @strong{Keypad mode.} If you are using the X window system, press
774 @w{@kbd{M-# k}} to get Keypad mode. (If you don't use X, skip to
778 Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
779 ``buttons'' using your left mouse button.
782 Click on @key{PI}, @key{2}, and @t{y^x}.
785 Click on @key{INV}, then @key{ENTER} to swap the two results.
788 Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
791 Click on @key{<-} to erase the result, then click @key{OFF} to turn
792 the Keypad Calculator off.
794 @strong{Grabbing data.} Type @kbd{M-# x} if necessary to exit Calc.
795 Now select the following numbers as an Emacs region: ``Mark'' the
796 front of the list by typing control-@kbd{SPC} or control-@kbd{@@} there,
797 then move to the other end of the list. (Either get this list from
798 the on-line copy of this manual, accessed by @w{@kbd{M-# i}}, or just
799 type these numbers into a scratch file.) Now type @kbd{M-# g} to
800 ``grab'' these numbers into Calc.
811 The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
812 Type @w{@kbd{V R +}} to compute the sum of these numbers.
815 Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
816 the product of the numbers.
819 You can also grab data as a rectangular matrix. Place the cursor on
820 the upper-leftmost @samp{1} and set the mark, then move to just after
821 the lower-right @samp{8} and press @kbd{M-# r}.
824 Type @kbd{v t} to transpose this @c{$3\times2$}
825 @asis{3x2} matrix into a @c{$2\times3$}
826 @asis{2x3} matrix. Type
827 @w{@kbd{v u}} to unpack the rows into two separate vectors. Now type
828 @w{@kbd{V R + TAB V R +}} to compute the sums of the two original columns.
829 (There is also a special grab-and-sum-columns command, @kbd{M-# :}.)
831 @strong{Units conversion.} Units are entered algebraically.
832 Type @w{@kbd{' 43 mi/hr RET}} to enter the quantity 43 miles-per-hour.
833 Type @w{@kbd{u c km/hr RET}}. Type @w{@kbd{u c m/s RET}}.
835 @strong{Date arithmetic.} Type @kbd{t N} to get the current date and
836 time. Type @kbd{90 +} to find the date 90 days from now. Type
837 @kbd{' <25 dec 87> RET} to enter a date, then @kbd{- 7 /} to see how
838 many weeks have passed since then.
840 @strong{Algebra.} Algebraic entries can also include formulas
841 or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] RET}
842 to enter a pair of equations involving three variables.
843 (Note the leading apostrophe in this example; also, note that the space
844 between @samp{x y} is required.) Type @w{@kbd{a S x,y RET}} to solve
845 these equations for the variables @cite{x} and @cite{y}.@refill
848 Type @kbd{d B} to view the solutions in more readable notation.
849 Type @w{@kbd{d C}} to view them in C language notation, and @kbd{d T}
850 to view them in the notation for the @TeX{} typesetting system.
851 Type @kbd{d N} to return to normal notation.
854 Type @kbd{7.5}, then @kbd{s l a RET} to let @cite{a = 7.5} in these formulas.
855 (That's a letter @kbd{l}, not a numeral @kbd{1}.)
858 @strong{Help functions.} You can read about any command in the on-line
859 manual. Type @kbd{M-# c} to return to Calc after each of these
860 commands: @kbd{h k t N} to read about the @kbd{t N} command,
861 @kbd{h f sqrt RET} to read about the @code{sqrt} function, and
862 @kbd{h s} to read the Calc summary.
865 @strong{Help functions.} You can read about any command in the on-line
866 manual. Remember to type the letter @kbd{l}, then @kbd{M-# c}, to
867 return here after each of these commands: @w{@kbd{h k t N}} to read
868 about the @w{@kbd{t N}} command, @kbd{h f sqrt RET} to read about the
869 @code{sqrt} function, and @kbd{h s} to read the Calc summary.
872 Press @kbd{DEL} repeatedly to remove any leftover results from the stack.
873 To exit from Calc, press @kbd{q} or @kbd{M-# c} again.
875 @node Using Calc, History and Acknowledgements, Demonstration of Calc, Getting Started
879 Calc has several user interfaces that are specialized for
880 different kinds of tasks. As well as Calc's standard interface,
881 there are Quick Mode, Keypad Mode, and Embedded Mode.
883 @c [fix-ref Installation]
884 Calc must be @dfn{installed} before it can be used. @xref{Installation},
885 for instructions on setting up and installing Calc. We will assume
886 you or someone on your system has already installed Calc as described
891 * The Standard Interface::
892 * Quick Mode Overview::
893 * Keypad Mode Overview::
894 * Standalone Operation::
895 * Embedded Mode Overview::
896 * Other M-# Commands::
899 @node Starting Calc, The Standard Interface, Using Calc, Using Calc
900 @subsection Starting Calc
903 On most systems, you can type @kbd{M-#} to start the Calculator.
904 The notation @kbd{M-#} is short for Meta-@kbd{#}. On most
905 keyboards this means holding down the Meta (or Alt) and
906 Shift keys while typing @kbd{3}.
909 Once again, if you don't have a Meta key on your keyboard you can type
910 @key{ESC} first, then @kbd{#}, to accomplish the same thing. If you
911 don't even have an @key{ESC} key, you can fake it by holding down
912 Control or @key{CTRL} while typing a left square bracket
913 (that's @kbd{C-[} in Emacs notation).@refill
915 @kbd{M-#} is a @dfn{prefix key}; when you press it, Emacs waits for
916 you to press a second key to complete the command. In this case,
917 you will follow @kbd{M-#} with a letter (upper- or lower-case, it
918 doesn't matter for @kbd{M-#}) that says which Calc interface you
921 To get Calc's standard interface, type @kbd{M-# c}. To get
922 Keypad Mode, type @kbd{M-# k}. Type @kbd{M-# ?} to get a brief
923 list of the available options, and type a second @kbd{?} to get
926 To ease typing, @kbd{M-# M-#} (or @kbd{M-# #} if that's easier)
927 also works to start Calc. It starts the same interface (either
928 @kbd{M-# c} or @w{@kbd{M-# k}}) that you last used, selecting the
929 @kbd{M-# c} interface by default. (If your installation has
930 a special function key set up to act like @kbd{M-#}, hitting that
931 function key twice is just like hitting @kbd{M-# M-#}.)
933 If @kbd{M-#} doesn't work for you, you can always type explicit
934 commands like @kbd{M-x calc} (for the standard user interface) or
935 @w{@kbd{M-x calc-keypad}} (for Keypad Mode). First type @kbd{M-x}
936 (that's Meta with the letter @kbd{x}), then, at the prompt,
937 type the full command (like @kbd{calc-keypad}) and press Return.
939 If you type @kbd{M-x calc} and Emacs still doesn't recognize the
940 command (it will say @samp{[No match]} when you try to press
941 @key{RET}), then Calc has not been properly installed.
943 The same commands (like @kbd{M-# c} or @kbd{M-# M-#}) that start
944 the Calculator also turn it off if it is already on.
946 @node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
947 @subsection The Standard Calc Interface
950 @cindex Standard user interface
951 Calc's standard interface acts like a traditional RPN calculator,
952 operated by the normal Emacs keyboard. When you type @kbd{M-# c}
953 to start the Calculator, the Emacs screen splits into two windows
954 with the file you were editing on top and Calc on the bottom.
963 --**-Emacs: myfile (Fundamental)----All----------------------
964 --- Emacs Calculator Mode --- |Emacs Calc Mode v2.00...
972 --%%-Calc: 12 Deg (Calculator)----All----- --%%-Emacs: *Calc Trail*
976 In this figure, the mode-line for @file{myfile} has moved up and the
977 ``Calculator'' window has appeared below it. As you can see, Calc
978 actually makes two windows side-by-side. The lefthand one is
979 called the @dfn{stack window} and the righthand one is called the
980 @dfn{trail window.} The stack holds the numbers involved in the
981 calculation you are currently performing. The trail holds a complete
982 record of all calculations you have done. In a desk calculator with
983 a printer, the trail corresponds to the paper tape that records what
986 In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
987 were first entered into the Calculator, then the 2 and 4 were
988 multiplied to get 8, then the 3 and 8 were subtracted to get @i{-5}.
989 (The @samp{>} symbol shows that this was the most recent calculation.)
990 The net result is the two numbers 17.3 and @i{-5} sitting on the stack.
992 Most Calculator commands deal explicitly with the stack only, but
993 there is a set of commands that allow you to search back through
994 the trail and retrieve any previous result.
996 Calc commands use the digits, letters, and punctuation keys.
997 Shifted (i.e., upper-case) letters are different from lowercase
998 letters. Some letters are @dfn{prefix} keys that begin two-letter
999 commands. For example, @kbd{e} means ``enter exponent'' and shifted
1000 @kbd{E} means @cite{e^x}. With the @kbd{d} (``display modes'') prefix
1001 the letter ``e'' takes on very different meanings: @kbd{d e} means
1002 ``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
1004 There is nothing stopping you from switching out of the Calc
1005 window and back into your editing window, say by using the Emacs
1006 @w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is
1007 inside a regular window, Emacs acts just like normal. When the
1008 cursor is in the Calc stack or trail windows, keys are interpreted
1011 When you quit by pressing @kbd{M-# c} a second time, the Calculator
1012 windows go away but the actual Stack and Trail are not gone, just
1013 hidden. When you press @kbd{M-# c} once again you will get the
1014 same stack and trail contents you had when you last used the
1017 The Calculator does not remember its state between Emacs sessions.
1018 Thus if you quit Emacs and start it again, @kbd{M-# c} will give you
1019 a fresh stack and trail. There is a command (@kbd{m m}) that lets
1020 you save your favorite mode settings between sessions, though.
1021 One of the things it saves is which user interface (standard or
1022 Keypad) you last used; otherwise, a freshly started Emacs will
1023 always treat @kbd{M-# M-#} the same as @kbd{M-# c}.
1025 The @kbd{q} key is another equivalent way to turn the Calculator off.
1027 If you type @kbd{M-# b} first and then @kbd{M-# c}, you get a
1028 full-screen version of Calc (@code{full-calc}) in which the stack and
1029 trail windows are still side-by-side but are now as tall as the whole
1030 Emacs screen. When you press @kbd{q} or @kbd{M-# c} again to quit,
1031 the file you were editing before reappears. The @kbd{M-# b} key
1032 switches back and forth between ``big'' full-screen mode and the
1033 normal partial-screen mode.
1035 Finally, @kbd{M-# o} (@code{calc-other-window}) is like @kbd{M-# c}
1036 except that the Calc window is not selected. The buffer you were
1037 editing before remains selected instead. @kbd{M-# o} is a handy
1038 way to switch out of Calc momentarily to edit your file; type
1039 @kbd{M-# c} to switch back into Calc when you are done.
1041 @node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
1042 @subsection Quick Mode (Overview)
1045 @dfn{Quick Mode} is a quick way to use Calc when you don't need the
1046 full complexity of the stack and trail. To use it, type @kbd{M-# q}
1047 (@code{quick-calc}) in any regular editing buffer.
1049 Quick Mode is very simple: It prompts you to type any formula in
1050 standard algebraic notation (like @samp{4 - 2/3}) and then displays
1051 the result at the bottom of the Emacs screen (@i{3.33333333333}
1052 in this case). You are then back in the same editing buffer you
1053 were in before, ready to continue editing or to type @kbd{M-# q}
1054 again to do another quick calculation. The result of the calculation
1055 will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
1056 at this point will yank the result into your editing buffer.
1058 Calc mode settings affect Quick Mode, too, though you will have to
1059 go into regular Calc (with @kbd{M-# c}) to change the mode settings.
1061 @c [fix-ref Quick Calculator mode]
1062 @xref{Quick Calculator}, for further information.
1064 @node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
1065 @subsection Keypad Mode (Overview)
1068 @dfn{Keypad Mode} is a mouse-based interface to the Calculator.
1069 It is designed for use with the X window system. If you don't
1070 have X, you will have to operate keypad mode with your arrow
1071 keys (which is probably more trouble than it's worth). Keypad
1072 mode is currently not supported under Emacs 19.
1074 Type @kbd{M-# k} to turn Keypad Mode on or off. Once again you
1075 get two new windows, this time on the righthand side of the screen
1076 instead of at the bottom. The upper window is the familiar Calc
1077 Stack; the lower window is a picture of a typical calculator keypad.
1081 \advance \dimen0 by 24\baselineskip%
1082 \ifdim \dimen0>\pagegoal \vfill\eject \fi%
1086 |--- Emacs Calculator Mode ---
1090 |--%%-Calc: 12 Deg (Calcul
1091 |----+-----Calc 2.00-----+----1
1092 |FLR |CEIL|RND |TRNC|CLN2|FLT |
1093 |----+----+----+----+----+----|
1094 | LN |EXP | |ABS |IDIV|MOD |
1095 |----+----+----+----+----+----|
1096 |SIN |COS |TAN |SQRT|y^x |1/x |
1097 |----+----+----+----+----+----|
1098 | ENTER |+/- |EEX |UNDO| <- |
1099 |-----+---+-+--+--+-+---++----|
1100 | INV | 7 | 8 | 9 | / |
1101 |-----+-----+-----+-----+-----|
1102 | HYP | 4 | 5 | 6 | * |
1103 |-----+-----+-----+-----+-----|
1104 |EXEC | 1 | 2 | 3 | - |
1105 |-----+-----+-----+-----+-----|
1106 | OFF | 0 | . | PI | + |
1107 |-----+-----+-----+-----+-----+
1113 @advance@hsize-2.2in
1116 @advance@hsize-3.05in
1121 Keypad Mode is much easier for beginners to learn, because there
1122 is no need to memorize lots of obscure key sequences. But not all
1123 commands in regular Calc are available on the Keypad. You can
1124 always switch the cursor into the Calc stack window to use
1125 standard Calc commands if you need. Serious Calc users, though,
1126 often find they prefer the standard interface over Keypad Mode.
1128 To operate the Calculator, just click on the ``buttons'' of the
1129 keypad using your left mouse button. To enter the two numbers
1130 shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
1131 add them together you would then click @kbd{+} (to get 12.3 on
1134 If you click the right mouse button, the top three rows of the
1135 keypad change to show other sets of commands, such as advanced
1136 math functions, vector operations, and operations on binary
1142 Because Keypad Mode doesn't use the regular keyboard, Calc leaves
1143 the cursor in your original editing buffer. You can type in
1144 this buffer in the usual way while also clicking on the Calculator
1145 keypad. One advantage of Keypad Mode is that you don't need an
1146 explicit command to switch between editing and calculating.
1148 If you press @kbd{M-# b} first, you get a full-screen Keypad Mode
1149 (@code{full-calc-keypad}) with three windows: The keypad in the lower
1150 left, the stack in the lower right, and the trail on top.
1152 @c [fix-ref Keypad Mode]
1153 @xref{Keypad Mode}, for further information.
1155 @node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
1156 @subsection Standalone Operation
1159 @cindex Standalone Operation
1160 If you are not in Emacs at the moment but you wish to use Calc,
1161 you must start Emacs first. If all you want is to run Calc, you
1162 can give the commands:
1172 emacs -f full-calc-keypad
1176 which run a full-screen Calculator (as if by @kbd{M-# b M-# c}) or
1177 a full-screen X-based Calculator (as if by @kbd{M-# b M-# k}).
1178 In standalone operation, quitting the Calculator (by pressing
1179 @kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
1182 @node Embedded Mode Overview, Other M-# Commands, Standalone Operation, Using Calc
1183 @subsection Embedded Mode (Overview)
1186 @dfn{Embedded Mode} is a way to use Calc directly from inside an
1187 editing buffer. Suppose you have a formula written as part of a
1201 and you wish to have Calc compute and format the derivative for
1202 you and store this derivative in the buffer automatically. To
1203 do this with Embedded Mode, first copy the formula down to where
1204 you want the result to be:
1218 Now, move the cursor onto this new formula and press @kbd{M-# e}.
1219 Calc will read the formula (using the surrounding blank lines to
1220 tell how much text to read), then push this formula (invisibly)
1221 onto the Calc stack. The cursor will stay on the formula in the
1222 editing buffer, but the buffer's mode line will change to look
1223 like the Calc mode line (with mode indicators like @samp{12 Deg}
1224 and so on). Even though you are still in your editing buffer,
1225 the keyboard now acts like the Calc keyboard, and any new result
1226 you get is copied from the stack back into the buffer. To take
1227 the derivative, you would type @kbd{a d x @key{RET}}.
1241 To make this look nicer, you might want to press @kbd{d =} to center
1242 the formula, and even @kbd{d B} to use ``big'' display mode.
1251 % [calc-mode: justify: center]
1252 % [calc-mode: language: big]
1260 Calc has added annotations to the file to help it remember the modes
1261 that were used for this formula. They are formatted like comments
1262 in the @TeX{} typesetting language, just in case you are using @TeX{}.
1263 (In this example @TeX{} is not being used, so you might want to move
1264 these comments up to the top of the file or otherwise put them out
1267 As an extra flourish, we can add an equation number using a
1268 righthand label: Type @kbd{d @} (1) RET}.
1272 % [calc-mode: justify: center]
1273 % [calc-mode: language: big]
1274 % [calc-mode: right-label: " (1)"]
1282 To leave Embedded Mode, type @kbd{M-# e} again. The mode line
1283 and keyboard will revert to the way they were before. (If you have
1284 actually been trying this as you read along, you'll want to press
1285 @kbd{M-# 0} [with the digit zero] now to reset the modes you changed.)
1287 The related command @kbd{M-# w} operates on a single word, which
1288 generally means a single number, inside text. It uses any
1289 non-numeric characters rather than blank lines to delimit the
1290 formula it reads. Here's an example of its use:
1293 A slope of one-third corresponds to an angle of 1 degrees.
1296 Place the cursor on the @samp{1}, then type @kbd{M-# w} to enable
1297 Embedded Mode on that number. Now type @kbd{3 /} (to get one-third),
1298 and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
1299 then @w{@kbd{M-# w}} again to exit Embedded mode.
1302 A slope of one-third corresponds to an angle of 18.4349488229 degrees.
1305 @c [fix-ref Embedded Mode]
1306 @xref{Embedded Mode}, for full details.
1308 @node Other M-# Commands, , Embedded Mode Overview, Using Calc
1309 @subsection Other @kbd{M-#} Commands
1312 Two more Calc-related commands are @kbd{M-# g} and @kbd{M-# r},
1313 which ``grab'' data from a selected region of a buffer into the
1314 Calculator. The region is defined in the usual Emacs way, by
1315 a ``mark'' placed at one end of the region, and the Emacs
1316 cursor or ``point'' placed at the other.
1318 The @kbd{M-# g} command reads the region in the usual left-to-right,
1319 top-to-bottom order. The result is packaged into a Calc vector
1320 of numbers and placed on the stack. Calc (in its standard
1321 user interface) is then started. Type @kbd{v u} if you want
1322 to unpack this vector into separate numbers on the stack. Also,
1323 @kbd{C-u M-# g} interprets the region as a single number or
1326 The @kbd{M-# r} command reads a rectangle, with the point and
1327 mark defining opposite corners of the rectangle. The result
1328 is a matrix of numbers on the Calculator stack.
1330 Complementary to these is @kbd{M-# y}, which ``yanks'' the
1331 value at the top of the Calc stack back into an editing buffer.
1332 If you type @w{@kbd{M-# y}} while in such a buffer, the value is
1333 yanked at the current position. If you type @kbd{M-# y} while
1334 in the Calc buffer, Calc makes an educated guess as to which
1335 editing buffer you want to use. The Calc window does not have
1336 to be visible in order to use this command, as long as there
1337 is something on the Calc stack.
1339 Here, for reference, is the complete list of @kbd{M-#} commands.
1340 The shift, control, and meta keys are ignored for the keystroke
1341 following @kbd{M-#}.
1344 Commands for turning Calc on and off:
1348 Turn Calc on or off, employing the same user interface as last time.
1351 Turn Calc on or off using its standard bottom-of-the-screen
1352 interface. If Calc is already turned on but the cursor is not
1353 in the Calc window, move the cursor into the window.
1356 Same as @kbd{C}, but don't select the new Calc window. If
1357 Calc is already turned on and the cursor is in the Calc window,
1358 move it out of that window.
1361 Control whether @kbd{M-# c} and @kbd{M-# k} use the full screen.
1364 Use Quick Mode for a single short calculation.
1367 Turn Calc Keypad mode on or off.
1370 Turn Calc Embedded mode on or off at the current formula.
1373 Turn Calc Embedded mode on or off, select the interesting part.
1376 Turn Calc Embedded mode on or off at the current word (number).
1379 Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
1382 Quit Calc; turn off standard, Keypad, or Embedded mode if on.
1383 (This is like @kbd{q} or @key{OFF} inside of Calc.)
1391 Commands for moving data into and out of the Calculator:
1395 Grab the region into the Calculator as a vector.
1398 Grab the rectangular region into the Calculator as a matrix.
1401 Grab the rectangular region and compute the sums of its columns.
1404 Grab the rectangular region and compute the sums of its rows.
1407 Yank a value from the Calculator into the current editing buffer.
1416 Commands for use with Embedded Mode:
1420 ``Activate'' the current buffer. Locate all formulas that
1421 contain @samp{:=} or @samp{=>} symbols and record their locations
1422 so that they can be updated automatically as variables are changed.
1425 Duplicate the current formula immediately below and select
1429 Insert a new formula at the current point.
1432 Move the cursor to the next active formula in the buffer.
1435 Move the cursor to the previous active formula in the buffer.
1438 Update (i.e., as if by the @kbd{=} key) the formula at the current point.
1441 Edit (as if by @code{calc-edit}) the formula at the current point.
1450 Miscellaneous commands:
1454 Run the Emacs Info system to read the Calc manual.
1455 (This is the same as @kbd{h i} inside of Calc.)
1458 Run the Emacs Info system to read the Calc Tutorial.
1461 Run the Emacs Info system to read the Calc Summary.
1464 Load Calc entirely into memory. (Normally the various parts
1465 are loaded only as they are needed.)
1468 Read a region of written keystroke names (like @samp{C-n a b c RET})
1469 and record them as the current keyboard macro.
1472 (This is the ``zero'' digit key.) Reset the Calculator to
1473 its default state: Empty stack, and default mode settings.
1474 With any prefix argument, reset everything but the stack.
1478 @node History and Acknowledgements, , Using Calc, Getting Started
1479 @section History and Acknowledgements
1482 Calc was originally started as a two-week project to occupy a lull
1483 in the author's schedule. Basically, a friend asked if I remembered
1484 the value of @c{$2^{32}$}
1485 @cite{2^32}. I didn't offhand, but I said, ``that's
1486 easy, just call up an @code{xcalc}.'' @code{Xcalc} duly reported
1487 that the answer to our question was @samp{4.294967e+09}---with no way to
1488 see the full ten digits even though we knew they were there in the
1489 program's memory! I was so annoyed, I vowed to write a calculator
1490 of my own, once and for all.
1492 I chose Emacs Lisp, a) because I had always been curious about it
1493 and b) because, being only a text editor extension language after
1494 all, Emacs Lisp would surely reach its limits long before the project
1495 got too far out of hand.
1497 To make a long story short, Emacs Lisp turned out to be a distressingly
1498 solid implementation of Lisp, and the humble task of calculating
1499 turned out to be more open-ended than one might have expected.
1501 Emacs Lisp doesn't have built-in floating point math, so it had to be
1502 simulated in software. In fact, Emacs integers will only comfortably
1503 fit six decimal digits or so---not enough for a decent calculator. So
1504 I had to write my own high-precision integer code as well, and once I had
1505 this I figured that arbitrary-size integers were just as easy as large
1506 integers. Arbitrary floating-point precision was the logical next step.
1507 Also, since the large integer arithmetic was there anyway it seemed only
1508 fair to give the user direct access to it, which in turn made it practical
1509 to support fractions as well as floats. All these features inspired me
1510 to look around for other data types that might be worth having.
1512 Around this time, my friend Rick Koshi showed me his nifty new HP-28
1513 calculator. It allowed the user to manipulate formulas as well as
1514 numerical quantities, and it could also operate on matrices. I decided
1515 that these would be good for Calc to have, too. And once things had
1516 gone this far, I figured I might as well take a look at serious algebra
1517 systems like Mathematica, Macsyma, and Maple for further ideas. Since
1518 these systems did far more than I could ever hope to implement, I decided
1519 to focus on rewrite rules and other programming features so that users
1520 could implement what they needed for themselves.
1522 Rick complained that matrices were hard to read, so I put in code to
1523 format them in a 2D style. Once these routines were in place, Big mode
1524 was obligatory. Gee, what other language modes would be useful?
1526 Scott Hemphill and Allen Knutson, two friends with a strong mathematical
1527 bent, contributed ideas and algorithms for a number of Calc features
1528 including modulo forms, primality testing, and float-to-fraction conversion.
1530 Units were added at the eager insistence of Mass Sivilotti. Later,
1531 Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
1532 expert assistance with the units table. As far as I can remember, the
1533 idea of using algebraic formulas and variables to represent units dates
1534 back to an ancient article in Byte magazine about muMath, an early
1535 algebra system for microcomputers.
1537 Many people have contributed to Calc by reporting bugs and suggesting
1538 features, large and small. A few deserve special mention: Tim Peters,
1539 who helped develop the ideas that led to the selection commands, rewrite
1540 rules, and many other algebra features; @c{Fran\c cois}
1541 @asis{Francois} Pinard, who contributed
1542 an early prototype of the Calc Summary appendix as well as providing
1543 valuable suggestions in many other areas of Calc; Carl Witty, whose eagle
1544 eyes discovered many typographical and factual errors in the Calc manual;
1545 Tim Kay, who drove the development of Embedded mode; Ove Ewerlid, who
1546 made many suggestions relating to the algebra commands and contributed
1547 some code for polynomial operations; Randal Schwartz, who suggested the
1548 @code{calc-eval} function; Robert J. Chassell, who suggested the Calc
1549 Tutorial and exercises; and Juha Sarlin, who first worked out how to split
1550 Calc into quickly-loading parts. Bob Weiner helped immensely with the
1553 @cindex Bibliography
1554 @cindex Knuth, Art of Computer Programming
1555 @cindex Numerical Recipes
1556 @c Should these be expanded into more complete references?
1557 Among the books used in the development of Calc were Knuth's @emph{Art
1558 of Computer Programming} (especially volume II, @emph{Seminumerical
1559 Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
1560 and Vetterling; Bevington's @emph{Data Reduction and Error Analysis for
1561 the Physical Sciences}; @emph{Concrete Mathematics} by Graham, Knuth,
1562 and Patashnik; Steele's @emph{Common Lisp, the Language}; the @emph{CRC
1563 Standard Math Tables} (William H. Beyer, ed.); and Abramowitz and
1564 Stegun's venerable @emph{Handbook of Mathematical Functions}. I
1565 consulted the user's manuals for the HP-28 and HP-48 calculators, as
1566 well as for the programs Mathematica, SMP, Macsyma, Maple, MathCAD,
1567 Gnuplot, and others. Also, of course, Calc could not have been written
1568 without the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil
1569 Lewis and Dan LaLiberte.
1571 Final thanks go to Richard Stallman, without whose fine implementations
1572 of the Emacs editor, language, and environment, Calc would have been
1573 finished in two weeks.
1578 @c This node is accessed by the `M-# t' command.
1579 @node Interactive Tutorial, , , Top
1583 Some brief instructions on using the Emacs Info system for this tutorial:
1585 Press the space bar and Delete keys to go forward and backward in a
1586 section by screenfuls (or use the regular Emacs scrolling commands
1589 Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
1590 If the section has a @dfn{menu}, press a digit key like @kbd{1}
1591 or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to
1592 go back up from a sub-section to the menu it is part of.
1594 Exercises in the tutorial all have cross-references to the
1595 appropriate page of the ``answers'' section. Press @kbd{f}, then
1596 the exercise number, to see the answer to an exercise. After
1597 you have followed a cross-reference, you can press the letter
1598 @kbd{l} to return to where you were before.
1600 You can press @kbd{?} at any time for a brief summary of Info commands.
1602 Press @kbd{1} now to enter the first section of the Tutorial.
1609 @node Tutorial, Introduction, Getting Started, Top
1613 This chapter explains how to use Calc and its many features, in
1614 a step-by-step, tutorial way. You are encouraged to run Calc and
1615 work along with the examples as you read (@pxref{Starting Calc}).
1616 If you are already familiar with advanced calculators, you may wish
1618 to skip on to the rest of this manual.
1620 @c to skip on to volume II of this manual, the @dfn{Calc Reference}.
1622 @c [fix-ref Embedded Mode]
1623 This tutorial describes the standard user interface of Calc only.
1624 The ``Quick Mode'' and ``Keypad Mode'' interfaces are fairly
1625 self-explanatory. @xref{Embedded Mode}, for a description of
1626 the ``Embedded Mode'' interface.
1629 The easiest way to read this tutorial on-line is to have two windows on
1630 your Emacs screen, one with Calc and one with the Info system. (If you
1631 have 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
1633 press @kbd{M-# i} to start the Info system or to switch into its window.
1634 Or, you may prefer to use the tutorial in printed form.
1637 The easiest way to read this tutorial on-line is to have two windows on
1638 your Emacs screen, one with Calc and one with the Info system. (If you
1639 have a printed copy of the manual you can use that instead.) Press
1640 @kbd{M-# c} to turn Calc on or to switch into the Calc window, and
1641 press @kbd{M-# i} to start the Info system or to switch into its window.
1644 This tutorial is designed to be done in sequence. But the rest of this
1645 manual does not assume you have gone through the tutorial. The tutorial
1646 does not cover everything in the Calculator, but it touches on most
1650 You may wish to print out a copy of the Calc Summary and keep notes on
1651 it as you learn Calc. @xref{Installation}, to see how to make a printed
1652 summary. @xref{Summary}.
1655 The Calc Summary at the end of the reference manual includes some blank
1656 space for your own use. You may wish to keep notes there as you learn
1662 * Arithmetic Tutorial::
1663 * Vector/Matrix Tutorial::
1665 * Algebra Tutorial::
1666 * Programming Tutorial::
1668 * Answers to Exercises::
1671 @node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
1672 @section Basic Tutorial
1675 In this section, we learn how RPN and algebraic-style calculations
1676 work, how to undo and redo an operation done by mistake, and how
1677 to control various modes of the Calculator.
1680 * RPN Tutorial:: Basic operations with the stack.
1681 * Algebraic Tutorial:: Algebraic entry; variables.
1682 * Undo Tutorial:: If you make a mistake: Undo and the trail.
1683 * Modes Tutorial:: Common mode-setting commands.
1686 @node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
1687 @subsection RPN Calculations and the Stack
1689 @cindex RPN notation
1692 Calc normally uses RPN notation. You may be familiar with the RPN
1693 system from Hewlett-Packard calculators, FORTH, or PostScript.
1694 (Reverse Polish Notation, RPN, is named after the Polish mathematician
1699 Calc normally uses RPN notation. You may be familiar with the RPN
1700 system from Hewlett-Packard calculators, FORTH, or PostScript.
1701 (Reverse Polish Notation, RPN, is named after the Polish mathematician
1705 The central component of an RPN calculator is the @dfn{stack}. A
1706 calculator stack is like a stack of dishes. New dishes (numbers) are
1707 added at the top of the stack, and numbers are normally only removed
1708 from the top of the stack.
1712 In an operation like @cite{2+3}, the 2 and 3 are called the @dfn{operands}
1713 and the @cite{+} is the @dfn{operator}. In an RPN calculator you always
1714 enter the operands first, then the operator. Each time you type a
1715 number, Calc adds or @dfn{pushes} it onto the top of the Stack.
1716 When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
1717 number of operands from the stack and pushes back the result.
1719 Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
1720 @kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to
1721 the @key{ENTER} key on traditional RPN calculators.) Try this now if
1722 you wish; type @kbd{M-# c} to switch into the Calc window (you can type
1723 @kbd{M-# c} again or @kbd{M-# o} to switch back to the Tutorial window).
1724 The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
1725 The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
1726 and pushes the result (5) back onto the stack. Here's how the stack
1727 will look at various points throughout the calculation:@refill
1735 M-# c 2 RET 3 RET + DEL
1739 The @samp{.} symbol is a marker that represents the top of the stack.
1740 Note that the ``top'' of the stack is really shown at the bottom of
1741 the Stack window. This may seem backwards, but it turns out to be
1742 less distracting in regular use.
1744 @cindex Stack levels
1745 @cindex Levels of stack
1746 The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
1747 numbers}. Old RPN calculators always had four stack levels called
1748 @cite{x}, @cite{y}, @cite{z}, and @cite{t}. Calc's stack can grow
1749 as large as you like, so it uses numbers instead of letters. Some
1750 stack-manipulation commands accept a numeric argument that says
1751 which stack level to work on. Normal commands like @kbd{+} always
1752 work on the top few levels of the stack.@refill
1754 @c [fix-ref Truncating the Stack]
1755 The Stack buffer is just an Emacs buffer, and you can move around in
1756 it using the regular Emacs motion commands. But no matter where the
1757 cursor is, even if you have scrolled the @samp{.} marker out of
1758 view, most Calc commands always move the cursor back down to level 1
1759 before doing anything. It is possible to move the @samp{.} marker
1760 upwards through the stack, temporarily ``hiding'' some numbers from
1761 commands like @kbd{+}. This is called @dfn{stack truncation} and
1762 we will not cover it in this tutorial; @pxref{Truncating the Stack},
1763 if you are interested.
1765 You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
1766 @key{RET} +}. That's because if you type any operator name or
1767 other non-numeric key when you are entering a number, the Calculator
1768 automatically enters that number and then does the requested command.
1769 Thus @kbd{2 @key{RET} 3 +} will work just as well.@refill
1771 Examples in this tutorial will often omit @key{RET} even when the
1772 stack displays shown would only happen if you did press @key{RET}:
1785 Here, after pressing @kbd{3} the stack would really show @samp{1: 2}
1786 with @samp{Calc:@: 3} in the minibuffer. In these situations, you can
1787 press the optional @key{RET} to see the stack as the figure shows.
1789 (@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises
1790 at various points. Try them if you wish. Answers to all the exercises
1791 are located at the end of the Tutorial chapter. Each exercise will
1792 include a cross-reference to its particular answer. If you are
1793 reading with the Emacs Info system, press @kbd{f} and the
1794 exercise number to go to the answer, then the letter @kbd{l} to
1795 return to where you were.)
1798 Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2
1799 @key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for
1800 multiplication.) Figure it out by hand, then try it with Calc to see
1801 if you're right. @xref{RPN Answer 1, 1}. (@bullet{})
1803 (@bullet{}) @strong{Exercise 2.} Compute @c{$(2\times4) + (7\times9.4) + {5\over4}$}
1804 @cite{2*4 + 7*9.5 + 5/4} using the
1805 stack. @xref{RPN Answer 2, 2}. (@bullet{})
1807 The @key{DEL} key is called Backspace on some keyboards. It is
1808 whatever key you would use to correct a simple typing error when
1809 regularly using Emacs. The @key{DEL} key pops and throws away the
1810 top value on the stack. (You can still get that value back from
1811 the Trail if you should need it later on.) There are many places
1812 in this tutorial where we assume you have used @key{DEL} to erase the
1813 results of the previous example at the beginning of a new example.
1814 In the few places where it is really important to use @key{DEL} to
1815 clear away old results, the text will remind you to do so.
1817 (It won't hurt to let things accumulate on the stack, except that
1818 whenever you give a display-mode-changing command Calc will have to
1819 spend a long time reformatting such a large stack.)
1821 Since the @kbd{-} key is also an operator (it subtracts the top two
1822 stack elements), how does one enter a negative number? Calc uses
1823 the @kbd{_} (underscore) key to act like the minus sign in a number.
1824 So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
1825 will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
1827 You can also press @kbd{n}, which means ``change sign.'' It changes
1828 the number at the top of the stack (or the number being entered)
1829 from positive to negative or vice-versa: @kbd{5 n @key{RET}}.
1831 @cindex Duplicating a stack entry
1832 If you press @key{RET} when you're not entering a number, the effect
1833 is to duplicate the top number on the stack. Consider this calculation:
1837 1: 3 2: 3 1: 9 2: 9 1: 81
1846 (Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
1847 to raise 3 to the fourth power.)
1849 The space-bar key (denoted @key{SPC} here) performs the same function
1850 as @key{RET}; you could replace all three occurrences of @key{RET} in
1851 the above example with @key{SPC} and the effect would be the same.
1853 @cindex Exchanging stack entries
1854 Another stack manipulation key is @key{TAB}. This exchanges the top
1855 two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +}
1856 to get 5, and then you realize what you really wanted to compute
1857 was @cite{20 / (2+3)}.
1861 1: 5 2: 5 2: 20 1: 4
1870 Planning ahead, the calculation would have gone like this:
1874 1: 20 2: 20 3: 20 2: 20 1: 4
1883 A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
1884 @key{TAB}). It rotates the top three elements of the stack upward,
1885 bringing the object in level 3 to the top.
1889 1: 10 2: 10 3: 10 3: 20 3: 30
1890 . 1: 20 2: 20 2: 30 2: 10
1894 10 RET 20 RET 30 RET M-TAB M-TAB
1898 (@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
1899 on the stack. Figure out how to add one to the number in level 2
1900 without affecting the rest of the stack. Also figure out how to add
1901 one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{})
1903 Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
1904 arguments from the stack and push a result. Operations like @kbd{n} and
1905 @kbd{Q} (square root) pop a single number and push the result. You can
1906 think of them as simply operating on the top element of the stack.
1910 1: 3 1: 9 2: 9 1: 25 1: 5
1914 3 RET RET * 4 RET RET * + Q
1919 (Note that capital @kbd{Q} means to hold down the Shift key while
1920 typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.)
1922 @cindex Pythagorean Theorem
1923 Here we've used the Pythagorean Theorem to determine the hypotenuse of a
1924 right triangle. Calc actually has a built-in command for that called
1925 @kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
1926 We can still enter it by its full name using @kbd{M-x} notation:
1934 3 RET 4 RET M-x calc-hypot
1938 All Calculator commands begin with the word @samp{calc-}. Since it
1939 gets tiring to type this, Calc provides an @kbd{x} key which is just
1940 like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
1953 What happens if you take the square root of a negative number?
1957 1: 4 1: -4 1: (0, 2)
1965 The notation @cite{(a, b)} represents a complex number.
1966 Complex numbers are more traditionally written @c{$a + b i$}
1968 Calc can display in this format, too, but for now we'll stick to the
1969 @cite{(a, b)} notation.
1971 If you don't know how complex numbers work, you can safely ignore this
1972 feature. Complex numbers only arise from operations that would be
1973 errors in a calculator that didn't have complex numbers. (For example,
1974 taking the square root or logarithm of a negative number produces a
1977 Complex numbers are entered in the notation shown. The @kbd{(} and
1978 @kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
1982 1: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3)
1990 You can perform calculations while entering parts of incomplete objects.
1991 However, an incomplete object cannot actually participate in a calculation:
1995 1: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ...
2005 Adding 5 to an incomplete object makes no sense, so the last command
2006 produces an error message and leaves the stack the same.
2008 Incomplete objects can't participate in arithmetic, but they can be
2009 moved around by the regular stack commands.
2013 2: 2 3: 2 3: 3 1: ( ... 1: (2, 3)
2014 1: 3 2: 3 2: ( ... 2 .
2018 2 RET 3 RET ( M-TAB M-TAB )
2023 Note that the @kbd{,} (comma) key did not have to be used here.
2024 When you press @kbd{)} all the stack entries between the incomplete
2025 entry and the top are collected, so there's never really a reason
2026 to use the comma. It's up to you.
2028 (@bullet{}) @strong{Exercise 4.} To enter the complex number @cite{(2, 3)},
2029 your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened?
2030 (Joe thought of a clever way to correct his mistake in only two
2031 keystrokes, but it didn't quite work. Try it to find out why.)
2032 @xref{RPN Answer 4, 4}. (@bullet{})
2034 Vectors are entered the same way as complex numbers, but with square
2035 brackets in place of parentheses. We'll meet vectors again later in
2038 Any Emacs command can be given a @dfn{numeric prefix argument} by
2039 typing a series of @key{META}-digits beforehand. If @key{META} is
2040 awkward for you, you can instead type @kbd{C-u} followed by the
2041 necessary digits. Numeric prefix arguments can be negative, as in
2042 @kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric
2043 prefix arguments in a variety of ways. For example, a numeric prefix
2044 on the @kbd{+} operator adds any number of stack entries at once:
2048 1: 10 2: 10 3: 10 3: 10 1: 60
2049 . 1: 20 2: 20 2: 20 .
2053 10 RET 20 RET 30 RET C-u 3 +
2057 For stack manipulation commands like @key{RET}, a positive numeric
2058 prefix argument operates on the top @var{n} stack entries at once. A
2059 negative argument operates on the entry in level @var{n} only. An
2060 argument of zero operates on the entire stack. In this example, we copy
2061 the second-to-top element of the stack:
2065 1: 10 2: 10 3: 10 3: 10 4: 10
2066 . 1: 20 2: 20 2: 20 3: 20
2071 10 RET 20 RET 30 RET C-u -2 RET
2075 @cindex Clearing the stack
2076 @cindex Emptying the stack
2077 Another common idiom is @kbd{M-0 DEL}, which clears the stack.
2078 (The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
2081 @node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
2082 @subsection Algebraic-Style Calculations
2085 If you are not used to RPN notation, you may prefer to operate the
2086 Calculator in ``algebraic mode,'' which is closer to the way
2087 non-RPN calculators work. In algebraic mode, you enter formulas
2088 in traditional @cite{2+3} notation.
2090 You don't really need any special ``mode'' to enter algebraic formulas.
2091 You can enter a formula at any time by pressing the apostrophe (@kbd{'})
2092 key. Answer the prompt with the desired formula, then press @key{RET}.
2093 The formula is evaluated and the result is pushed onto the RPN stack.
2094 If you don't want to think in RPN at all, you can enter your whole
2095 computation as a formula, read the result from the stack, then press
2096 @key{DEL} to delete it from the stack.
2098 Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
2099 The result should be the number 9.
2101 Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
2102 @samp{/}, and @samp{^}. You can use parentheses to make the order
2103 of evaluation clear. In the absence of parentheses, @samp{^} is
2104 evaluated first, then @samp{*}, then @samp{/}, then finally
2105 @samp{+} and @samp{-}. For example, the expression
2108 2 + 3*4*5 / 6*7^8 - 9
2115 2 + ((3*4*5) / (6*(7^8)) - 9
2119 or, in large mathematical notation,
2134 $$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
2139 The result of this expression will be the number @i{-6.99999826533}.
2141 Calc's order of evaluation is the same as for most computer languages,
2142 except that @samp{*} binds more strongly than @samp{/}, as the above
2143 example shows. As in normal mathematical notation, the @samp{*} symbol
2144 can often be omitted: @samp{2 a} is the same as @samp{2*a}.
2146 Operators at the same level are evaluated from left to right, except
2147 that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is
2148 equivalent to @samp{(2-3)-4} or @i{-5}, whereas @samp{2^3^4} is equivalent
2149 to @samp{2^(3^4)} (a very large integer; try it!).
2151 If you tire of typing the apostrophe all the time, there is an
2152 ``algebraic mode'' you can select in which Calc automatically senses
2153 when you are about to type an algebraic expression. To enter this
2154 mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator
2155 should appear in the Calc window's mode line.)
2157 Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
2159 In algebraic mode, when you press any key that would normally begin
2160 entering a number (such as a digit, a decimal point, or the @kbd{_}
2161 key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
2164 Functions which do not have operator symbols like @samp{+} and @samp{*}
2165 must be entered in formulas using function-call notation. For example,
2166 the function name corresponding to the square-root key @kbd{Q} is
2167 @code{sqrt}. To compute a square root in a formula, you would use
2168 the notation @samp{sqrt(@var{x})}.
2170 Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should
2171 be @cite{0.16227766017}.
2173 Note that if the formula begins with a function name, you need to use
2174 the apostrophe even if you are in algebraic mode. If you type @kbd{arcsin}
2175 out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
2176 command, and the @kbd{csin} will be taken as the name of the rewrite
2179 Some people prefer to enter complex numbers and vectors in algebraic
2180 form because they find RPN entry with incomplete objects to be too
2181 distracting, even though they otherwise use Calc as an RPN calculator.
2183 Still in algebraic mode, type:
2187 1: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1)
2188 . 1: (1, -2) . 1: 1 .
2191 (2,3) RET (1,-2) RET * 1 RET +
2195 Algebraic mode allows us to enter complex numbers without pressing
2196 an apostrophe first, but it also means we need to press @key{RET}
2197 after every entry, even for a simple number like @cite{1}.
2199 (You can type @kbd{C-u m a} to enable a special ``incomplete algebraic
2200 mode'' in which the @kbd{(} and @kbd{[} keys use algebraic entry even
2201 though regular numeric keys still use RPN numeric entry. There is also
2202 a ``total algebraic mode,'' started by typing @kbd{m t}, in which all
2203 normal keys begin algebraic entry. You must then use the @key{META} key
2204 to type Calc commands: @kbd{M-m t} to get back out of total algebraic
2205 mode, @kbd{M-q} to quit, etc. Total algebraic mode is not supported
2208 If you're still in algebraic mode, press @kbd{m a} again to turn it off.
2210 Actual non-RPN calculators use a mixture of algebraic and RPN styles.
2211 In general, operators of two numbers (like @kbd{+} and @kbd{*})
2212 use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
2213 use RPN form. Also, a non-RPN calculator allows you to see the
2214 intermediate results of a calculation as you go along. You can
2215 accomplish this in Calc by performing your calculation as a series
2216 of algebraic entries, using the @kbd{$} sign to tie them together.
2217 In an algebraic formula, @kbd{$} represents the number on the top
2218 of the stack. Here, we perform the calculation @c{$\sqrt{2\times4+1}$}
2220 which on a traditional calculator would be done by pressing
2221 @kbd{2 * 4 + 1 =} and then the square-root key.
2233 Notice that we didn't need to press an apostrophe for the @kbd{$+1},
2234 because the dollar sign always begins an algebraic entry.
2236 (@bullet{}) @strong{Exercise 1.} How could you get the same effect as
2237 pressing @kbd{Q} but using an algebraic entry instead? How about
2238 if the @kbd{Q} key on your keyboard were broken?
2239 @xref{Algebraic Answer 1, 1}. (@bullet{})
2241 The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
2242 entries. For example, @kbd{' $$+$ RET} is just like typing @kbd{+}.
2244 Algebraic formulas can include @dfn{variables}. To store in a
2245 variable, press @kbd{s s}, then type the variable name, then press
2246 @key{RET}. (There are actually two flavors of store command:
2247 @kbd{s s} stores a number in a variable but also leaves the number
2248 on the stack, while @w{@kbd{s t}} removes a number from the stack and
2249 stores it in the variable.) A variable name should consist of one
2250 or more letters or digits, beginning with a letter.
2254 1: 17 . 1: a + a^2 1: 306
2257 17 s t a RET ' a+a^2 RET =
2262 The @kbd{=} key @dfn{evaluates} a formula by replacing all its
2263 variables by the values that were stored in them.
2265 For RPN calculations, you can recall a variable's value on the
2266 stack either by entering its name as a formula and pressing @kbd{=},
2267 or by using the @kbd{s r} command.
2271 1: 17 2: 17 3: 17 2: 17 1: 306
2272 . 1: 17 2: 17 1: 289 .
2276 s r a RET ' a RET = 2 ^ +
2280 If you press a single digit for a variable name (as in @kbd{s t 3}, you
2281 get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
2282 They are ``quick'' simply because you don't have to type the letter
2283 @code{q} or the @key{RET} after their names. In fact, you can type
2284 simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
2285 @kbd{t 3} and @w{@kbd{r 3}}.
2287 Any variables in an algebraic formula for which you have not stored
2288 values are left alone, even when you evaluate the formula.
2292 1: 2 a + 2 b 1: 34 + 2 b
2299 Calls to function names which are undefined in Calc are also left
2300 alone, as are calls for which the value is undefined.
2304 1: 2 + log10(0) + log10(x) + log10(5, 6) + foo(3)
2307 ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) RET
2312 In this example, the first call to @code{log10} works, but the other
2313 calls are not evaluated. In the second call, the logarithm is
2314 undefined for that value of the argument; in the third, the argument
2315 is symbolic, and in the fourth, there are too many arguments. In the
2316 fifth case, there is no function called @code{foo}. You will see a
2317 ``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
2318 Press the @kbd{w} (``why'') key to see any other messages that may
2319 have arisen from the last calculation. In this case you will get
2320 ``logarithm of zero,'' then ``number expected: @code{x}''. Calc
2321 automatically displays the first message only if the message is
2322 sufficiently important; for example, Calc considers ``wrong number
2323 of arguments'' and ``logarithm of zero'' to be important enough to
2324 report automatically, while a message like ``number expected: @code{x}''
2325 will only show up if you explicitly press the @kbd{w} key.
2327 (@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y},
2328 stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
2329 @samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)},
2330 expecting @samp{10 (1+y)}, but it didn't work. Why not?
2331 @xref{Algebraic Answer 2, 2}. (@bullet{})
2333 (@bullet{}) @strong{Exercise 3.} What result would you expect
2334 @kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}?
2335 @xref{Algebraic Answer 3, 3}. (@bullet{})
2337 One interesting way to work with variables is to use the
2338 @dfn{evaluates-to} (@samp{=>}) operator. It works like this:
2339 Enter a formula algebraically in the usual way, but follow
2340 the formula with an @samp{=>} symbol. (There is also an @kbd{s =}
2341 command which builds an @samp{=>} formula using the stack.) On
2342 the stack, you will see two copies of the formula with an @samp{=>}
2343 between them. The lefthand formula is exactly like you typed it;
2344 the righthand formula has been evaluated as if by typing @kbd{=}.
2348 2: 2 + 3 => 5 2: 2 + 3 => 5
2349 1: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b
2352 ' 2+3 => RET ' 2a+2b RET s = 10 s t a RET
2357 Notice that the instant we stored a new value in @code{a}, all
2358 @samp{=>} operators already on the stack that referred to @cite{a}
2359 were updated to use the new value. With @samp{=>}, you can push a
2360 set of formulas on the stack, then change the variables experimentally
2361 to see the effects on the formulas' values.
2363 You can also ``unstore'' a variable when you are through with it:
2368 1: 2 a + 2 b => 2 a + 2 b
2375 We will encounter formulas involving variables and functions again
2376 when we discuss the algebra and calculus features of the Calculator.
2378 @node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
2379 @subsection Undo and Redo
2382 If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
2383 the ``undo'' command. First, clear the stack (@kbd{M-0 DEL}) and exit
2384 and restart Calc (@kbd{M-# M-# M-# M-#}) to make sure things start off
2385 with a clean slate. Now:
2389 1: 2 2: 2 1: 8 2: 2 1: 6
2397 You can undo any number of times. Calc keeps a complete record of
2398 all you have done since you last opened the Calc window. After the
2399 above example, you could type:
2411 You can also type @kbd{D} to ``redo'' a command that you have undone
2416 . 1: 2 2: 2 1: 6 1: 6
2425 It was not possible to redo past the @cite{6}, since that was placed there
2426 by something other than an undo command.
2429 You can think of undo and redo as a sort of ``time machine.'' Press
2430 @kbd{U} to go backward in time, @kbd{D} to go forward. If you go
2431 backward and do something (like @kbd{*}) then, as any science fiction
2432 reader knows, you have changed your future and you cannot go forward
2433 again. Thus, the inability to redo past the @cite{6} even though there
2434 was an earlier undo command.
2436 You can always recall an earlier result using the Trail. We've ignored
2437 the trail so far, but it has been faithfully recording everything we
2438 did since we loaded the Calculator. If the Trail is not displayed,
2439 press @kbd{t d} now to turn it on.
2441 Let's try grabbing an earlier result. The @cite{8} we computed was
2442 undone by a @kbd{U} command, and was lost even to Redo when we pressed
2443 @kbd{*}, but it's still there in the trail. There should be a little
2444 @samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
2445 entry. If there isn't, press @kbd{t ]} to reset the trail pointer.
2446 Now, press @w{@kbd{t p}} to move the arrow onto the line containing
2447 @cite{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
2450 If you press @kbd{t ]} again, you will see that even our Yank command
2451 went into the trail.
2453 Let's go further back in time. Earlier in the tutorial we computed
2454 a huge integer using the formula @samp{2^3^4}. We don't remember
2455 what it was, but the first digits were ``241''. Press @kbd{t r}
2456 (which stands for trail-search-reverse), then type @kbd{241}.
2457 The trail cursor will jump back to the next previous occurrence of
2458 the string ``241'' in the trail. This is just a regular Emacs
2459 incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
2460 continue the search forwards or backwards as you like.
2462 To finish the search, press @key{RET}. This halts the incremental
2463 search and leaves the trail pointer at the thing we found. Now we
2464 can type @kbd{t y} to yank that number onto the stack. If we hadn't
2465 remembered the ``241'', we could simply have searched for @kbd{2^3^4},
2466 then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
2468 You may have noticed that all the trail-related commands begin with
2469 the letter @kbd{t}. (The store-and-recall commands, on the other hand,
2470 all began with @kbd{s}.) Calc has so many commands that there aren't
2471 enough keys for all of them, so various commands are grouped into
2472 two-letter sequences where the first letter is called the @dfn{prefix}
2473 key. If you type a prefix key by accident, you can press @kbd{C-g}
2474 to cancel it. (In fact, you can press @kbd{C-g} to cancel almost
2475 anything in Emacs.) To get help on a prefix key, press that key
2476 followed by @kbd{?}. Some prefixes have several lines of help,
2477 so you need to press @kbd{?} repeatedly to see them all. This may
2478 not work under Lucid Emacs, but you can also type @kbd{h h} to
2479 see all the help at once.
2481 Try pressing @kbd{t ?} now. You will see a line of the form,
2484 trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-
2488 The word ``trail'' indicates that the @kbd{t} prefix key contains
2489 trail-related commands. Each entry on the line shows one command,
2490 with a single capital letter showing which letter you press to get
2491 that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
2492 @kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?}
2493 again to see more @kbd{t}-prefix comands. Notice that the commands
2494 are roughly divided (by semicolons) into related groups.
2496 When you are in the help display for a prefix key, the prefix is
2497 still active. If you press another key, like @kbd{y} for example,
2498 it will be interpreted as a @kbd{t y} command. If all you wanted
2499 was to look at the help messages, press @kbd{C-g} afterwards to cancel
2502 One more way to correct an error is by editing the stack entries.
2503 The actual Stack buffer is marked read-only and must not be edited
2504 directly, but you can press @kbd{`} (the backquote or accent grave)
2505 to edit a stack entry.
2507 Try entering @samp{3.141439} now. If this is supposed to represent
2509 @cite{pi}, it's got several errors. Press @kbd{`} to edit this number.
2510 Now use the normal Emacs cursor motion and editing keys to change
2511 the second 4 to a 5, and to transpose the 3 and the 9. When you
2512 press @key{RET}, the number on the stack will be replaced by your
2513 new number. This works for formulas, vectors, and all other types
2514 of values you can put on the stack. The @kbd{`} key also works
2515 during entry of a number or algebraic formula.
2517 @node Modes Tutorial, , Undo Tutorial, Basic Tutorial
2518 @subsection Mode-Setting Commands
2521 Calc has many types of @dfn{modes} that affect the way it interprets
2522 your commands or the way it displays data. We have already seen one
2523 mode, namely algebraic mode. There are many others, too; we'll
2524 try some of the most common ones here.
2526 Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
2527 Notice the @samp{12} on the Calc window's mode line:
2530 --%%-Calc: 12 Deg (Calculator)----All------
2534 Most of the symbols there are Emacs things you don't need to worry
2535 about, but the @samp{12} and the @samp{Deg} are mode indicators.
2536 The @samp{12} means that calculations should always be carried to
2537 12 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /},
2538 we get @cite{0.142857142857} with exactly 12 digits, not counting
2539 leading and trailing zeros.
2541 You can set the precision to anything you like by pressing @kbd{p},
2542 then entering a suitable number. Try pressing @kbd{p 30 @key{RET}},
2543 then doing @kbd{1 @key{RET} 7 /} again:
2548 2: 0.142857142857142857142857142857
2553 Although the precision can be set arbitrarily high, Calc always
2554 has to have @emph{some} value for the current precision. After
2555 all, the true value @cite{1/7} is an infinitely repeating decimal;
2556 Calc has to stop somewhere.
2558 Of course, calculations are slower the more digits you request.
2559 Press @w{@kbd{p 12}} now to set the precision back down to the default.
2561 Calculations always use the current precision. For example, even
2562 though we have a 30-digit value for @cite{1/7} on the stack, if
2563 we use it in a calculation in 12-digit mode it will be rounded
2564 down to 12 digits before it is used. Try it; press @key{RET} to
2565 duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET}
2566 key didn't round the number, because it doesn't do any calculation.
2567 But the instant we pressed @kbd{+}, the number was rounded down.
2572 2: 0.142857142857142857142857142857
2579 In fact, since we added a digit on the left, we had to lose one
2580 digit on the right from even the 12-digit value of @cite{1/7}.
2582 How did we get more than 12 digits when we computed @samp{2^3^4}? The
2583 answer is that Calc makes a distinction between @dfn{integers} and
2584 @dfn{floating-point} numbers, or @dfn{floats}. An integer is a number
2585 that does not contain a decimal point. There is no such thing as an
2586 ``infinitely repeating fraction integer,'' so Calc doesn't have to limit
2587 itself. If you asked for @samp{2^10000} (don't try this!), you would
2588 have to wait a long time but you would eventually get an exact answer.
2589 If you ask for @samp{2.^10000}, you will quickly get an answer which is
2590 correct only to 12 places. The decimal point tells Calc that it should
2591 use floating-point arithmetic to get the answer, not exact integer
2594 You can use the @kbd{F} (@code{calc-floor}) command to convert a
2595 floating-point value to an integer, and @kbd{c f} (@code{calc-float})
2596 to convert an integer to floating-point form.
2598 Let's try entering that last calculation:
2602 1: 2. 2: 2. 1: 1.99506311689e3010
2611 @cindex Scientific notation, entry of
2612 Notice the letter @samp{e} in there. It represents ``times ten to the
2613 power of,'' and is used by Calc automatically whenever writing the
2614 number out fully would introduce more extra zeros than you probably
2615 want to see. You can enter numbers in this notation, too.
2619 1: 2. 2: 2. 1: 1.99506311678e3010
2627 @cindex Round-off errors
2629 Hey, the answer is different! Look closely at the middle columns
2630 of the two examples. In the first, the stack contained the
2631 exact integer @cite{10000}, but in the second it contained
2632 a floating-point value with a decimal point. When you raise a
2633 number to an integer power, Calc uses repeated squaring and
2634 multiplication to get the answer. When you use a floating-point
2635 power, Calc uses logarithms and exponentials. As you can see,
2636 a slight error crept in during one of these methods. Which
2637 one should we trust? Let's raise the precision a bit and find
2642 . 1: 2. 2: 2. 1: 1.995063116880828e3010
2646 p 16 RET 2. RET 1e4 ^ p 12 RET
2651 @cindex Guard digits
2652 Presumably, it doesn't matter whether we do this higher-precision
2653 calculation using an integer or floating-point power, since we
2654 have added enough ``guard digits'' to trust the first 12 digits
2655 no matter what. And the verdict is@dots{} Integer powers were more
2656 accurate; in fact, the result was only off by one unit in the
2659 @cindex Guard digits
2660 Calc does many of its internal calculations to a slightly higher
2661 precision, but it doesn't always bump the precision up enough.
2662 In each case, Calc added about two digits of precision during
2663 its calculation and then rounded back down to 12 digits
2664 afterward. In one case, it was enough; in the other, it
2665 wasn't. If you really need @var{x} digits of precision, it
2666 never hurts to do the calculation with a few extra guard digits.
2668 What if we want guard digits but don't want to look at them?
2669 We can set the @dfn{float format}. Calc supports four major
2670 formats for floating-point numbers, called @dfn{normal},
2671 @dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
2672 notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f},
2673 @kbd{d s}, and @kbd{d e}, respectively. In each case, you can
2674 supply a numeric prefix argument which says how many digits
2675 should be displayed. As an example, let's put a few numbers
2676 onto the stack and try some different display modes. First,
2677 use @kbd{M-0 DEL} to clear the stack, then enter the four
2682 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345
2683 3: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000
2684 2: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450
2685 1: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345
2688 d n M-3 d n d s M-3 d s M-3 d f
2693 Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
2694 to three significant digits, but then when we typed @kbd{d s} all
2695 five significant figures reappeared. The float format does not
2696 affect how numbers are stored, it only affects how they are
2697 displayed. Only the current precision governs the actual rounding
2698 of numbers in the Calculator's memory.
2700 Engineering notation, not shown here, is like scientific notation
2701 except the exponent (the power-of-ten part) is always adjusted to be
2702 a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result
2703 there will be one, two, or three digits before the decimal point.
2705 Whenever you change a display-related mode, Calc redraws everything
2706 in the stack. This may be slow if there are many things on the stack,
2707 so Calc allows you to type shift-@kbd{H} before any mode command to
2708 prevent it from updating the stack. Anything Calc displays after the
2709 mode-changing command will appear in the new format.
2713 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345
2714 3: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345.
2715 2: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45
2716 1: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345
2719 H d s DEL U TAB d SPC d n
2724 Here the @kbd{H d s} command changes to scientific notation but without
2725 updating the screen. Deleting the top stack entry and undoing it back
2726 causes it to show up in the new format; swapping the top two stack
2727 entries reformats both entries. The @kbd{d SPC} command refreshes the
2728 whole stack. The @kbd{d n} command changes back to the normal float
2729 format; since it doesn't have an @kbd{H} prefix, it also updates all
2730 the stack entries to be in @kbd{d n} format.
2732 Notice that the integer @cite{12345} was not affected by any
2733 of the float formats. Integers are integers, and are always
2736 @cindex Large numbers, readability
2737 Large integers have their own problems. Let's look back at
2738 the result of @kbd{2^3^4}.
2741 2417851639229258349412352
2745 Quick---how many digits does this have? Try typing @kbd{d g}:
2748 2,417,851,639,229,258,349,412,352
2752 Now how many digits does this have? It's much easier to tell!
2753 We can actually group digits into clumps of any size. Some
2754 people prefer @kbd{M-5 d g}:
2757 24178,51639,22925,83494,12352
2760 Let's see what happens to floating-point numbers when they are grouped.
2761 First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
2762 to get ourselves into trouble. Now, type @kbd{1e13 /}:
2765 24,17851,63922.9258349412352
2769 The integer part is grouped but the fractional part isn't. Now try
2770 @kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
2773 24,17851,63922.92583,49412,352
2776 If you find it hard to tell the decimal point from the commas, try
2777 changing the grouping character to a space with @kbd{d , @key{SPC}}:
2780 24 17851 63922.92583 49412 352
2783 Type @kbd{d , ,} to restore the normal grouping character, then
2784 @kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to
2785 restore the default precision.
2787 Press @kbd{U} enough times to get the original big integer back.
2788 (Notice that @kbd{U} does not undo each mode-setting command; if
2789 you want to undo a mode-setting command, you have to do it yourself.)
2790 Now, type @kbd{d r 16 @key{RET}}:
2793 16#200000000000000000000
2797 The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
2798 Suddenly it looks pretty simple; this should be no surprise, since we
2799 got this number by computing a power of two, and 16 is a power of 2.
2800 In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
2804 2#1000000000000000000000000000000000000000000000000000000 @dots{}
2808 We don't have enough space here to show all the zeros! They won't
2809 fit on a typical screen, either, so you will have to use horizontal
2810 scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the
2811 stack window left and right by half its width. Another way to view
2812 something large is to press @kbd{`} (back-quote) to edit the top of
2813 stack in a separate window. (Press @kbd{M-# M-#} when you are done.)
2815 You can enter non-decimal numbers using the @kbd{#} symbol, too.
2816 Let's see what the hexadecimal number @samp{5FE} looks like in
2817 binary. Type @kbd{16#5FE} (the letters can be typed in upper or
2818 lower case; they will always appear in upper case). It will also
2819 help to turn grouping on with @kbd{d g}:
2825 Notice that @kbd{d g} groups by fours by default if the display radix
2826 is binary or hexadecimal, but by threes if it is decimal, octal, or any
2829 Now let's see that number in decimal; type @kbd{d r 10}:
2835 Numbers are not @emph{stored} with any particular radix attached. They're
2836 just numbers; they can be entered in any radix, and are always displayed
2837 in whatever radix you've chosen with @kbd{d r}. The current radix applies
2838 to integers, fractions, and floats.
2840 @cindex Roundoff errors, in non-decimal numbers
2841 (@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third
2842 as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got
2843 @samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied
2844 that by three, he got @samp{3#0.222222...} instead of the expected
2845 @samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief,
2846 saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got
2847 @samp{3#0.10000001} (some zeros omitted). What's going on here?
2848 @xref{Modes Answer 1, 1}. (@bullet{})
2850 @cindex Scientific notation, in non-decimal numbers
2851 (@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal
2852 modes in the natural way (the exponent is a power of the radix instead of
2853 a power of ten, although the exponent itself is always written in decimal).
2854 Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number
2855 @samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}.
2856 What is wrong with this picture? What could we write instead that would
2857 work better? @xref{Modes Answer 2, 2}. (@bullet{})
2859 The @kbd{m} prefix key has another set of modes, relating to the way
2860 Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix
2861 modes generally affect the way things look, @kbd{m}-prefix modes affect
2862 the way they are actually computed.
2864 The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice
2865 the @samp{Deg} indicator in the mode line. This means that if you use
2866 a command that interprets a number as an angle, it will assume the
2867 angle is measured in degrees. For example,
2871 1: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5
2879 The shift-@kbd{S} command computes the sine of an angle. The sine
2880 of 45 degrees is @c{$\sqrt{2}/2$}
2881 @cite{sqrt(2)/2}; squaring this yields @cite{2/4 = 0.5}.
2882 However, there has been a slight roundoff error because the
2883 representation of @c{$\sqrt{2}/2$}
2884 @cite{sqrt(2)/2} wasn't exact. The @kbd{c 1}
2885 command is a handy way to clean up numbers in this case; it
2886 temporarily reduces the precision by one digit while it
2887 re-rounds the number on the top of the stack.
2889 @cindex Roundoff errors, examples
2890 (@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine
2891 of 45 degrees as shown above, then, hoping to avoid an inexact
2892 result, he increased the precision to 16 digits before squaring.
2893 What happened? @xref{Modes Answer 3, 3}. (@bullet{})
2895 To do this calculation in radians, we would type @kbd{m r} first.
2896 (The indicator changes to @samp{Rad}.) 45 degrees corresponds to
2898 @cite{pi/4} radians. To get @c{$\pi$}
2899 @cite{pi}, press the @kbd{P} key. (Once
2900 again, this is a shifted capital @kbd{P}. Remember, unshifted
2901 @kbd{p} sets the precision.)
2905 1: 3.14159265359 1: 0.785398163398 1: 0.707106781187
2912 Likewise, inverse trigonometric functions generate results in
2913 either radians or degrees, depending on the current angular mode.
2917 1: 0.707106781187 1: 0.785398163398 1: 45.
2920 .5 Q m r I S m d U I S
2925 Here we compute the Inverse Sine of @c{$\sqrt{0.5}$}
2926 @cite{sqrt(0.5)}, first in
2927 radians, then in degrees.
2929 Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
2934 1: 45 1: 0.785398163397 1: 45.
2941 Another interesting mode is @dfn{fraction mode}. Normally,
2942 dividing two integers produces a floating-point result if the
2943 quotient can't be expressed as an exact integer. Fraction mode
2944 causes integer division to produce a fraction, i.e., a rational
2949 2: 12 1: 1.33333333333 1: 4:3
2953 12 RET 9 / m f U / m f
2958 In the first case, we get an approximate floating-point result.
2959 In the second case, we get an exact fractional result (four-thirds).
2961 You can enter a fraction at any time using @kbd{:} notation.
2962 (Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
2963 because @kbd{/} is already used to divide the top two stack
2964 elements.) Calculations involving fractions will always
2965 produce exact fractional results; fraction mode only says
2966 what to do when dividing two integers.
2968 @cindex Fractions vs. floats
2969 @cindex Floats vs. fractions
2970 (@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact,
2971 why would you ever use floating-point numbers instead?
2972 @xref{Modes Answer 4, 4}. (@bullet{})
2974 Typing @kbd{m f} doesn't change any existing values in the stack.
2975 In the above example, we had to Undo the division and do it over
2976 again when we changed to fraction mode. But if you use the
2977 evaluates-to operator you can get commands like @kbd{m f} to
2982 1: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3
2985 ' 12/9 => RET p 4 RET m f
2990 In this example, the righthand side of the @samp{=>} operator
2991 on the stack is recomputed when we change the precision, then
2992 again when we change to fraction mode. All @samp{=>} expressions
2993 on the stack are recomputed every time you change any mode that
2994 might affect their values.
2996 @node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
2997 @section Arithmetic Tutorial
3000 In this section, we explore the arithmetic and scientific functions
3001 available in the Calculator.
3003 The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
3004 and @kbd{^}. Each normally takes two numbers from the top of the stack
3005 and pushes back a result. The @kbd{n} and @kbd{&} keys perform
3006 change-sign and reciprocal operations, respectively.
3010 1: 5 1: 0.2 1: 5. 1: -5. 1: 5.
3017 @cindex Binary operators
3018 You can apply a ``binary operator'' like @kbd{+} across any number of
3019 stack entries by giving it a numeric prefix. You can also apply it
3020 pairwise to several stack elements along with the top one if you use
3025 3: 2 1: 9 3: 2 4: 2 3: 12
3026 2: 3 . 2: 3 3: 3 2: 13
3027 1: 4 1: 4 2: 4 1: 14
3031 2 RET 3 RET 4 M-3 + U 10 M-- M-3 +
3035 @cindex Unary operators
3036 You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
3037 stack entries with a numeric prefix, too.
3042 2: 3 2: 0.333333333333 2: 3.
3046 2 RET 3 RET 4 M-3 & M-2 &
3050 Notice that the results here are left in floating-point form.
3051 We can convert them back to integers by pressing @kbd{F}, the
3052 ``floor'' function. This function rounds down to the next lower
3053 integer. There is also @kbd{R}, which rounds to the nearest
3071 Since dividing-and-flooring (i.e., ``integer quotient'') is such a
3072 common operation, Calc provides a special command for that purpose, the
3073 backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which
3074 computes the remainder that would arise from a @kbd{\} operation, i.e.,
3075 the ``modulo'' of two numbers. For example,
3079 2: 1234 1: 12 2: 1234 1: 34
3087 These commands actually work for any real numbers, not just integers.
3091 2: 3.1415 1: 3 2: 3.1415 1: 0.1415
3099 (@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a
3100 frill, since you could always do the same thing with @kbd{/ F}. Think
3101 of a situation where this is not true---@kbd{/ F} would be inadequate.
3102 Now think of a way you could get around the problem if Calc didn't
3103 provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{})
3105 We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
3106 commands. Other commands along those lines are @kbd{C} (cosine),
3107 @kbd{T} (tangent), @kbd{E} (@cite{e^x}) and @kbd{L} (natural
3108 logarithm). These can be modified by the @kbd{I} (inverse) and
3109 @kbd{H} (hyperbolic) prefix keys.
3111 Let's compute the sine and cosine of an angle, and verify the
3112 identity @c{$\sin^2x + \cos^2x = 1$}
3113 @cite{sin(x)^2 + cos(x)^2 = 1}. We'll
3114 arbitrarily pick @i{-64} degrees as a good value for @cite{x}. With
3115 the angular mode set to degrees (type @w{@kbd{m d}}), do:
3119 2: -64 2: -64 2: -0.89879 2: -0.89879 1: 1.
3120 1: -64 1: -0.89879 1: -64 1: 0.43837 .
3123 64 n RET RET S TAB C f h
3128 (For brevity, we're showing only five digits of the results here.
3129 You can of course do these calculations to any precision you like.)
3131 Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
3132 of squares, command.
3134 Another identity is @c{$\displaystyle\tan x = {\sin x \over \cos x}$}
3135 @cite{tan(x) = sin(x) / cos(x)}.
3139 2: -0.89879 1: -2.0503 1: -64.
3147 A physical interpretation of this calculation is that if you move
3148 @cite{0.89879} units downward and @cite{0.43837} units to the right,
3149 your direction of motion is @i{-64} degrees from horizontal. Suppose
3150 we move in the opposite direction, up and to the left:
3154 2: -0.89879 2: 0.89879 1: -2.0503 1: -64.
3155 1: 0.43837 1: -0.43837 . .
3163 How can the angle be the same? The answer is that the @kbd{/} operation
3164 loses information about the signs of its inputs. Because the quotient
3165 is negative, we know exactly one of the inputs was negative, but we
3166 can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which
3167 computes the inverse tangent of the quotient of a pair of numbers.
3168 Since you feed it the two original numbers, it has enough information
3169 to give you a full 360-degree answer.
3173 2: 0.89879 1: 116. 3: 116. 2: 116. 1: 180.
3174 1: -0.43837 . 2: -0.89879 1: -64. .
3178 U U f T M-RET M-2 n f T -
3183 The resulting angles differ by 180 degrees; in other words, they
3184 point in opposite directions, just as we would expect.
3186 The @key{META}-@key{RET} we used in the third step is the
3187 ``last-arguments'' command. It is sort of like Undo, except that it
3188 restores the arguments of the last command to the stack without removing
3189 the command's result. It is useful in situations like this one,
3190 where we need to do several operations on the same inputs. We could
3191 have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
3192 the top two stack elements right after the @kbd{U U}, then a pair of
3193 @kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
3195 A similar identity is supposed to hold for hyperbolic sines and cosines,
3196 except that it is the @emph{difference}
3197 @c{$\cosh^2x - \sinh^2x$}
3198 @cite{cosh(x)^2 - sinh(x)^2} that always equals one.
3199 Let's try to verify this identity.@refill
3203 2: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54
3204 1: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54
3207 64 n RET RET H C 2 ^ TAB H S 2 ^
3212 @cindex Roundoff errors, examples
3213 Something's obviously wrong, because when we subtract these numbers
3214 the answer will clearly be zero! But if you think about it, if these
3215 numbers @emph{did} differ by one, it would be in the 55th decimal
3216 place. The difference we seek has been lost entirely to roundoff
3219 We could verify this hypothesis by doing the actual calculation with,
3220 say, 60 decimal places of precision. This will be slow, but not
3221 enormously so. Try it if you wish; sure enough, the answer is
3222 0.99999, reasonably close to 1.
3224 Of course, a more reasonable way to verify the identity is to use
3225 a more reasonable value for @cite{x}!
3227 @cindex Common logarithm
3228 Some Calculator commands use the Hyperbolic prefix for other purposes.
3229 The logarithm and exponential functions, for example, work to the base
3230 @cite{e} normally but use base-10 instead if you use the Hyperbolic
3235 1: 1000 1: 6.9077 1: 1000 1: 3
3243 First, we mistakenly compute a natural logarithm. Then we undo
3244 and compute a common logarithm instead.
3246 The @kbd{B} key computes a general base-@var{b} logarithm for any
3251 2: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077
3252 1: 10 . . 1: 2.71828 .
3255 1000 RET 10 B H E H P B
3260 Here we first use @kbd{B} to compute the base-10 logarithm, then use
3261 the ``hyperbolic'' exponential as a cheap hack to recover the number
3262 1000, then use @kbd{B} again to compute the natural logarithm. Note
3263 that @kbd{P} with the hyperbolic prefix pushes the constant @cite{e}
3266 You may have noticed that both times we took the base-10 logarithm
3267 of 1000, we got an exact integer result. Calc always tries to give
3268 an exact rational result for calculations involving rational numbers
3269 where possible. But when we used @kbd{H E}, the result was a
3270 floating-point number for no apparent reason. In fact, if we had
3271 computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
3272 exact integer 1000. But the @kbd{H E} command is rigged to generate
3273 a floating-point result all of the time so that @kbd{1000 H E} will
3274 not waste time computing a thousand-digit integer when all you
3275 probably wanted was @samp{1e1000}.
3277 (@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to
3278 the @kbd{B} command for which Calc could find an exact rational
3279 result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{})
3281 The Calculator also has a set of functions relating to combinatorics
3282 and statistics. You may be familiar with the @dfn{factorial} function,
3283 which computes the product of all the integers up to a given number.
3287 1: 100 1: 93326215443... 1: 100. 1: 9.3326e157
3295 Recall, the @kbd{c f} command converts the integer or fraction at the
3296 top of the stack to floating-point format. If you take the factorial
3297 of a floating-point number, you get a floating-point result
3298 accurate to the current precision. But if you give @kbd{!} an
3299 exact integer, you get an exact integer result (158 digits long
3302 If you take the factorial of a non-integer, Calc uses a generalized
3303 factorial function defined in terms of Euler's Gamma function
3306 (which is itself available as the @kbd{f g} command).
3310 3: 4. 3: 24. 1: 5.5 1: 52.342777847
3311 2: 4.5 2: 52.3427777847 . .
3315 M-3 ! M-0 DEL 5.5 f g
3320 Here we verify the identity @c{$n! = \Gamma(n+1)$}
3321 @cite{@var{n}!@: = gamma(@var{n}+1)}.
3323 The binomial coefficient @var{n}-choose-@var{m}@c{ or $\displaystyle {n \choose m}$}
3324 @asis{} is defined by
3325 @c{$\displaystyle {n! \over m! \, (n-m)!}$}
3326 @cite{n!@: / m!@: (n-m)!} for all reals @cite{n} and
3327 @cite{m}. The intermediate results in this formula can become quite
3328 large even if the final result is small; the @kbd{k c} command computes
3329 a binomial coefficient in a way that avoids large intermediate
3332 The @kbd{k} prefix key defines several common functions out of
3333 combinatorics and number theory. Here we compute the binomial
3334 coefficient 30-choose-20, then determine its prime factorization.
3338 2: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29]
3347 You can verify these prime factors by using @kbd{v u} to ``unpack''
3348 this vector into 8 separate stack entries, then @kbd{M-8 *} to
3349 multiply them back together. The result is the original number,
3353 Suppose a program you are writing needs a hash table with at least
3354 10000 entries. It's best to use a prime number as the actual size
3355 of a hash table. Calc can compute the next prime number after 10000:
3359 1: 10000 1: 10007 1: 9973
3367 Just for kicks we've also computed the next prime @emph{less} than
3370 @c [fix-ref Financial Functions]
3371 @xref{Financial Functions}, for a description of the Calculator
3372 commands that deal with business and financial calculations (functions
3373 like @code{pv}, @code{rate}, and @code{sln}).
3375 @c [fix-ref Binary Number Functions]
3376 @xref{Binary Functions}, to read about the commands for operating
3377 on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
3379 @node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
3380 @section Vector/Matrix Tutorial
3383 A @dfn{vector} is a list of numbers or other Calc data objects.
3384 Calc provides a large set of commands that operate on vectors. Some
3385 are familiar operations from vector analysis. Others simply treat
3386 a vector as a list of objects.
3389 * Vector Analysis Tutorial::
3394 @node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
3395 @subsection Vector Analysis
3398 If you add two vectors, the result is a vector of the sums of the
3399 elements, taken pairwise.
3403 1: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3]
3407 [1,2,3] s 1 [7 6 0] s 2 +
3412 Note that we can separate the vector elements with either commas or
3413 spaces. This is true whether we are using incomplete vectors or
3414 algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these
3415 vectors so we can easily reuse them later.
3417 If you multiply two vectors, the result is the sum of the products
3418 of the elements taken pairwise. This is called the @dfn{dot product}
3432 The dot product of two vectors is equal to the product of their
3433 lengths times the cosine of the angle between them. (Here the vector
3434 is interpreted as a line from the origin @cite{(0,0,0)} to the
3435 specified point in three-dimensional space.) The @kbd{A}
3436 (absolute value) command can be used to compute the length of a
3441 3: 19 3: 19 1: 0.550782 1: 56.579
3442 2: [1, 2, 3] 2: 3.741657 . .
3443 1: [7, 6, 0] 1: 9.219544
3451 First we recall the arguments to the dot product command, then
3452 we compute the absolute values of the top two stack entries to
3453 obtain the lengths of the vectors, then we divide the dot product
3454 by the product of the lengths to get the cosine of the angle.
3455 The inverse cosine finds that the angle between the vectors
3456 is about 56 degrees.
3458 @cindex Cross product
3459 @cindex Perpendicular vectors
3460 The @dfn{cross product} of two vectors is a vector whose length
3461 is the product of the lengths of the inputs times the sine of the
3462 angle between them, and whose direction is perpendicular to both
3463 input vectors. Unlike the dot product, the cross product is
3464 defined only for three-dimensional vectors. Let's double-check
3465 our computation of the angle using the cross product.
3469 2: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579
3470 1: [7, 6, 0] 2: [1, 2, 3] . .
3474 r 1 r 2 V C s 3 M-RET M-2 A * / A I S
3479 First we recall the original vectors and compute their cross product,
3480 which we also store for later reference. Now we divide the vector
3481 by the product of the lengths of the original vectors. The length of
3482 this vector should be the sine of the angle; sure enough, it is!
3484 @c [fix-ref General Mode Commands]
3485 Vector-related commands generally begin with the @kbd{v} prefix key.
3486 Some are uppercase letters and some are lowercase. To make it easier
3487 to type these commands, the shift-@kbd{V} prefix key acts the same as
3488 the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all
3489 prefix keys have this property.)
3491 If we take the dot product of two perpendicular vectors we expect
3492 to get zero, since the cosine of 90 degrees is zero. Let's check
3493 that the cross product is indeed perpendicular to both inputs:
3497 2: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0
3498 1: [-18, 21, -8] . 1: [-18, 21, -8] .
3501 r 1 r 3 * DEL r 2 r 3 *
3505 @cindex Normalizing a vector
3506 @cindex Unit vectors
3507 (@bullet{}) @strong{Exercise 1.} Given a vector on the top of the
3508 stack, what keystrokes would you use to @dfn{normalize} the
3509 vector, i.e., to reduce its length to one without changing its
3510 direction? @xref{Vector Answer 1, 1}. (@bullet{})
3512 (@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be
3513 at any of several positions along a ruler. You have a list of
3514 those positions in the form of a vector, and another list of the
3515 probabilities for the particle to be at the corresponding positions.
3516 Find the average position of the particle.
3517 @xref{Vector Answer 2, 2}. (@bullet{})
3519 @node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
3520 @subsection Matrices
3523 A @dfn{matrix} is just a vector of vectors, all the same length.
3524 This means you can enter a matrix using nested brackets. You can
3525 also use the semicolon character to enter a matrix. We'll show
3530 1: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3531 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3534 [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] RET
3539 We'll be using this matrix again, so type @kbd{s 4} to save it now.
3541 Note that semicolons work with incomplete vectors, but they work
3542 better in algebraic entry. That's why we use the apostrophe in
3545 When two matrices are multiplied, the lefthand matrix must have
3546 the same number of columns as the righthand matrix has rows.
3547 Row @cite{i}, column @cite{j} of the result is effectively the
3548 dot product of row @cite{i} of the left matrix by column @cite{j}
3549 of the right matrix.
3551 If we try to duplicate this matrix and multiply it by itself,
3552 the dimensions are wrong and the multiplication cannot take place:
3556 1: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ]
3557 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3565 Though rather hard to read, this is a formula which shows the product
3566 of two matrices. The @samp{*} function, having invalid arguments, has
3567 been left in symbolic form.
3569 We can multiply the matrices if we @dfn{transpose} one of them first.
3573 2: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ]
3574 [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ]
3575 1: [ [ 1, 4 ] . [ 27, 36, 45 ] ]
3584 Matrix multiplication is not commutative; indeed, switching the
3585 order of the operands can even change the dimensions of the result
3586 matrix, as happened here!
3588 If you multiply a plain vector by a matrix, it is treated as a
3589 single row or column depending on which side of the matrix it is
3590 on. The result is a plain vector which should also be interpreted
3591 as a row or column as appropriate.
3595 2: [ [ 1, 2, 3 ] 1: [14, 32]
3604 Multiplying in the other order wouldn't work because the number of
3605 rows in the matrix is different from the number of elements in the
3608 (@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows
3609 of the above @c{$2\times3$}
3610 @asis{2x3} matrix to get @cite{[6, 15]}. Now use @samp{*} to
3611 sum along the columns to get @cite{[5, 7, 9]}.
3612 @xref{Matrix Answer 1, 1}. (@bullet{})
3614 @cindex Identity matrix
3615 An @dfn{identity matrix} is a square matrix with ones along the
3616 diagonal and zeros elsewhere. It has the property that multiplication
3617 by an identity matrix, on the left or on the right, always produces
3618 the original matrix.
3622 1: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3623 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3624 . 1: [ [ 1, 0, 0 ] .
3633 If a matrix is square, it is often possible to find its @dfn{inverse},
3634 that is, a matrix which, when multiplied by the original matrix, yields
3635 an identity matrix. The @kbd{&} (reciprocal) key also computes the
3636 inverse of a matrix.
3640 1: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ]
3641 [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ]
3642 [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ]
3650 The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
3651 matrices together. Here we have used it to add a new row onto
3652 our matrix to make it square.
3654 We can multiply these two matrices in either order to get an identity.
3658 1: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ]
3659 [ 0., 1., 0. ] [ 0., 1., 0. ]
3660 [ 0., 0., 1. ] ] [ 0., 0., 1. ] ]
3667 @cindex Systems of linear equations
3668 @cindex Linear equations, systems of
3669 Matrix inverses are related to systems of linear equations in algebra.
3670 Suppose we had the following set of equations:
3684 $$ \openup1\jot \tabskip=0pt plus1fil
3685 \halign to\displaywidth{\tabskip=0pt
3686 $\hfil#$&$\hfil{}#{}$&
3687 $\hfil#$&$\hfil{}#{}$&
3688 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3697 This can be cast into the matrix equation,
3702 [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ]
3703 [ 4, 5, 6 ] * [ b ] = [ 2 ]
3704 [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]
3711 $$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
3713 \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
3718 We can solve this system of equations by multiplying both sides by the
3719 inverse of the matrix. Calc can do this all in one step:
3723 2: [6, 2, 3] 1: [-12.6, 15.2, -3.93333]
3734 The result is the @cite{[a, b, c]} vector that solves the equations.
3735 (Dividing by a square matrix is equivalent to multiplying by its
3738 Let's verify this solution:
3742 2: [ [ 1, 2, 3 ] 1: [6., 2., 3.]
3745 1: [-12.6, 15.2, -3.93333]
3753 Note that we had to be careful about the order in which we multiplied
3754 the matrix and vector. If we multiplied in the other order, Calc would
3755 assume the vector was a row vector in order to make the dimensions
3756 come out right, and the answer would be incorrect. If you
3757 don't feel safe letting Calc take either interpretation of your
3758 vectors, use explicit @c{$N\times1$}
3759 @asis{Nx1} or @c{$1\times N$}
3760 @asis{1xN} matrices instead.
3761 In this case, you would enter the original column vector as
3762 @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
3764 (@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make
3765 vectors and matrices that include variables. Solve the following
3766 system of equations to get expressions for @cite{x} and @cite{y}
3767 in terms of @cite{a} and @cite{b}.
3780 $$ \eqalign{ x &+ a y = 6 \cr
3787 @xref{Matrix Answer 2, 2}. (@bullet{})
3789 @cindex Least-squares for over-determined systems
3790 @cindex Over-determined systems of equations
3791 (@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined''
3792 if it has more equations than variables. It is often the case that
3793 there are no values for the variables that will satisfy all the
3794 equations at once, but it is still useful to find a set of values
3795 which ``nearly'' satisfy all the equations. In terms of matrix equations,
3796 you can't solve @cite{A X = B} directly because the matrix @cite{A}
3797 is not square for an over-determined system. Matrix inversion works
3798 only for square matrices. One common trick is to multiply both sides
3799 on the left by the transpose of @cite{A}:
3801 @samp{trn(A)*A*X = trn(A)*B}.
3805 $A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
3808 @cite{trn(A)*A} is a square matrix so a solution is possible. It
3809 turns out that the @cite{X} vector you compute in this way will be a
3810 ``least-squares'' solution, which can be regarded as the ``closest''
3811 solution to the set of equations. Use Calc to solve the following
3812 over-determined system:@refill
3827 $$ \openup1\jot \tabskip=0pt plus1fil
3828 \halign to\displaywidth{\tabskip=0pt
3829 $\hfil#$&$\hfil{}#{}$&
3830 $\hfil#$&$\hfil{}#{}$&
3831 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3835 2a&+&4b&+&6c&=11 \cr}
3841 @xref{Matrix Answer 3, 3}. (@bullet{})
3843 @node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
3844 @subsection Vectors as Lists
3848 Although Calc has a number of features for manipulating vectors and
3849 matrices as mathematical objects, you can also treat vectors as
3850 simple lists of values. For example, we saw that the @kbd{k f}
3851 command returns a vector which is a list of the prime factors of a
3854 You can pack and unpack stack entries into vectors:
3858 3: 10 1: [10, 20, 30] 3: 10
3867 You can also build vectors out of consecutive integers, or out
3868 of many copies of a given value:
3872 1: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4]
3873 . 1: 17 1: [17, 17, 17, 17]
3876 v x 4 RET 17 v b 4 RET
3880 You can apply an operator to every element of a vector using the
3885 1: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68]
3893 In the first step, we multiply the vector of integers by the vector
3894 of 17's elementwise. In the second step, we raise each element to
3895 the power two. (The general rule is that both operands must be
3896 vectors of the same length, or else one must be a vector and the
3897 other a plain number.) In the final step, we take the square root
3900 (@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two
3902 @cite{2^-4} to @cite{2^4}. @xref{List Answer 1, 1}. (@bullet{})
3904 You can also @dfn{reduce} a binary operator across a vector.
3905 For example, reducing @samp{*} computes the product of all the
3906 elements in the vector:
3910 1: 123123 1: [3, 7, 11, 13, 41] 1: 123123
3918 In this example, we decompose 123123 into its prime factors, then
3919 multiply those factors together again to yield the original number.
3921 We could compute a dot product ``by hand'' using mapping and
3926 2: [1, 2, 3] 1: [7, 12, 0] 1: 19
3935 Recalling two vectors from the previous section, we compute the
3936 sum of pairwise products of the elements to get the same answer
3937 for the dot product as before.
3939 A slight variant of vector reduction is the @dfn{accumulate} operation,
3940 @kbd{V U}. This produces a vector of the intermediate results from
3941 a corresponding reduction. Here we compute a table of factorials:
3945 1: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720]
3952 Calc allows vectors to grow as large as you like, although it gets
3953 rather slow if vectors have more than about a hundred elements.
3954 Actually, most of the time is spent formatting these large vectors
3955 for display, not calculating on them. Try the following experiment
3956 (if your computer is very fast you may need to substitute a larger
3961 1: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ...
3968 Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
3969 experiment again. In @kbd{v .} mode, long vectors are displayed
3970 ``abbreviated'' like this:
3974 1: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501]
3982 (where now the @samp{...} is actually part of the Calc display).
3983 You will find both operations are now much faster. But notice that
3984 even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
3985 Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
3986 experiment one more time. Operations on long vectors are now quite
3987 fast! (But of course if you use @kbd{t .} you will lose the ability
3988 to get old vectors back using the @kbd{t y} command.)
3990 An easy way to view a full vector when @kbd{v .} mode is active is
3991 to press @kbd{`} (back-quote) to edit the vector; editing always works
3992 with the full, unabbreviated value.
3994 @cindex Least-squares for fitting a straight line
3995 @cindex Fitting data to a line
3996 @cindex Line, fitting data to
3997 @cindex Data, extracting from buffers
3998 @cindex Columns of data, extracting
3999 As a larger example, let's try to fit a straight line to some data,
4000 using the method of least squares. (Calc has a built-in command for
4001 least-squares curve fitting, but we'll do it by hand here just to
4002 practice working with vectors.) Suppose we have the following list
4003 of values in a file we have loaded into Emacs:
4030 If you are reading this tutorial in printed form, you will find it
4031 easiest to press @kbd{M-# i} to enter the on-line Info version of
4032 the manual and find this table there. (Press @kbd{g}, then type
4033 @kbd{List Tutorial}, to jump straight to this section.)
4035 Position the cursor at the upper-left corner of this table, just
4036 to the left of the @cite{1.34}. Press @kbd{C-@@} to set the mark.
4037 (On your system this may be @kbd{C-2}, @kbd{C-SPC}, or @kbd{NUL}.)
4038 Now position the cursor to the lower-right, just after the @cite{1.354}.
4039 You have now defined this region as an Emacs ``rectangle.'' Still
4040 in the Info buffer, type @kbd{M-# r}. This command
4041 (@code{calc-grab-rectangle}) will pop you back into the Calculator, with
4042 the contents of the rectangle you specified in the form of a matrix.@refill
4046 1: [ [ 1.34, 0.234 ]
4053 (You may wish to use @kbd{v .} mode to abbreviate the display of this
4056 We want to treat this as a pair of lists. The first step is to
4057 transpose this matrix into a pair of rows. Remember, a matrix is
4058 just a vector of vectors. So we can unpack the matrix into a pair
4059 of row vectors on the stack.
4063 1: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ]
4064 [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ]
4072 Let's store these in quick variables 1 and 2, respectively.
4076 1: [1.34, 1.41, 1.49, ... ] .
4084 (Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
4085 stored value from the stack.)
4087 In a least squares fit, the slope @cite{m} is given by the formula
4091 m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
4097 $$ m = {N \sum x y - \sum x \sum y \over
4098 N \sum x^2 - \left( \sum x \right)^2} $$
4104 @cite{sum(x)} represents the sum of all the values of @cite{x}.
4105 While there is an actual @code{sum} function in Calc, it's easier to
4106 sum a vector using a simple reduction. First, let's compute the four
4107 different sums that this formula uses.
4114 r 1 V R + t 3 r 1 2 V M ^ V R + t 4
4121 1: 13.613 1: 33.36554
4124 r 2 V R + t 5 r 1 r 2 V M * V R + t 6
4130 These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
4131 respectively. (We could have used @kbd{*} to compute @samp{sum(x^2)} and
4136 These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
4137 respectively. (We could have used \kbd{*} to compute $\sum x^2$ and
4141 Finally, we also need @cite{N}, the number of data points. This is just
4142 the length of either of our lists.
4154 (That's @kbd{v} followed by a lower-case @kbd{l}.)
4156 Now we grind through the formula:
4160 1: 633.94526 2: 633.94526 1: 67.23607
4164 r 7 r 6 * r 3 r 5 * -
4171 2: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679
4172 1: 1862.0057 2: 1862.0057 1: 128.9488 .
4176 r 7 r 4 * r 3 2 ^ - / t 8
4180 That gives us the slope @cite{m}. The y-intercept @cite{b} can now
4181 be found with the simple formula,
4185 b = (sum(y) - m sum(x)) / N
4191 $$ b = {\sum y - m \sum x \over N} $$
4198 1: 13.613 2: 13.613 1: -8.09358 1: -0.425978
4202 r 5 r 8 r 3 * - r 7 / t 9
4206 Let's ``plot'' this straight line approximation, @c{$y \approx m x + b$}
4207 @cite{m x + b}, and compare it with the original data.@refill
4211 1: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ]
4219 Notice that multiplying a vector by a constant, and adding a constant
4220 to a vector, can be done without mapping commands since these are
4221 common operations from vector algebra. As far as Calc is concerned,
4222 we've just been doing geometry in 19-dimensional space!
4224 We can subtract this vector from our original @cite{y} vector to get
4225 a feel for the error of our fit. Let's find the maximum error:
4229 1: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897
4237 First we compute a vector of differences, then we take the absolute
4238 values of these differences, then we reduce the @code{max} function
4239 across the vector. (The @code{max} function is on the two-key sequence
4240 @kbd{f x}; because it is so common to use @code{max} in a vector
4241 operation, the letters @kbd{X} and @kbd{N} are also accepted for
4242 @code{max} and @code{min} in this context. In general, you answer
4243 the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
4244 invokes the function you want. You could have typed @kbd{V R f x} or
4245 even @kbd{V R x max @key{RET}} if you had preferred.)
4247 If your system has the GNUPLOT program, you can see graphs of your
4248 data and your straight line to see how well they match. (If you have
4249 GNUPLOT 3.0, the following instructions will work regardless of the
4250 kind of display you have. Some GNUPLOT 2.0, non-X-windows systems
4251 may require additional steps to view the graphs.)
4253 Let's start by plotting the original data. Recall the ``@i{x}'' and ``@i{y}''
4254 vectors onto the stack and press @kbd{g f}. This ``fast'' graphing
4255 command does everything you need to do for simple, straightforward
4260 2: [1.34, 1.41, 1.49, ... ]
4261 1: [0.234, 0.298, 0.402, ... ]
4268 If all goes well, you will shortly get a new window containing a graph
4269 of the data. (If not, contact your GNUPLOT or Calc installer to find
4270 out what went wrong.) In the X window system, this will be a separate
4271 graphics window. For other kinds of displays, the default is to
4272 display the graph in Emacs itself using rough character graphics.
4273 Press @kbd{q} when you are done viewing the character graphics.
4275 Next, let's add the line we got from our least-squares fit:
4279 2: [1.34, 1.41, 1.49, ... ]
4280 1: [0.273, 0.309, 0.351, ... ]
4287 It's not very useful to get symbols to mark the data points on this
4288 second curve; you can type @kbd{g S g p} to remove them. Type @kbd{g q}
4289 when you are done to remove the X graphics window and terminate GNUPLOT.
4291 (@bullet{}) @strong{Exercise 2.} An earlier exercise showed how to do
4292 least squares fitting to a general system of equations. Our 19 data
4293 points are really 19 equations of the form @cite{y_i = m x_i + b} for
4294 different pairs of @cite{(x_i,y_i)}. Use the matrix-transpose method
4295 to solve for @cite{m} and @cite{b}, duplicating the above result.
4296 @xref{List Answer 2, 2}. (@bullet{})
4298 @cindex Geometric mean
4299 (@bullet{}) @strong{Exercise 3.} If the input data do not form a
4300 rectangle, you can use @w{@kbd{M-# g}} (@code{calc-grab-region})
4301 to grab the data the way Emacs normally works with regions---it reads
4302 left-to-right, top-to-bottom, treating line breaks the same as spaces.
4303 Use this command to find the geometric mean of the following numbers.
4304 (The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
4313 The @kbd{M-# g} command accepts numbers separated by spaces or commas,
4314 with or without surrounding vector brackets.
4315 @xref{List Answer 3, 3}. (@bullet{})
4318 As another example, a theorem about binomial coefficients tells
4319 us that the alternating sum of binomial coefficients
4320 @var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
4321 on up to @var{n}-choose-@var{n},
4322 always comes out to zero. Let's verify this
4323 for @cite{n=6}.@refill
4326 As another example, a theorem about binomial coefficients tells
4327 us that the alternating sum of binomial coefficients
4328 ${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
4329 always comes out to zero. Let's verify this
4335 1: [1, 2, 3, 4, 5, 6, 7] 1: [0, 1, 2, 3, 4, 5, 6]
4345 1: [1, -6, 15, -20, 15, -6, 1] 1: 0
4348 V M ' (-1)^$ choose(6,$) RET V R +
4352 The @kbd{V M '} command prompts you to enter any algebraic expression
4353 to define the function to map over the vector. The symbol @samp{$}
4354 inside this expression represents the argument to the function.
4355 The Calculator applies this formula to each element of the vector,
4356 substituting each element's value for the @samp{$} sign(s) in turn.
4358 To define a two-argument function, use @samp{$$} for the first
4359 argument and @samp{$} for the second: @kbd{V M ' $$-$ RET} is
4360 equivalent to @kbd{V M -}. This is analogous to regular algebraic
4361 entry, where @samp{$$} would refer to the next-to-top stack entry
4362 and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ RET}
4363 would act exactly like @kbd{-}.
4365 Notice that the @kbd{V M '} command has recorded two things in the
4366 trail: The result, as usual, and also a funny-looking thing marked
4367 @samp{oper} that represents the operator function you typed in.
4368 The function is enclosed in @samp{< >} brackets, and the argument is
4369 denoted by a @samp{#} sign. If there were several arguments, they
4370 would be shown as @samp{#1}, @samp{#2}, and so on. (For example,
4371 @kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
4372 trail.) This object is a ``nameless function''; you can use nameless
4373 @w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
4374 Nameless function notation has the interesting, occasionally useful
4375 property that a nameless function is not actually evaluated until
4376 it is used. For example, @kbd{V M ' $+random(2.0)} evaluates
4377 @samp{random(2.0)} once and adds that random number to all elements
4378 of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
4379 @samp{random(2.0)} separately for each vector element.
4381 Another group of operators that are often useful with @kbd{V M} are
4382 the relational operators: @kbd{a =}, for example, compares two numbers
4383 and gives the result 1 if they are equal, or 0 if not. Similarly,
4384 @w{@kbd{a <}} checks for one number being less than another.
4386 Other useful vector operations include @kbd{v v}, to reverse a
4387 vector end-for-end; @kbd{V S}, to sort the elements of a vector
4388 into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
4389 one row or column of a matrix, or (in both cases) to extract one
4390 element of a plain vector. With a negative argument, @kbd{v r}
4391 and @kbd{v c} instead delete one row, column, or vector element.
4393 @cindex Divisor functions
4394 (@bullet{}) @strong{Exercise 4.} The @cite{k}th @dfn{divisor function}
4398 is the sum of the @cite{k}th powers of all the divisors of an
4399 integer @cite{n}. Figure out a method for computing the divisor
4400 function for reasonably small values of @cite{n}. As a test,
4401 the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
4402 @xref{List Answer 4, 4}. (@bullet{})
4404 @cindex Square-free numbers
4405 @cindex Duplicate values in a list
4406 (@bullet{}) @strong{Exercise 5.} The @kbd{k f} command produces a
4407 list of prime factors for a number. Sometimes it is important to
4408 know that a number is @dfn{square-free}, i.e., that no prime occurs
4409 more than once in its list of prime factors. Find a sequence of
4410 keystrokes to tell if a number is square-free; your method should
4411 leave 1 on the stack if it is, or 0 if it isn't.
4412 @xref{List Answer 5, 5}. (@bullet{})
4414 @cindex Triangular lists
4415 (@bullet{}) @strong{Exercise 6.} Build a list of lists that looks
4416 like the following diagram. (You may wish to use the @kbd{v /}
4417 command to enable multi-line display of vectors.)
4426 [1, 2, 3, 4, 5, 6] ]
4431 @xref{List Answer 6, 6}. (@bullet{})
4433 (@bullet{}) @strong{Exercise 7.} Build the following list of lists.
4441 [10, 11, 12, 13, 14],
4442 [15, 16, 17, 18, 19, 20] ]
4447 @xref{List Answer 7, 7}. (@bullet{})
4449 @cindex Maximizing a function over a list of values
4450 @c [fix-ref Numerical Solutions]
4451 (@bullet{}) @strong{Exercise 8.} Compute a list of values of Bessel's
4453 @cite{J1} function @samp{besJ(1,x)} for @cite{x} from 0 to 5
4455 Find the value of @cite{x} (from among the above set of values) for
4456 which @samp{besJ(1,x)} is a maximum. Use an ``automatic'' method,
4457 i.e., just reading along the list by hand to find the largest value
4458 is not allowed! (There is an @kbd{a X} command which does this kind
4459 of thing automatically; @pxref{Numerical Solutions}.)
4460 @xref{List Answer 8, 8}. (@bullet{})@refill
4462 @cindex Digits, vectors of
4463 (@bullet{}) @strong{Exercise 9.} You are given an integer in the range
4464 @c{$0 \le N < 10^m$}
4465 @cite{0 <= N < 10^m} for @cite{m=12} (i.e., an integer of less than
4466 twelve digits). Convert this integer into a vector of @cite{m}
4467 digits, each in the range from 0 to 9. In vector-of-digits notation,
4468 add one to this integer to produce a vector of @cite{m+1} digits
4469 (since there could be a carry out of the most significant digit).
4470 Convert this vector back into a regular integer. A good integer
4471 to try is 25129925999. @xref{List Answer 9, 9}. (@bullet{})
4473 (@bullet{}) @strong{Exercise 10.} Your friend Joe tried to use
4474 @kbd{V R a =} to test if all numbers in a list were equal. What
4475 happened? How would you do this test? @xref{List Answer 10, 10}. (@bullet{})
4477 (@bullet{}) @strong{Exercise 11.} The area of a circle of radius one
4479 @cite{pi}. The area of the @c{$2\times2$}
4480 @asis{2x2} square that encloses that
4481 circle is 4. So if we throw @i{N} darts at random points in the square,
4483 @cite{pi/4} of them will land inside the circle. This gives us
4484 an entertaining way to estimate the value of @c{$\pi$}
4485 @cite{pi}. The @w{@kbd{k r}}
4486 command picks a random number between zero and the value on the stack.
4487 We could get a random floating-point number between @i{-1} and 1 by typing
4488 @w{@kbd{2.0 k r 1 -}}. Build a vector of 100 random @cite{(x,y)} points in
4489 this square, then use vector mapping and reduction to count how many
4490 points lie inside the unit circle. Hint: Use the @kbd{v b} command.
4491 @xref{List Answer 11, 11}. (@bullet{})
4493 @cindex Matchstick problem
4494 (@bullet{}) @strong{Exercise 12.} The @dfn{matchstick problem} provides
4495 another way to calculate @c{$\pi$}
4496 @cite{pi}. Say you have an infinite field
4497 of vertical lines with a spacing of one inch. Toss a one-inch matchstick
4498 onto the field. The probability that the matchstick will land crossing
4499 a line turns out to be @c{$2/\pi$}
4500 @cite{2/pi}. Toss 100 matchsticks to estimate
4502 @cite{pi}. (If you want still more fun, the probability that the GCD
4503 (@w{@kbd{k g}}) of two large integers is one turns out to be @c{$6/\pi^2$}
4505 That provides yet another way to estimate @c{$\pi$}
4507 @xref{List Answer 12, 12}. (@bullet{})
4509 (@bullet{}) @strong{Exercise 13.} An algebraic entry of a string in
4510 double-quote marks, @samp{"hello"}, creates a vector of the numerical
4511 (ASCII) codes of the characters (here, @cite{[104, 101, 108, 108, 111]}).
4512 Sometimes it is convenient to compute a @dfn{hash code} of a string,
4513 which is just an integer that represents the value of that string.
4514 Two equal strings have the same hash code; two different strings
4515 @dfn{probably} have different hash codes. (For example, Calc has
4516 over 400 function names, but Emacs can quickly find the definition for
4517 any given name because it has sorted the functions into ``buckets'' by
4518 their hash codes. Sometimes a few names will hash into the same bucket,
4519 but it is easier to search among a few names than among all the names.)
4520 One popular hash function is computed as follows: First set @cite{h = 0}.
4521 Then, for each character from the string in turn, set @cite{h = 3h + c_i}
4522 where @cite{c_i} is the character's ASCII code. If we have 511 buckets,
4523 we then take the hash code modulo 511 to get the bucket number. Develop a
4524 simple command or commands for converting string vectors into hash codes.
4525 The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
4526 511 is 121. @xref{List Answer 13, 13}. (@bullet{})
4528 (@bullet{}) @strong{Exercise 14.} The @kbd{H V R} and @kbd{H V U}
4529 commands do nested function evaluations. @kbd{H V U} takes a starting
4530 value and a number of steps @var{n} from the stack; it then applies the
4531 function you give to the starting value 0, 1, 2, up to @var{n} times
4532 and returns a vector of the results. Use this command to create a
4533 ``random walk'' of 50 steps. Start with the two-dimensional point
4534 @cite{(0,0)}; then take one step a random distance between @i{-1} and 1
4535 in both @cite{x} and @cite{y}; then take another step, and so on. Use the
4536 @kbd{g f} command to display this random walk. Now modify your random
4537 walk to walk a unit distance, but in a random direction, at each step.
4538 (Hint: The @code{sincos} function returns a vector of the cosine and
4539 sine of an angle.) @xref{List Answer 14, 14}. (@bullet{})
4541 @node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
4542 @section Types Tutorial
4545 Calc understands a variety of data types as well as simple numbers.
4546 In this section, we'll experiment with each of these types in turn.
4548 The numbers we've been using so far have mainly been either @dfn{integers}
4549 or @dfn{floats}. We saw that floats are usually a good approximation to
4550 the mathematical concept of real numbers, but they are only approximations
4551 and are susceptible to roundoff error. Calc also supports @dfn{fractions},
4552 which can exactly represent any rational number.
4556 1: 3628800 2: 3628800 1: 518400:7 1: 518414:7 1: 7:518414
4565 The @kbd{:} command divides two integers to get a fraction; @kbd{/}
4566 would normally divide integers to get a floating-point result.
4567 Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
4568 since the @kbd{:} would otherwise be interpreted as part of a
4569 fraction beginning with 49.
4571 You can convert between floating-point and fractional format using
4572 @kbd{c f} and @kbd{c F}:
4576 1: 1.35027217629e-5 1: 7:518414
4583 The @kbd{c F} command replaces a floating-point number with the
4584 ``simplest'' fraction whose floating-point representation is the
4585 same, to within the current precision.
4589 1: 3.14159265359 1: 1146408:364913 1: 3.1416 1: 355:113
4592 P c F DEL p 5 RET P c F
4596 (@bullet{}) @strong{Exercise 1.} A calculation has produced the
4597 result 1.26508260337. You suspect it is the square root of the
4598 product of @c{$\pi$}
4599 @cite{pi} and some rational number. Is it? (Be sure
4600 to allow for roundoff error!) @xref{Types Answer 1, 1}. (@bullet{})
4602 @dfn{Complex numbers} can be stored in both rectangular and polar form.
4606 1: -9 1: (0, 3) 1: (3; 90.) 1: (6; 90.) 1: (2.4495; 45.)
4614 The square root of @i{-9} is by default rendered in rectangular form
4615 (@w{@cite{0 + 3i}}), but we can convert it to polar form (3 with a
4616 phase angle of 90 degrees). All the usual arithmetic and scientific
4617 operations are defined on both types of complex numbers.
4619 Another generalized kind of number is @dfn{infinity}. Infinity
4620 isn't really a number, but it can sometimes be treated like one.
4621 Calc uses the symbol @code{inf} to represent positive infinity,
4622 i.e., a value greater than any real number. Naturally, you can
4623 also write @samp{-inf} for minus infinity, a value less than any
4624 real number. The word @code{inf} can only be input using
4629 2: inf 2: -inf 2: -inf 2: -inf 1: nan
4630 1: -17 1: -inf 1: -inf 1: inf .
4633 ' inf RET 17 n * RET 72 + A +
4638 Since infinity is infinitely large, multiplying it by any finite
4639 number (like @i{-17}) has no effect, except that since @i{-17}
4640 is negative, it changes a plus infinity to a minus infinity.
4641 (``A huge positive number, multiplied by @i{-17}, yields a huge
4642 negative number.'') Adding any finite number to infinity also
4643 leaves it unchanged. Taking an absolute value gives us plus
4644 infinity again. Finally, we add this plus infinity to the minus
4645 infinity we had earlier. If you work it out, you might expect
4646 the answer to be @i{-72} for this. But the 72 has been completely
4647 lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
4648 the finite difference between them, if any, is indetectable.
4649 So we say the result is @dfn{indeterminate}, which Calc writes
4650 with the symbol @code{nan} (for Not A Number).
4652 Dividing by zero is normally treated as an error, but you can get
4653 Calc to write an answer in terms of infinity by pressing @kbd{m i}
4654 to turn on ``infinite mode.''
4658 3: nan 2: nan 2: nan 2: nan 1: nan
4659 2: 1 1: 1 / 0 1: uinf 1: uinf .
4663 1 RET 0 / m i U / 17 n * +
4668 Dividing by zero normally is left unevaluated, but after @kbd{m i}
4669 it instead gives an infinite result. The answer is actually
4670 @code{uinf}, ``undirected infinity.'' If you look at a graph of
4671 @cite{1 / x} around @w{@cite{x = 0}}, you'll see that it goes toward
4672 plus infinity as you approach zero from above, but toward minus
4673 infinity as you approach from below. Since we said only @cite{1 / 0},
4674 Calc knows that the answer is infinite but not in which direction.
4675 That's what @code{uinf} means. Notice that multiplying @code{uinf}
4676 by a negative number still leaves plain @code{uinf}; there's no
4677 point in saying @samp{-uinf} because the sign of @code{uinf} is
4678 unknown anyway. Finally, we add @code{uinf} to our @code{nan},
4679 yielding @code{nan} again. It's easy to see that, because
4680 @code{nan} means ``totally unknown'' while @code{uinf} means
4681 ``unknown sign but known to be infinite,'' the more mysterious
4682 @code{nan} wins out when it is combined with @code{uinf}, or, for
4683 that matter, with anything else.
4685 (@bullet{}) @strong{Exercise 2.} Predict what Calc will answer
4686 for each of these formulas: @samp{inf / inf}, @samp{exp(inf)},
4687 @samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
4688 @samp{abs(uinf)}, @samp{ln(0)}.
4689 @xref{Types Answer 2, 2}. (@bullet{})
4691 (@bullet{}) @strong{Exercise 3.} We saw that @samp{inf - inf = nan},
4692 which stands for an unknown value. Can @code{nan} stand for
4693 a complex number? Can it stand for infinity?
4694 @xref{Types Answer 3, 3}. (@bullet{})
4696 @dfn{HMS forms} represent a value in terms of hours, minutes, and
4701 1: 2@@ 30' 0" 1: 3@@ 30' 0" 2: 3@@ 30' 0" 1: 2.
4702 . . 1: 1@@ 45' 0." .
4705 2@@ 30' RET 1 + RET 2 / /
4709 HMS forms can also be used to hold angles in degrees, minutes, and
4714 1: 0.5 1: 26.56505 1: 26@@ 33' 54.18" 1: 0.44721
4722 First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
4723 form, then we take the sine of that angle. Note that the trigonometric
4724 functions will accept HMS forms directly as input.
4727 (@bullet{}) @strong{Exercise 4.} The Beatles' @emph{Abbey Road} is
4728 47 minutes and 26 seconds long, and contains 17 songs. What is the
4729 average length of a song on @emph{Abbey Road}? If the Extended Disco
4730 Version of @emph{Abbey Road} added 20 seconds to the length of each
4731 song, how long would the album be? @xref{Types Answer 4, 4}. (@bullet{})
4733 A @dfn{date form} represents a date, or a date and time. Dates must
4734 be entered using algebraic entry. Date forms are surrounded by
4735 @samp{< >} symbols; most standard formats for dates are recognized.
4739 2: <Sun Jan 13, 1991> 1: 2.25
4740 1: <6:00pm Thu Jan 10, 1991> .
4743 ' <13 Jan 1991>, <1/10/91, 6pm> RET -
4748 In this example, we enter two dates, then subtract to find the
4749 number of days between them. It is also possible to add an
4750 HMS form or a number (of days) to a date form to get another
4755 1: <4:45:59pm Mon Jan 14, 1991> 1: <2:50:59am Thu Jan 17, 1991>
4762 @c [fix-ref Date Arithmetic]
4764 The @kbd{t N} (``now'') command pushes the current date and time on the
4765 stack; then we add two days, ten hours and five minutes to the date and
4766 time. Other date-and-time related commands include @kbd{t J}, which
4767 does Julian day conversions, @kbd{t W}, which finds the beginning of
4768 the week in which a date form lies, and @kbd{t I}, which increments a
4769 date by one or several months. @xref{Date Arithmetic}, for more.
4771 (@bullet{}) @strong{Exercise 5.} How many days until the next
4772 Friday the 13th? @xref{Types Answer 5, 5}. (@bullet{})
4774 (@bullet{}) @strong{Exercise 6.} How many leap years will there be
4775 between now and the year 10001 A.D.? @xref{Types Answer 6, 6}. (@bullet{})
4777 @cindex Slope and angle of a line
4778 @cindex Angle and slope of a line
4779 An @dfn{error form} represents a mean value with an attached standard
4780 deviation, or error estimate. Suppose our measurements indicate that
4781 a certain telephone pole is about 30 meters away, with an estimated
4782 error of 1 meter, and 8 meters tall, with an estimated error of 0.2
4783 meters. What is the slope of a line from here to the top of the
4784 pole, and what is the equivalent angle in degrees?
4788 1: 8 +/- 0.2 2: 8 +/- 0.2 1: 0.266 +/- 0.011 1: 14.93 +/- 0.594
4792 8 p .2 RET 30 p 1 / I T
4797 This means that the angle is about 15 degrees, and, assuming our
4798 original error estimates were valid standard deviations, there is about
4799 a 60% chance that the result is correct within 0.59 degrees.
4801 @cindex Torus, volume of
4802 (@bullet{}) @strong{Exercise 7.} The volume of a torus (a donut shape) is
4804 @w{@cite{2 pi^2 R r^2}} where @cite{R} is the radius of the circle that
4805 defines the center of the tube and @cite{r} is the radius of the tube
4806 itself. Suppose @cite{R} is 20 cm and @cite{r} is 4 cm, each known to
4807 within 5 percent. What is the volume and the relative uncertainty of
4808 the volume? @xref{Types Answer 7, 7}. (@bullet{})
4810 An @dfn{interval form} represents a range of values. While an
4811 error form is best for making statistical estimates, intervals give
4812 you exact bounds on an answer. Suppose we additionally know that
4813 our telephone pole is definitely between 28 and 31 meters away,
4814 and that it is between 7.7 and 8.1 meters tall.
4818 1: [7.7 .. 8.1] 2: [7.7 .. 8.1] 1: [0.24 .. 0.28] 1: [13.9 .. 16.1]
4822 [ 7.7 .. 8.1 ] [ 28 .. 31 ] / I T
4827 If our bounds were correct, then the angle to the top of the pole
4828 is sure to lie in the range shown.
4830 The square brackets around these intervals indicate that the endpoints
4831 themselves are allowable values. In other words, the distance to the
4832 telephone pole is between 28 and 31, @emph{inclusive}. You can also
4833 make an interval that is exclusive of its endpoints by writing
4834 parentheses instead of square brackets. You can even make an interval
4835 which is inclusive (``closed'') on one end and exclusive (``open'') on
4840 1: [1 .. 10) 1: (0.1 .. 1] 2: (0.1 .. 1] 1: (0.2 .. 3)
4844 [ 1 .. 10 ) & [ 2 .. 3 ) *
4849 The Calculator automatically keeps track of which end values should
4850 be open and which should be closed. You can also make infinite or
4851 semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
4854 (@bullet{}) @strong{Exercise 8.} What answer would you expect from
4855 @samp{@w{1 /} @w{(0 .. 10)}}? What about @samp{@w{1 /} @w{(-10 .. 0)}}? What
4856 about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
4857 zero)? What about @samp{@w{1 /} @w{(-10 .. 10)}}?
4858 @xref{Types Answer 8, 8}. (@bullet{})
4860 (@bullet{}) @strong{Exercise 9.} Two easy ways of squaring a number
4861 are @kbd{RET *} and @w{@kbd{2 ^}}. Normally these produce the same
4862 answer. Would you expect this still to hold true for interval forms?
4863 If not, which of these will result in a larger interval?
4864 @xref{Types Answer 9, 9}. (@bullet{})
4866 A @dfn{modulo form} is used for performing arithmetic modulo @i{M}.
4867 For example, arithmetic involving time is generally done modulo 12
4872 1: 17 mod 24 1: 3 mod 24 1: 21 mod 24 1: 9 mod 24
4875 17 M 24 RET 10 + n 5 /
4880 In this last step, Calc has found a new number which, when multiplied
4881 by 5 modulo 24, produces the original number, 21. If @i{M} is prime
4882 it is always possible to find such a number. For non-prime @i{M}
4883 like 24, it is only sometimes possible.
4887 1: 10 mod 24 1: 16 mod 24 1: 1000000... 1: 16
4890 10 M 24 RET 100 ^ 10 RET 100 ^ 24 %
4895 These two calculations get the same answer, but the first one is
4896 much more efficient because it avoids the huge intermediate value
4897 that arises in the second one.
4899 @cindex Fermat, primality test of
4900 (@bullet{}) @strong{Exercise 10.} A theorem of Pierre de Fermat
4901 says that @c{\w{$x^{n-1} \bmod n = 1$}}
4902 @cite{x^(n-1) mod n = 1} if @cite{n} is a prime number
4903 and @cite{x} is an integer less than @cite{n}. If @cite{n} is
4904 @emph{not} a prime number, this will @emph{not} be true for most
4905 values of @cite{x}. Thus we can test informally if a number is
4906 prime by trying this formula for several values of @cite{x}.
4907 Use this test to tell whether the following numbers are prime:
4908 811749613, 15485863. @xref{Types Answer 10, 10}. (@bullet{})
4910 It is possible to use HMS forms as parts of error forms, intervals,
4911 modulo forms, or as the phase part of a polar complex number.
4912 For example, the @code{calc-time} command pushes the current time
4913 of day on the stack as an HMS/modulo form.
4917 1: 17@@ 34' 45" mod 24@@ 0' 0" 1: 6@@ 22' 15" mod 24@@ 0' 0"
4925 This calculation tells me it is six hours and 22 minutes until midnight.
4927 (@bullet{}) @strong{Exercise 11.} A rule of thumb is that one year
4928 is about @c{$\pi \times 10^7$}
4929 @w{@cite{pi * 10^7}} seconds. What time will it be that
4930 many seconds from right now? @xref{Types Answer 11, 11}. (@bullet{})
4932 (@bullet{}) @strong{Exercise 12.} You are preparing to order packaging
4933 for the CD release of the Extended Disco Version of @emph{Abbey Road}.
4934 You are told that the songs will actually be anywhere from 20 to 60
4935 seconds longer than the originals. One CD can hold about 75 minutes
4936 of music. Should you order single or double packages?
4937 @xref{Types Answer 12, 12}. (@bullet{})
4939 Another kind of data the Calculator can manipulate is numbers with
4940 @dfn{units}. This isn't strictly a new data type; it's simply an
4941 application of algebraic expressions, where we use variables with
4942 suggestive names like @samp{cm} and @samp{in} to represent units
4943 like centimeters and inches.
4947 1: 2 in 1: 5.08 cm 1: 0.027778 fath 1: 0.0508 m
4950 ' 2in RET u c cm RET u c fath RET u b
4955 We enter the quantity ``2 inches'' (actually an algebraic expression
4956 which means two times the variable @samp{in}), then we convert it
4957 first to centimeters, then to fathoms, then finally to ``base'' units,
4958 which in this case means meters.
4962 1: 9 acre 1: 3 sqrt(acre) 1: 190.84 m 1: 190.84 m + 30 cm
4965 ' 9 acre RET Q u s ' $+30 cm RET
4972 1: 191.14 m 1: 36536.3046 m^2 1: 365363046 cm^2
4980 Since units expressions are really just formulas, taking the square
4981 root of @samp{acre} is undefined. After all, @code{acre} might be an
4982 algebraic variable that you will someday assign a value. We use the
4983 ``units-simplify'' command to simplify the expression with variables
4984 being interpreted as unit names.
4986 In the final step, we have converted not to a particular unit, but to a
4987 units system. The ``cgs'' system uses centimeters instead of meters
4988 as its standard unit of length.
4990 There is a wide variety of units defined in the Calculator.
4994 1: 55 mph 1: 88.5139 kph 1: 88.5139 km / hr 1: 8.201407e-8 c
4997 ' 55 mph RET u c kph RET u c km/hr RET u c c RET
5002 We express a speed first in miles per hour, then in kilometers per
5003 hour, then again using a slightly more explicit notation, then
5004 finally in terms of fractions of the speed of light.
5006 Temperature conversions are a bit more tricky. There are two ways to
5007 interpret ``20 degrees Fahrenheit''---it could mean an actual
5008 temperature, or it could mean a change in temperature. For normal
5009 units there is no difference, but temperature units have an offset
5010 as well as a scale factor and so there must be two explicit commands
5015 1: 20 degF 1: 11.1111 degC 1: -20:3 degC 1: -6.666 degC
5018 ' 20 degF RET u c degC RET U u t degC RET c f
5023 First we convert a change of 20 degrees Fahrenheit into an equivalent
5024 change in degrees Celsius (or Centigrade). Then, we convert the
5025 absolute temperature 20 degrees Fahrenheit into Celsius. Since
5026 this comes out as an exact fraction, we then convert to floating-point
5027 for easier comparison with the other result.
5029 For simple unit conversions, you can put a plain number on the stack.
5030 Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
5031 When you use this method, you're responsible for remembering which
5032 numbers are in which units:
5036 1: 55 1: 88.5139 1: 8.201407e-8
5039 55 u c mph RET kph RET u c km/hr RET c RET
5043 To see a complete list of built-in units, type @kbd{u v}. Press
5044 @w{@kbd{M-# c}} again to re-enter the Calculator when you're done looking
5047 (@bullet{}) @strong{Exercise 13.} How many seconds are there really
5048 in a year? @xref{Types Answer 13, 13}. (@bullet{})
5050 @cindex Speed of light
5051 (@bullet{}) @strong{Exercise 14.} Supercomputer designs are limited by
5052 the speed of light (and of electricity, which is nearly as fast).
5053 Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
5054 cabinet is one meter across. Is speed of light going to be a
5055 significant factor in its design? @xref{Types Answer 14, 14}. (@bullet{})
5057 (@bullet{}) @strong{Exercise 15.} Sam the Slug normally travels about
5058 five yards in an hour. He has obtained a supply of Power Pills; each
5059 Power Pill he eats doubles his speed. How many Power Pills can he
5060 swallow and still travel legally on most US highways?
5061 @xref{Types Answer 15, 15}. (@bullet{})
5063 @node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
5064 @section Algebra and Calculus Tutorial
5067 This section shows how to use Calc's algebra facilities to solve
5068 equations, do simple calculus problems, and manipulate algebraic
5072 * Basic Algebra Tutorial::
5073 * Rewrites Tutorial::
5076 @node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
5077 @subsection Basic Algebra
5080 If you enter a formula in algebraic mode that refers to variables,
5081 the formula itself is pushed onto the stack. You can manipulate
5082 formulas as regular data objects.
5086 1: 2 x^2 - 6 1: 6 - 2 x^2 1: (6 - 2 x^2) (3 x^2 + y)
5089 ' 2x^2-6 RET n ' 3x^2+y RET *
5093 (@bullet{}) @strong{Exercise 1.} Do @kbd{' x RET Q 2 ^} and
5094 @kbd{' x RET 2 ^ Q} both wind up with the same result (@samp{x})?
5095 Why or why not? @xref{Algebra Answer 1, 1}. (@bullet{})
5097 There are also commands for doing common algebraic operations on
5098 formulas. Continuing with the formula from the last example,
5102 1: 18 x^2 + 6 y - 6 x^4 - 2 x^2 y 1: (18 - 2 y) x^2 - 6 x^4 + 6 y
5110 First we ``expand'' using the distributive law, then we ``collect''
5111 terms involving like powers of @cite{x}.
5113 Let's find the value of this expression when @cite{x} is 2 and @cite{y}
5118 1: 17 x^2 - 6 x^4 + 3 1: -25
5121 1:2 s l y RET 2 s l x RET
5126 The @kbd{s l} command means ``let''; it takes a number from the top of
5127 the stack and temporarily assigns it as the value of the variable
5128 you specify. It then evaluates (as if by the @kbd{=} key) the
5129 next expression on the stack. After this command, the variable goes
5130 back to its original value, if any.
5132 (An earlier exercise in this tutorial involved storing a value in the
5133 variable @code{x}; if this value is still there, you will have to
5134 unstore it with @kbd{s u x RET} before the above example will work
5137 @cindex Maximum of a function using Calculus
5138 Let's find the maximum value of our original expression when @cite{y}
5139 is one-half and @cite{x} ranges over all possible values. We can
5140 do this by taking the derivative with respect to @cite{x} and examining
5141 values of @cite{x} for which the derivative is zero. If the second
5142 derivative of the function at that value of @cite{x} is negative,
5143 the function has a local maximum there.
5147 1: 17 x^2 - 6 x^4 + 3 1: 34 x - 24 x^3
5150 U DEL s 1 a d x RET s 2
5155 Well, the derivative is clearly zero when @cite{x} is zero. To find
5156 the other root(s), let's divide through by @cite{x} and then solve:
5160 1: (34 x - 24 x^3) / x 1: 34 x / x - 24 x^3 / x 1: 34 - 24 x^2
5170 1: 34 - 24 x^2 = 0 1: x = 1.19023
5178 Notice the use of @kbd{a s} to ``simplify'' the formula. When the
5179 default algebraic simplifications don't do enough, you can use
5180 @kbd{a s} to tell Calc to spend more time on the job.
5182 Now we compute the second derivative and plug in our values of @cite{x}:
5186 1: 1.19023 2: 1.19023 2: 1.19023
5187 . 1: 34 x - 24 x^3 1: 34 - 72 x^2
5190 a . r 2 a d x RET s 4
5195 (The @kbd{a .} command extracts just the righthand side of an equation.
5196 Another method would have been to use @kbd{v u} to unpack the equation
5197 @w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 DEL}
5198 to delete the @samp{x}.)
5202 2: 34 - 72 x^2 1: -68. 2: 34 - 72 x^2 1: 34
5206 TAB s l x RET U DEL 0 s l x RET
5211 The first of these second derivatives is negative, so we know the function
5212 has a maximum value at @cite{x = 1.19023}. (The function also has a
5213 local @emph{minimum} at @cite{x = 0}.)
5215 When we solved for @cite{x}, we got only one value even though
5216 @cite{34 - 24 x^2 = 0} is a quadratic equation that ought to have
5217 two solutions. The reason is that @w{@kbd{a S}} normally returns a
5218 single ``principal'' solution. If it needs to come up with an
5219 arbitrary sign (as occurs in the quadratic formula) it picks @cite{+}.
5220 If it needs an arbitrary integer, it picks zero. We can get a full
5221 solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
5225 1: 34 - 24 x^2 = 0 1: x = 1.19023 s1 1: x = -1.19023
5228 r 3 H a S x RET s 5 1 n s l s1 RET
5233 Calc has invented the variable @samp{s1} to represent an unknown sign;
5234 it is supposed to be either @i{+1} or @i{-1}. Here we have used
5235 the ``let'' command to evaluate the expression when the sign is negative.
5236 If we plugged this into our second derivative we would get the same,
5237 negative, answer, so @cite{x = -1.19023} is also a maximum.
5239 To find the actual maximum value, we must plug our two values of @cite{x}
5240 into the original formula.
5244 2: 17 x^2 - 6 x^4 + 3 1: 24.08333 s1^2 - 12.04166 s1^4 + 3
5253 (Here we see another way to use @kbd{s l}; if its input is an equation
5254 with a variable on the lefthand side, then @kbd{s l} treats the equation
5255 like an assignment to that variable if you don't give a variable name.)
5257 It's clear that this will have the same value for either sign of
5258 @code{s1}, but let's work it out anyway, just for the exercise:
5262 2: [-1, 1] 1: [15.04166, 15.04166]
5263 1: 24.08333 s1^2 ... .
5266 [ 1 n , 1 ] TAB V M $ RET
5271 Here we have used a vector mapping operation to evaluate the function
5272 at several values of @samp{s1} at once. @kbd{V M $} is like @kbd{V M '}
5273 except that it takes the formula from the top of the stack. The
5274 formula is interpreted as a function to apply across the vector at the
5275 next-to-top stack level. Since a formula on the stack can't contain
5276 @samp{$} signs, Calc assumes the variables in the formula stand for
5277 different arguments. It prompts you for an @dfn{argument list}, giving
5278 the list of all variables in the formula in alphabetical order as the
5279 default list. In this case the default is @samp{(s1)}, which is just
5280 what we want so we simply press @key{RET} at the prompt.
5282 If there had been several different values, we could have used
5283 @w{@kbd{V R X}} to find the global maximum.
5285 Calc has a built-in @kbd{a P} command that solves an equation using
5286 @w{@kbd{H a S}} and returns a vector of all the solutions. It simply
5287 automates the job we just did by hand. Applied to our original
5288 cubic polynomial, it would produce the vector of solutions
5289 @cite{[1.19023, -1.19023, 0]}. (There is also an @kbd{a X} command
5290 which finds a local maximum of a function. It uses a numerical search
5291 method rather than examining the derivatives, and thus requires you
5292 to provide some kind of initial guess to show it where to look.)
5294 (@bullet{}) @strong{Exercise 2.} Given a vector of the roots of a
5295 polynomial (such as the output of an @kbd{a P} command), what
5296 sequence of commands would you use to reconstruct the original
5297 polynomial? (The answer will be unique to within a constant
5298 multiple; choose the solution where the leading coefficient is one.)
5299 @xref{Algebra Answer 2, 2}. (@bullet{})
5301 The @kbd{m s} command enables ``symbolic mode,'' in which formulas
5302 like @samp{sqrt(5)} that can't be evaluated exactly are left in
5303 symbolic form rather than giving a floating-point approximate answer.
5304 Fraction mode (@kbd{m f}) is also useful when doing algebra.
5308 2: 34 x - 24 x^3 2: 34 x - 24 x^3
5309 1: 34 x - 24 x^3 1: [sqrt(51) / 6, sqrt(51) / -6, 0]
5312 r 2 RET m s m f a P x RET
5316 One more mode that makes reading formulas easier is ``Big mode.''
5325 1: [-----, -----, 0]
5334 Here things like powers, square roots, and quotients and fractions
5335 are displayed in a two-dimensional pictorial form. Calc has other
5336 language modes as well, such as C mode, FORTRAN mode, and @TeX{} mode.
5340 2: 34*x - 24*pow(x, 3) 2: 34*x - 24*x**3
5341 1: @{sqrt(51) / 6, sqrt(51) / -6, 0@} 1: /sqrt(51) / 6, sqrt(51) / -6, 0/
5352 2: [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
5353 1: @{2 \over 3@} \sqrt@{5@}
5356 d T ' 2 \sqrt@{5@} \over 3 RET
5361 As you can see, language modes affect both entry and display of
5362 formulas. They affect such things as the names used for built-in
5363 functions, the set of arithmetic operators and their precedences,
5364 and notations for vectors and matrices.
5366 Notice that @samp{sqrt(51)} may cause problems with older
5367 implementations of C and FORTRAN, which would require something more
5368 like @samp{sqrt(51.0)}. It is always wise to check over the formulas
5369 produced by the various language modes to make sure they are fully
5372 Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes. (You
5373 may prefer to remain in Big mode, but all the examples in the tutorial
5374 are shown in normal mode.)
5376 @cindex Area under a curve
5377 What is the area under the portion of this curve from @cite{x = 1} to @cite{2}?
5378 This is simply the integral of the function:
5382 1: 17 x^2 - 6 x^4 + 3 1: 5.6666 x^3 - 1.2 x^5 + 3 x
5390 We want to evaluate this at our two values for @cite{x} and subtract.
5391 One way to do it is again with vector mapping and reduction:
5395 2: [2, 1] 1: [12.93333, 7.46666] 1: 5.46666
5396 1: 5.6666 x^3 ... . .
5398 [ 2 , 1 ] TAB V M $ RET V R -
5402 (@bullet{}) @strong{Exercise 3.} Find the integral from 1 to @cite{y}
5403 of @c{$x \sin \pi x$}
5404 @w{@cite{x sin(pi x)}} (where the sine is calculated in radians).
5405 Find the values of the integral for integers @cite{y} from 1 to 5.
5406 @xref{Algebra Answer 3, 3}. (@bullet{})
5408 Calc's integrator can do many simple integrals symbolically, but many
5409 others are beyond its capabilities. Suppose we wish to find the area
5410 under the curve @c{$\sin x \ln x$}
5411 @cite{sin(x) ln(x)} over the same range of @cite{x}. If
5412 you entered this formula and typed @kbd{a i x RET} (don't bother to try
5413 this), Calc would work for a long time but would be unable to find a
5414 solution. In fact, there is no closed-form solution to this integral.
5417 @cindex Integration, numerical
5418 @cindex Numerical integration
5419 One approach would be to do the integral numerically. It is not hard
5420 to do this by hand using vector mapping and reduction. It is rather
5421 slow, though, since the sine and logarithm functions take a long time.
5422 We can save some time by reducing the working precision.
5426 3: 10 1: [1, 1.1, 1.2, ... , 1.8, 1.9]
5431 10 RET 1 RET .1 RET C-u v x
5436 (Note that we have used the extended version of @kbd{v x}; we could
5437 also have used plain @kbd{v x} as follows: @kbd{v x 10 RET 9 + .1 *}.)
5441 2: [1, 1.1, ... ] 1: [0., 0.084941, 0.16993, ... ]
5445 ' sin(x) ln(x) RET s 1 m r p 5 RET V M $ RET
5460 (If you got wildly different results, did you remember to switch
5463 Here we have divided the curve into ten segments of equal width;
5464 approximating these segments as rectangular boxes (i.e., assuming
5465 the curve is nearly flat at that resolution), we compute the areas
5466 of the boxes (height times width), then sum the areas. (It is
5467 faster to sum first, then multiply by the width, since the width
5468 is the same for every box.)
5470 The true value of this integral turns out to be about 0.374, so
5471 we're not doing too well. Let's try another approach.
5475 1: sin(x) ln(x) 1: 0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
5478 r 1 a t x=1 RET 4 RET
5483 Here we have computed the Taylor series expansion of the function
5484 about the point @cite{x=1}. We can now integrate this polynomial
5485 approximation, since polynomials are easy to integrate.
5489 1: 0.42074 x^2 + ... 1: [-0.0446, -0.42073] 1: 0.3761
5492 a i x RET [ 2 , 1 ] TAB V M $ RET V R -
5497 Better! By increasing the precision and/or asking for more terms
5498 in the Taylor series, we can get a result as accurate as we like.
5499 (Taylor series converge better away from singularities in the
5500 function such as the one at @code{ln(0)}, so it would also help to
5501 expand the series about the points @cite{x=2} or @cite{x=1.5} instead
5504 @cindex Simpson's rule
5505 @cindex Integration by Simpson's rule
5506 (@bullet{}) @strong{Exercise 4.} Our first method approximated the
5507 curve by stairsteps of width 0.1; the total area was then the sum
5508 of the areas of the rectangles under these stairsteps. Our second
5509 method approximated the function by a polynomial, which turned out
5510 to be a better approximation than stairsteps. A third method is
5511 @dfn{Simpson's rule}, which is like the stairstep method except
5512 that the steps are not required to be flat. Simpson's rule boils
5513 down to the formula,
5517 (h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
5518 + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
5525 \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
5526 \hfill \cr \hfill {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
5532 where @cite{n} (which must be even) is the number of slices and @cite{h}
5533 is the width of each slice. These are 10 and 0.1 in our example.
5534 For reference, here is the corresponding formula for the stairstep
5539 h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
5540 + f(a+(n-2)*h) + f(a+(n-1)*h))
5546 $$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
5547 + f(a+(n-2)h) + f(a+(n-1)h)) $$
5551 Compute the integral from 1 to 2 of @c{$\sin x \ln x$}
5552 @cite{sin(x) ln(x)} using
5553 Simpson's rule with 10 slices. @xref{Algebra Answer 4, 4}. (@bullet{})
5555 Calc has a built-in @kbd{a I} command for doing numerical integration.
5556 It uses @dfn{Romberg's method}, which is a more sophisticated cousin
5557 of Simpson's rule. In particular, it knows how to keep refining the
5558 result until the current precision is satisfied.
5560 @c [fix-ref Selecting Sub-Formulas]
5561 Aside from the commands we've seen so far, Calc also provides a
5562 large set of commands for operating on parts of formulas. You
5563 indicate the desired sub-formula by placing the cursor on any part
5564 of the formula before giving a @dfn{selection} command. Selections won't
5565 be covered in the tutorial; @pxref{Selecting Subformulas}, for
5566 details and examples.
5568 @c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
5569 @c to 2^((n-1)*(r-1)).
5571 @node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
5572 @subsection Rewrite Rules
5575 No matter how many built-in commands Calc provided for doing algebra,
5576 there would always be something you wanted to do that Calc didn't have
5577 in its repertoire. So Calc also provides a @dfn{rewrite rule} system
5578 that you can use to define your own algebraic manipulations.
5580 Suppose we want to simplify this trigonometric formula:
5584 1: 1 / cos(x) - sin(x) tan(x)
5587 ' 1/cos(x) - sin(x) tan(x) RET s 1
5592 If we were simplifying this by hand, we'd probably replace the
5593 @samp{tan} with a @samp{sin/cos} first, then combine over a common
5594 denominator. There is no Calc command to do the former; the @kbd{a n}
5595 algebra command will do the latter but we'll do both with rewrite
5596 rules just for practice.
5598 Rewrite rules are written with the @samp{:=} symbol.
5602 1: 1 / cos(x) - sin(x)^2 / cos(x)
5605 a r tan(a) := sin(a)/cos(a) RET
5610 (The ``assignment operator'' @samp{:=} has several uses in Calc. All
5611 by itself the formula @samp{tan(a) := sin(a)/cos(a)} doesn't do anything,
5612 but when it is given to the @kbd{a r} command, that command interprets
5613 it as a rewrite rule.)
5615 The lefthand side, @samp{tan(a)}, is called the @dfn{pattern} of the
5616 rewrite rule. Calc searches the formula on the stack for parts that
5617 match the pattern. Variables in a rewrite pattern are called
5618 @dfn{meta-variables}, and when matching the pattern each meta-variable
5619 can match any sub-formula. Here, the meta-variable @samp{a} matched
5620 the actual variable @samp{x}.
5622 When the pattern part of a rewrite rule matches a part of the formula,
5623 that part is replaced by the righthand side with all the meta-variables
5624 substituted with the things they matched. So the result is
5625 @samp{sin(x) / cos(x)}. Calc's normal algebraic simplifications then
5626 mix this in with the rest of the original formula.
5628 To merge over a common denominator, we can use another simple rule:
5632 1: (1 - sin(x)^2) / cos(x)
5635 a r a/x + b/x := (a+b)/x RET
5639 This rule points out several interesting features of rewrite patterns.
5640 First, if a meta-variable appears several times in a pattern, it must
5641 match the same thing everywhere. This rule detects common denominators
5642 because the same meta-variable @samp{x} is used in both of the
5645 Second, meta-variable names are independent from variables in the
5646 target formula. Notice that the meta-variable @samp{x} here matches
5647 the subformula @samp{cos(x)}; Calc never confuses the two meanings of
5650 And third, rewrite patterns know a little bit about the algebraic
5651 properties of formulas. The pattern called for a sum of two quotients;
5652 Calc was able to match a difference of two quotients by matching
5653 @samp{a = 1}, @samp{b = -sin(x)^2}, and @samp{x = cos(x)}.
5655 @c [fix-ref Algebraic Properties of Rewrite Rules]
5656 We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
5657 the rule. It would have worked just the same in all cases. (If we
5658 really wanted the rule to apply only to @samp{+} or only to @samp{-},
5659 we could have used the @code{plain} symbol. @xref{Algebraic Properties
5660 of Rewrite Rules}, for some examples of this.)
5662 One more rewrite will complete the job. We want to use the identity
5663 @samp{sin(x)^2 + cos(x)^2 = 1}, but of course we must first rearrange
5664 the identity in a way that matches our formula. The obvious rule
5665 would be @samp{@w{1 - sin(x)^2} := cos(x)^2}, but a little thought shows
5666 that the rule @samp{sin(x)^2 := 1 - cos(x)^2} will also work. The
5667 latter rule has a more general pattern so it will work in many other
5672 1: (1 + cos(x)^2 - 1) / cos(x) 1: cos(x)
5675 a r sin(x)^2 := 1 - cos(x)^2 RET a s
5679 You may ask, what's the point of using the most general rule if you
5680 have to type it in every time anyway? The answer is that Calc allows
5681 you to store a rewrite rule in a variable, then give the variable
5682 name in the @kbd{a r} command. In fact, this is the preferred way to
5683 use rewrites. For one, if you need a rule once you'll most likely
5684 need it again later. Also, if the rule doesn't work quite right you
5685 can simply Undo, edit the variable, and run the rule again without
5686 having to retype it.
5690 ' tan(x) := sin(x)/cos(x) RET s t tsc RET
5691 ' a/x + b/x := (a+b)/x RET s t merge RET
5692 ' sin(x)^2 := 1 - cos(x)^2 RET s t sinsqr RET
5694 1: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
5697 r 1 a r tsc RET a r merge RET a r sinsqr RET a s
5701 To edit a variable, type @kbd{s e} and the variable name, use regular
5702 Emacs editing commands as necessary, then type @kbd{M-# M-#} or
5703 @kbd{C-c C-c} to store the edited value back into the variable.
5704 You can also use @w{@kbd{s e}} to create a new variable if you wish.
5706 Notice that the first time you use each rule, Calc puts up a ``compiling''
5707 message briefly. The pattern matcher converts rules into a special
5708 optimized pattern-matching language rather than using them directly.
5709 This allows @kbd{a r} to apply even rather complicated rules very
5710 efficiently. If the rule is stored in a variable, Calc compiles it
5711 only once and stores the compiled form along with the variable. That's
5712 another good reason to store your rules in variables rather than
5713 entering them on the fly.
5715 (@bullet{}) @strong{Exercise 1.} Type @kbd{m s} to get symbolic
5716 mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
5717 Using a rewrite rule, simplify this formula by multiplying both
5718 sides by the conjugate @w{@samp{1 - sqrt(2)}}. The result will have
5719 to be expanded by the distributive law; do this with another
5720 rewrite. @xref{Rewrites Answer 1, 1}. (@bullet{})
5722 The @kbd{a r} command can also accept a vector of rewrite rules, or
5723 a variable containing a vector of rules.
5727 1: [tsc, merge, sinsqr] 1: [tan(x) := sin(x) / cos(x), ... ]
5730 ' [tsc,merge,sinsqr] RET =
5737 1: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
5740 s t trig RET r 1 a r trig RET a s
5744 @c [fix-ref Nested Formulas with Rewrite Rules]
5745 Calc tries all the rules you give against all parts of the formula,
5746 repeating until no further change is possible. (The exact order in
5747 which things are tried is rather complex, but for simple rules like
5748 the ones we've used here the order doesn't really matter.
5749 @xref{Nested Formulas with Rewrite Rules}.)
5751 Calc actually repeats only up to 100 times, just in case your rule set
5752 has gotten into an infinite loop. You can give a numeric prefix argument
5753 to @kbd{a r} to specify any limit. In particular, @kbd{M-1 a r} does
5754 only one rewrite at a time.
5758 1: 1 / cos(x) - sin(x)^2 / cos(x) 1: (1 - sin(x)^2) / cos(x)
5761 r 1 M-1 a r trig RET M-1 a r trig RET
5765 You can type @kbd{M-0 a r} if you want no limit at all on the number
5766 of rewrites that occur.
5768 Rewrite rules can also be @dfn{conditional}. Simply follow the rule
5769 with a @samp{::} symbol and the desired condition. For example,
5773 1: exp(2 pi i) + exp(3 pi i) + exp(4 pi i)
5776 ' exp(2 pi i) + exp(3 pi i) + exp(4 pi i) RET
5783 1: 1 + exp(3 pi i) + 1
5786 a r exp(k pi i) := 1 :: k % 2 = 0 RET
5791 (Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
5792 which will be zero only when @samp{k} is an even integer.)
5794 An interesting point is that the variables @samp{pi} and @samp{i}
5795 were matched literally rather than acting as meta-variables.
5796 This is because they are special-constant variables. The special
5797 constants @samp{e}, @samp{phi}, and so on also match literally.
5798 A common error with rewrite
5799 rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
5800 to match any @samp{f} with five arguments but in fact matching
5801 only when the fifth argument is literally @samp{e}!@refill
5803 @cindex Fibonacci numbers
5806 Rewrite rules provide an interesting way to define your own functions.
5807 Suppose we want to define @samp{fib(n)} to produce the @var{n}th
5808 Fibonacci number. The first two Fibonacci numbers are each 1;
5809 later numbers are formed by summing the two preceding numbers in
5810 the sequence. This is easy to express in a set of three rules:
5814 ' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] RET s t fib
5819 ' fib(7) RET a r fib RET
5823 One thing that is guaranteed about the order that rewrites are tried
5824 is that, for any given subformula, earlier rules in the rule set will
5825 be tried for that subformula before later ones. So even though the
5826 first and third rules both match @samp{fib(1)}, we know the first will
5827 be used preferentially.
5829 This rule set has one dangerous bug: Suppose we apply it to the
5830 formula @samp{fib(x)}? (Don't actually try this.) The third rule
5831 will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
5832 Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
5833 fib(x-4)}, and so on, expanding forever. What we really want is to apply
5834 the third rule only when @samp{n} is an integer greater than two. Type
5835 @w{@kbd{s e fib RET}}, then edit the third rule to:
5838 fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
5846 1: fib(6) + fib(x) + fib(0) 1: 8 + fib(x) + fib(0)
5849 ' fib(6)+fib(x)+fib(0) RET a r fib RET
5854 We've created a new function, @code{fib}, and a new command,
5855 @w{@kbd{a r fib RET}}, which means ``evaluate all @code{fib} calls in
5856 this formula.'' To make things easier still, we can tell Calc to
5857 apply these rules automatically by storing them in the special
5858 variable @code{EvalRules}.
5862 1: [fib(1) := ...] . 1: [8, 13]
5865 s r fib RET s t EvalRules RET ' [fib(6), fib(7)] RET
5869 It turns out that this rule set has the problem that it does far
5870 more work than it needs to when @samp{n} is large. Consider the
5871 first few steps of the computation of @samp{fib(6)}:
5877 fib(4) + fib(3) + fib(3) + fib(2) =
5878 fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
5883 Note that @samp{fib(3)} appears three times here. Unless Calc's
5884 algebraic simplifier notices the multiple @samp{fib(3)}s and combines
5885 them (and, as it happens, it doesn't), this rule set does lots of
5886 needless recomputation. To cure the problem, type @code{s e EvalRules}
5887 to edit the rules (or just @kbd{s E}, a shorthand command for editing
5888 @code{EvalRules}) and add another condition:
5891 fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
5895 If a @samp{:: remember} condition appears anywhere in a rule, then if
5896 that rule succeeds Calc will add another rule that describes that match
5897 to the front of the rule set. (Remembering works in any rule set, but
5898 for technical reasons it is most effective in @code{EvalRules}.) For
5899 example, if the rule rewrites @samp{fib(7)} to something that evaluates
5900 to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
5902 Type @kbd{' fib(8) RET} to compute the eighth Fibonacci number, then
5903 type @kbd{s E} again to see what has happened to the rule set.
5905 With the @code{remember} feature, our rule set can now compute
5906 @samp{fib(@var{n})} in just @var{n} steps. In the process it builds
5907 up a table of all Fibonacci numbers up to @var{n}. After we have
5908 computed the result for a particular @var{n}, we can get it back
5909 (and the results for all smaller @var{n}) later in just one step.
5911 All Calc operations will run somewhat slower whenever @code{EvalRules}
5912 contains any rules. You should type @kbd{s u EvalRules RET} now to
5913 un-store the variable.
5915 (@bullet{}) @strong{Exercise 2.} Sometimes it is possible to reformulate
5916 a problem to reduce the amount of recursion necessary to solve it.
5917 Create a rule that, in about @var{n} simple steps and without recourse
5918 to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
5919 @samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
5920 @var{n}th and @var{n+1}st Fibonacci numbers, respectively. This rule is
5921 rather clunky to use, so add a couple more rules to make the ``user
5922 interface'' the same as for our first version: enter @samp{fib(@var{n})},
5923 get back a plain number. @xref{Rewrites Answer 2, 2}. (@bullet{})
5925 There are many more things that rewrites can do. For example, there
5926 are @samp{&&&} and @samp{|||} pattern operators that create ``and''
5927 and ``or'' combinations of rules. As one really simple example, we
5928 could combine our first two Fibonacci rules thusly:
5931 [fib(1 ||| 2) := 1, fib(n) := ... ]
5935 That means ``@code{fib} of something matching either 1 or 2 rewrites
5938 You can also make meta-variables optional by enclosing them in @code{opt}.
5939 For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
5940 @samp{2 + x} or @samp{3 x} or @samp{x}. The pattern @samp{opt(a) + opt(b) x}
5941 matches all of these forms, filling in a default of zero for @samp{a}
5942 and one for @samp{b}.
5944 (@bullet{}) @strong{Exercise 3.} Your friend Joe had @samp{2 + 3 x}
5945 on the stack and tried to use the rule
5946 @samp{opt(a) + opt(b) x := f(a, b, x)}. What happened?
5947 @xref{Rewrites Answer 3, 3}. (@bullet{})
5949 (@bullet{}) @strong{Exercise 4.} Starting with a positive integer @cite{a},
5950 divide @cite{a} by two if it is even, otherwise compute @cite{3 a + 1}.
5951 Now repeat this step over and over. A famous unproved conjecture
5952 is that for any starting @cite{a}, the sequence always eventually
5953 reaches 1. Given the formula @samp{seq(@var{a}, 0)}, write a set of
5954 rules that convert this into @samp{seq(1, @var{n})} where @var{n}
5955 is the number of steps it took the sequence to reach the value 1.
5956 Now enhance the rules to accept @samp{seq(@var{a})} as a starting
5957 configuration, and to stop with just the number @var{n} by itself.
5958 Now make the result be a vector of values in the sequence, from @var{a}
5959 to 1. (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
5960 and @var{y}.) For example, rewriting @samp{seq(6)} should yield the
5961 vector @cite{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
5962 @xref{Rewrites Answer 4, 4}. (@bullet{})
5964 (@bullet{}) @strong{Exercise 5.} Define, using rewrite rules, a function
5965 @samp{nterms(@var{x})} that returns the number of terms in the sum
5966 @var{x}, or 1 if @var{x} is not a sum. (A @dfn{sum} for our purposes
5967 is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
5968 so that @cite{2 - 3 (x + y) + x y} is a sum of three terms.)
5969 @xref{Rewrites Answer 5, 5}. (@bullet{})
5971 (@bullet{}) @strong{Exercise 6.} Calc considers the form @cite{0^0}
5972 to be ``indeterminate,'' and leaves it unevaluated (assuming infinite
5973 mode is not enabled). Some people prefer to define @cite{0^0 = 1},
5974 so that the identity @cite{x^0 = 1} can safely be used for all @cite{x}.
5975 Find a way to make Calc follow this convention. What happens if you
5976 now type @kbd{m i} to turn on infinite mode?
5977 @xref{Rewrites Answer 6, 6}. (@bullet{})
5979 (@bullet{}) @strong{Exercise 7.} A Taylor series for a function is an
5980 infinite series that exactly equals the value of that function at
5981 values of @cite{x} near zero.
5985 cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
5989 \turnoffactive \let\rm\goodrm
5991 $$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
5995 The @kbd{a t} command produces a @dfn{truncated Taylor series} which
5996 is obtained by dropping all the terms higher than, say, @cite{x^2}.
5997 Calc represents the truncated Taylor series as a polynomial in @cite{x}.
5998 Mathematicians often write a truncated series using a ``big-O'' notation
5999 that records what was the lowest term that was truncated.
6003 cos(x) = 1 - x^2 / 2! + O(x^3)
6007 \turnoffactive \let\rm\goodrm
6009 $$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
6014 The meaning of @cite{O(x^3)} is ``a quantity which is negligibly small
6015 if @cite{x^3} is considered negligibly small as @cite{x} goes to zero.''
6017 The exercise is to create rewrite rules that simplify sums and products of
6018 power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
6019 For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
6020 on the stack, we want to be able to type @kbd{*} and get the result
6021 @samp{x - 2:3 x^3 + O(x^4)}. Don't worry if the terms of the sum are
6022 rearranged or if @kbd{a s} needs to be typed after rewriting. (This one
6023 is rather tricky; the solution at the end of this chapter uses 6 rewrite
6024 rules. Hint: The @samp{constant(x)} condition tests whether @samp{x} is
6025 a number.) @xref{Rewrites Answer 7, 7}. (@bullet{})
6027 @c [fix-ref Rewrite Rules]
6028 @xref{Rewrite Rules}, for the whole story on rewrite rules.
6030 @node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
6031 @section Programming Tutorial
6034 The Calculator is written entirely in Emacs Lisp, a highly extensible
6035 language. If you know Lisp, you can program the Calculator to do
6036 anything you like. Rewrite rules also work as a powerful programming
6037 system. But Lisp and rewrite rules take a while to master, and often
6038 all you want to do is define a new function or repeat a command a few
6039 times. Calc has features that allow you to do these things easily.
6041 (Note that the programming commands relating to user-defined keys
6042 are not yet supported under Lucid Emacs 19.)
6044 One very limited form of programming is defining your own functions.
6045 Calc's @kbd{Z F} command allows you to define a function name and
6046 key sequence to correspond to any formula. Programming commands use
6047 the shift-@kbd{Z} prefix; the user commands they create use the lower
6048 case @kbd{z} prefix.
6052 1: 1 + x + x^2 / 2 + x^3 / 6 1: 1 + x + x^2 / 2 + x^3 / 6
6055 ' 1 + x + x^2/2! + x^3/3! RET Z F e myexp RET RET RET y
6059 This polynomial is a Taylor series approximation to @samp{exp(x)}.
6060 The @kbd{Z F} command asks a number of questions. The above answers
6061 say that the key sequence for our function should be @kbd{z e}; the
6062 @kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
6063 function in algebraic formulas should also be @code{myexp}; the
6064 default argument list @samp{(x)} is acceptable; and finally @kbd{y}
6065 answers the question ``leave it in symbolic form for non-constant
6070 1: 1.3495 2: 1.3495 3: 1.3495
6071 . 1: 1.34986 2: 1.34986
6075 .3 z e .3 E ' a+1 RET z e
6080 First we call our new @code{exp} approximation with 0.3 as an
6081 argument, and compare it with the true @code{exp} function. Then
6082 we note that, as requested, if we try to give @kbd{z e} an
6083 argument that isn't a plain number, it leaves the @code{myexp}
6084 function call in symbolic form. If we had answered @kbd{n} to the
6085 final question, @samp{myexp(a + 1)} would have evaluated by plugging
6086 in @samp{a + 1} for @samp{x} in the defining formula.
6088 @cindex Sine integral Si(x)
6091 (@bullet{}) @strong{Exercise 1.} The ``sine integral'' function
6093 @cite{Si(x)} is defined as the integral of @samp{sin(t)/t} for
6094 @cite{t = 0} to @cite{x} in radians. (It was invented because this
6095 integral has no solution in terms of basic functions; if you give it
6096 to Calc's @kbd{a i} command, it will ponder it for a long time and then
6097 give up.) We can use the numerical integration command, however,
6098 which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
6099 with any integrand @samp{f(t)}. Define a @kbd{z s} command and
6100 @code{Si} function that implement this. You will need to edit the
6101 default argument list a bit. As a test, @samp{Si(1)} should return
6102 0.946083. (Hint: @code{ninteg} will run a lot faster if you reduce
6103 the precision to, say, six digits beforehand.)
6104 @xref{Programming Answer 1, 1}. (@bullet{})
6106 The simplest way to do real ``programming'' of Emacs is to define a
6107 @dfn{keyboard macro}. A keyboard macro is simply a sequence of
6108 keystrokes which Emacs has stored away and can play back on demand.
6109 For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
6110 you may wish to program a keyboard macro to type this for you.
6114 1: y = sqrt(x) 1: x = y^2
6117 ' y=sqrt(x) RET C-x ( H a S x RET C-x )
6119 1: y = cos(x) 1: x = s1 arccos(y) + 2 pi n1
6127 When you type @kbd{C-x (}, Emacs begins recording. But it is also
6128 still ready to execute your keystrokes, so you're really ``training''
6129 Emacs by walking it through the procedure once. When you type
6130 @w{@kbd{C-x )}}, the macro is recorded. You can now type @kbd{X} to
6131 re-execute the same keystrokes.
6133 You can give a name to your macro by typing @kbd{Z K}.
6137 1: . 1: y = x^4 1: x = s2 sqrt(s1 sqrt(y))
6140 Z K x RET ' y=x^4 RET z x
6145 Notice that we use shift-@kbd{Z} to define the command, and lower-case
6146 @kbd{z} to call it up.
6148 Keyboard macros can call other macros.
6152 1: abs(x) 1: x = s1 y 1: 2 / x 1: x = 2 / y
6155 ' abs(x) RET C-x ( ' y RET a = z x C-x ) ' 2/x RET X
6159 (@bullet{}) @strong{Exercise 2.} Define a keyboard macro to negate
6160 the item in level 3 of the stack, without disturbing the rest of
6161 the stack. @xref{Programming Answer 2, 2}. (@bullet{})
6163 (@bullet{}) @strong{Exercise 3.} Define keyboard macros to compute
6164 the following functions:
6168 Compute @c{$\displaystyle{\sin x \over x}$}
6169 @cite{sin(x) / x}, where @cite{x} is the number on the
6173 Compute the base-@cite{b} logarithm, just like the @kbd{B} key except
6174 the arguments are taken in the opposite order.
6177 Produce a vector of integers from 1 to the integer on the top of
6181 @xref{Programming Answer 3, 3}. (@bullet{})
6183 (@bullet{}) @strong{Exercise 4.} Define a keyboard macro to compute
6184 the average (mean) value of a list of numbers.
6185 @xref{Programming Answer 4, 4}. (@bullet{})
6187 In many programs, some of the steps must execute several times.
6188 Calc has @dfn{looping} commands that allow this. Loops are useful
6189 inside keyboard macros, but actually work at any time.
6193 1: x^6 2: x^6 1: 360 x^2
6197 ' x^6 RET 4 Z < a d x RET Z >
6202 Here we have computed the fourth derivative of @cite{x^6} by
6203 enclosing a derivative command in a ``repeat loop'' structure.
6204 This structure pops a repeat count from the stack, then
6205 executes the body of the loop that many times.
6207 If you make a mistake while entering the body of the loop,
6208 type @w{@kbd{Z C-g}} to cancel the loop command.
6210 @cindex Fibonacci numbers
6211 Here's another example:
6220 1 RET RET 20 Z < TAB C-j + Z >
6225 The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
6226 numbers, respectively. (To see what's going on, try a few repetitions
6227 of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
6228 key if you have one, makes a copy of the number in level 2.)
6230 @cindex Golden ratio
6231 @cindex Phi, golden ratio
6232 A fascinating property of the Fibonacci numbers is that the @cite{n}th
6233 Fibonacci number can be found directly by computing @c{$\phi^n / \sqrt{5}$}
6234 @cite{phi^n / sqrt(5)}
6235 and then rounding to the nearest integer, where @c{$\phi$ (``phi'')}
6237 ``golden ratio,'' is @c{$(1 + \sqrt{5}) / 2$}
6238 @cite{(1 + sqrt(5)) / 2}. (For convenience, this constant is available
6239 from the @code{phi} variable, or the @kbd{I H P} command.)
6243 1: 1.61803 1: 24476.0000409 1: 10945.9999817 1: 10946
6250 @cindex Continued fractions
6251 (@bullet{}) @strong{Exercise 5.} The @dfn{continued fraction}
6252 representation of @c{$\phi$}
6253 @cite{phi} is @c{$1 + 1/(1 + 1/(1 + 1/( \ldots )))$}
6254 @cite{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
6255 We can compute an approximate value by carrying this however far
6256 and then replacing the innermost @c{$1/( \ldots )$}
6257 @cite{1/( ...@: )} by 1. Approximate
6259 @cite{phi} using a twenty-term continued fraction.
6260 @xref{Programming Answer 5, 5}. (@bullet{})
6262 (@bullet{}) @strong{Exercise 6.} Linear recurrences like the one for
6263 Fibonacci numbers can be expressed in terms of matrices. Given a
6264 vector @w{@cite{[a, b]}} determine a matrix which, when multiplied by this
6265 vector, produces the vector @cite{[b, c]}, where @cite{a}, @cite{b} and
6266 @cite{c} are three successive Fibonacci numbers. Now write a program
6267 that, given an integer @cite{n}, computes the @cite{n}th Fibonacci number
6268 using matrix arithmetic. @xref{Programming Answer 6, 6}. (@bullet{})
6270 @cindex Harmonic numbers
6271 A more sophisticated kind of loop is the @dfn{for} loop. Suppose
6272 we wish to compute the 20th ``harmonic'' number, which is equal to
6273 the sum of the reciprocals of the integers from 1 to 20.
6282 0 RET 1 RET 20 Z ( & + 1 Z )
6287 The ``for'' loop pops two numbers, the lower and upper limits, then
6288 repeats the body of the loop as an internal counter increases from
6289 the lower limit to the upper one. Just before executing the loop
6290 body, it pushes the current loop counter. When the loop body
6291 finishes, it pops the ``step,'' i.e., the amount by which to
6292 increment the loop counter. As you can see, our loop always
6295 This harmonic number function uses the stack to hold the running
6296 total as well as for the various loop housekeeping functions. If
6297 you find this disorienting, you can sum in a variable instead:
6301 1: 0 2: 1 . 1: 3.597739
6305 0 t 7 1 RET 20 Z ( & s + 7 1 Z ) r 7
6310 The @kbd{s +} command adds the top-of-stack into the value in a
6311 variable (and removes that value from the stack).
6313 It's worth noting that many jobs that call for a ``for'' loop can
6314 also be done more easily by Calc's high-level operations. Two
6315 other ways to compute harmonic numbers are to use vector mapping
6316 and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
6317 or to use the summation command @kbd{a +}. Both of these are
6318 probably easier than using loops. However, there are some
6319 situations where loops really are the way to go:
6321 (@bullet{}) @strong{Exercise 7.} Use a ``for'' loop to find the first
6322 harmonic number which is greater than 4.0.
6323 @xref{Programming Answer 7, 7}. (@bullet{})
6325 Of course, if we're going to be using variables in our programs,
6326 we have to worry about the programs clobbering values that the
6327 caller was keeping in those same variables. This is easy to
6332 . 1: 0.6667 1: 0.6667 3: 0.6667
6337 Z ` p 4 RET 2 RET 3 / s 7 s s a RET Z ' r 7 s r a RET
6342 When we type @kbd{Z `} (that's a back-quote character), Calc saves
6343 its mode settings and the contents of the ten ``quick variables''
6344 for later reference. When we type @kbd{Z '} (that's an apostrophe
6345 now), Calc restores those saved values. Thus the @kbd{p 4} and
6346 @kbd{s 7} commands have no effect outside this sequence. Wrapping
6347 this around the body of a keyboard macro ensures that it doesn't
6348 interfere with what the user of the macro was doing. Notice that
6349 the contents of the stack, and the values of named variables,
6350 survive past the @kbd{Z '} command.
6352 @cindex Bernoulli numbers, approximate
6353 The @dfn{Bernoulli numbers} are a sequence with the interesting
6354 property that all of the odd Bernoulli numbers are zero, and the
6355 even ones, while difficult to compute, can be roughly approximated
6356 by the formula @c{$\displaystyle{2 n! \over (2 \pi)^n}$}
6357 @cite{2 n!@: / (2 pi)^n}. Let's write a keyboard
6358 macro to compute (approximate) Bernoulli numbers. (Calc has a
6359 command, @kbd{k b}, to compute exact Bernoulli numbers, but
6360 this command is very slow for large @cite{n} since the higher
6361 Bernoulli numbers are very large fractions.)
6368 10 C-x ( RET 2 % Z [ DEL 0 Z : ' 2 $! / (2 pi)^$ RET = Z ] C-x )
6373 You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
6374 @kbd{Z ]} as ``end-if.'' There is no need for an explicit ``if''
6375 command. For the purposes of @w{@kbd{Z [}}, the condition is ``true''
6376 if the value it pops from the stack is a nonzero number, or ``false''
6377 if it pops zero or something that is not a number (like a formula).
6378 Here we take our integer argument modulo 2; this will be nonzero
6379 if we're asking for an odd Bernoulli number.
6381 The actual tenth Bernoulli number is @cite{5/66}.
6385 3: 0.0756823 1: 0 1: 0.25305 1: 0 1: 1.16659
6390 10 k b RET c f M-0 DEL 11 X DEL 12 X DEL 13 X DEL 14 X
6394 Just to exercise loops a bit more, let's compute a table of even
6399 3: [] 1: [0.10132, 0.03079, 0.02340, 0.033197, ...]
6404 [ ] 2 RET 30 Z ( X | 2 Z )
6409 The vertical-bar @kbd{|} is the vector-concatenation command. When
6410 we execute it, the list we are building will be in stack level 2
6411 (initially this is an empty list), and the next Bernoulli number
6412 will be in level 1. The effect is to append the Bernoulli number
6413 onto the end of the list. (To create a table of exact fractional
6414 Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
6415 sequence of keystrokes.)
6417 With loops and conditionals, you can program essentially anything
6418 in Calc. One other command that makes looping easier is @kbd{Z /},
6419 which takes a condition from the stack and breaks out of the enclosing
6420 loop if the condition is true (non-zero). You can use this to make
6421 ``while'' and ``until'' style loops.
6423 If you make a mistake when entering a keyboard macro, you can edit
6424 it using @kbd{Z E}. First, you must attach it to a key with @kbd{Z K}.
6425 One technique is to enter a throwaway dummy definition for the macro,
6426 then enter the real one in the edit command.
6430 1: 3 1: 3 Keyboard Macro Editor.
6431 . . Original keys: 1 RET 2 +
6437 C-x ( 1 RET 2 + C-x ) Z K h RET Z E h
6442 This shows the screen display assuming you have the @file{macedit}
6443 keyboard macro editing package installed, which is usually the case
6444 since a copy of @file{macedit} comes bundled with Calc.
6446 A keyboard macro is stored as a pure keystroke sequence. The
6447 @file{macedit} package (invoked by @kbd{Z E}) scans along the
6448 macro and tries to decode it back into human-readable steps.
6449 If a key or keys are simply shorthand for some command with a
6450 @kbd{M-x} name, that name is shown. Anything that doesn't correspond
6451 to a @kbd{M-x} command is written as a @samp{type} command.
6453 Let's edit in a new definition, for computing harmonic numbers.
6454 First, erase the three lines of the old definition. Then, type
6455 in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
6456 to copy it from this page of the Info file; you can skip typing
6457 the comments that begin with @samp{#}).
6460 calc-kbd-push # Save local values (Z `)
6461 type "0" # Push a zero
6462 calc-store-into # Store it in variable 1
6464 type "1" # Initial value for loop
6465 calc-roll-down # This is the TAB key; swap initial & final
6466 calc-kbd-for # Begin "for" loop...
6467 calc-inv # Take reciprocal
6468 calc-store-plus # Add to accumulator
6470 type "1" # Loop step is 1
6471 calc-kbd-end-for # End "for" loop
6472 calc-recall # Now recall final accumulated value
6474 calc-kbd-pop # Restore values (Z ')
6478 Press @kbd{M-# M-#} to finish editing and return to the Calculator.
6489 If you don't know how to write a particular command in @file{macedit}
6490 format, you can always write it as keystrokes in a @code{type} command.
6491 There is also a @code{keys} command which interprets the rest of the
6492 line as standard Emacs keystroke names. In fact, @file{macedit} defines
6493 a handy @code{read-kbd-macro} command which reads the current region
6494 of the current buffer as a sequence of keystroke names, and defines that
6495 sequence on the @kbd{X} (and @kbd{C-x e}) key. Because this is so
6496 useful, Calc puts this command on the @kbd{M-# m} key. Try reading in
6497 this macro in the following form: Press @kbd{C-@@} (or @kbd{C-SPC}) at
6498 one end of the text below, then type @kbd{M-# m} at the other.
6510 (@bullet{}) @strong{Exercise 8.} A general algorithm for solving
6511 equations numerically is @dfn{Newton's Method}. Given the equation
6512 @cite{f(x) = 0} for any function @cite{f}, and an initial guess
6513 @cite{x_0} which is reasonably close to the desired solution, apply
6514 this formula over and over:
6518 new_x = x - f(x)/f'(x)
6523 $$ x_{\goodrm new} = x - {f(x) \over f'(x)} $$
6528 where @cite{f'(x)} is the derivative of @cite{f}. The @cite{x}
6529 values will quickly converge to a solution, i.e., eventually
6531 @cite{new_x} and @cite{x} will be equal to within the limits
6532 of the current precision. Write a program which takes a formula
6533 involving the variable @cite{x}, and an initial guess @cite{x_0},
6534 on the stack, and produces a value of @cite{x} for which the formula
6535 is zero. Use it to find a solution of @c{$\sin(\cos x) = 0.5$}
6536 @cite{sin(cos(x)) = 0.5}
6537 near @cite{x = 4.5}. (Use angles measured in radians.) Note that
6538 the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
6539 method when it is able. @xref{Programming Answer 8, 8}. (@bullet{})
6541 @cindex Digamma function
6542 @cindex Gamma constant, Euler's
6543 @cindex Euler's gamma constant
6544 (@bullet{}) @strong{Exercise 9.} The @dfn{digamma} function @c{$\psi(z)$ (``psi'')}
6546 is defined as the derivative of @c{$\ln \Gamma(z)$}
6547 @cite{ln(gamma(z))}. For large
6548 values of @cite{z}, it can be approximated by the infinite sum
6552 psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
6558 $$ \psi(z) \approx \ln z - {1\over2z} -
6559 \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
6566 @cite{sum} represents the sum over @cite{n} from 1 to infinity
6567 (or to some limit high enough to give the desired accuracy), and
6568 the @code{bern} function produces (exact) Bernoulli numbers.
6569 While this sum is not guaranteed to converge, in practice it is safe.
6570 An interesting mathematical constant is Euler's gamma, which is equal
6571 to about 0.5772. One way to compute it is by the formula,
6572 @c{$\gamma = -\psi(1)$}
6573 @cite{gamma = -psi(1)}. Unfortunately, 1 isn't a large enough argument
6574 for the above formula to work (5 is a much safer value for @cite{z}).
6575 Fortunately, we can compute @c{$\psi(1)$}
6576 @cite{psi(1)} from @c{$\psi(5)$}
6578 the recurrence @c{$\psi(z+1) = \psi(z) + {1 \over z}$}
6579 @cite{psi(z+1) = psi(z) + 1/z}. Your task: Develop
6580 a program to compute @c{$\psi(z)$}
6581 @cite{psi(z)}; it should ``pump up'' @cite{z}
6582 if necessary to be greater than 5, then use the above summation
6583 formula. Use looping commands to compute the sum. Use your function
6584 to compute @c{$\gamma$}
6585 @cite{gamma} to twelve decimal places. (Calc has a built-in command
6586 for Euler's constant, @kbd{I P}, which you can use to check your answer.)
6587 @xref{Programming Answer 9, 9}. (@bullet{})
6589 @cindex Polynomial, list of coefficients
6590 (@bullet{}) @strong{Exercise 10.} Given a polynomial in @cite{x} and
6591 a number @cite{m} on the stack, where the polynomial is of degree
6592 @cite{m} or less (i.e., does not have any terms higher than @cite{x^m}),
6593 write a program to convert the polynomial into a list-of-coefficients
6594 notation. For example, @cite{5 x^4 + (x + 1)^2} with @cite{m = 6}
6595 should produce the list @cite{[1, 2, 1, 0, 5, 0, 0]}. Also develop
6596 a way to convert from this form back to the standard algebraic form.
6597 @xref{Programming Answer 10, 10}. (@bullet{})
6600 (@bullet{}) @strong{Exercise 11.} The @dfn{Stirling numbers of the
6601 first kind} are defined by the recurrences,
6605 s(n,n) = 1 for n >= 0,
6606 s(n,0) = 0 for n > 0,
6607 s(n+1,m) = s(n,m-1) - n s(n,m) for n >= m >= 1.
6613 $$ \eqalign{ s(n,n) &= 1 \qquad \hbox{for } n \ge 0, \cr
6614 s(n,0) &= 0 \qquad \hbox{for } n > 0, \cr
6615 s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
6616 \hbox{for } n \ge m \ge 1.}
6620 (These numbers are also sometimes written $\displaystyle{n \brack m}$.)
6623 This can be implemented using a @dfn{recursive} program in Calc; the
6624 program must invoke itself in order to calculate the two righthand
6625 terms in the general formula. Since it always invokes itself with
6626 ``simpler'' arguments, it's easy to see that it must eventually finish
6627 the computation. Recursion is a little difficult with Emacs keyboard
6628 macros since the macro is executed before its definition is complete.
6629 So here's the recommended strategy: Create a ``dummy macro'' and assign
6630 it to a key with, e.g., @kbd{Z K s}. Now enter the true definition,
6631 using the @kbd{z s} command to call itself recursively, then assign it
6632 to the same key with @kbd{Z K s}. Now the @kbd{z s} command will run
6633 the complete recursive program. (Another way is to use @w{@kbd{Z E}}
6634 or @kbd{M-# m} (@code{read-kbd-macro}) to read the whole macro at once,
6635 thus avoiding the ``training'' phase.) The task: Write a program
6636 that computes Stirling numbers of the first kind, given @cite{n} and
6637 @cite{m} on the stack. Test it with @emph{small} inputs like
6638 @cite{s(4,2)}. (There is a built-in command for Stirling numbers,
6639 @kbd{k s}, which you can use to check your answers.)
6640 @xref{Programming Answer 11, 11}. (@bullet{})
6642 The programming commands we've seen in this part of the tutorial
6643 are low-level, general-purpose operations. Often you will find
6644 that a higher-level function, such as vector mapping or rewrite
6645 rules, will do the job much more easily than a detailed, step-by-step
6648 (@bullet{}) @strong{Exercise 12.} Write another program for
6649 computing Stirling numbers of the first kind, this time using
6650 rewrite rules. Once again, @cite{n} and @cite{m} should be taken
6651 from the stack. @xref{Programming Answer 12, 12}. (@bullet{})
6656 This ends the tutorial section of the Calc manual. Now you know enough
6657 about Calc to use it effectively for many kinds of calculations. But
6658 Calc has many features that were not even touched upon in this tutorial.
6660 The rest of this manual tells the whole story.
6662 @c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
6665 @node Answers to Exercises, , Programming Tutorial, Tutorial
6666 @section Answers to Exercises
6669 This section includes answers to all the exercises in the Calc tutorial.
6672 * RPN Answer 1:: 1 RET 2 RET 3 RET 4 + * -
6673 * RPN Answer 2:: 2*4 + 7*9.5 + 5/4
6674 * RPN Answer 3:: Operating on levels 2 and 3
6675 * RPN Answer 4:: Joe's complex problems
6676 * Algebraic Answer 1:: Simulating Q command
6677 * Algebraic Answer 2:: Joe's algebraic woes
6678 * Algebraic Answer 3:: 1 / 0
6679 * Modes Answer 1:: 3#0.1 = 3#0.0222222?
6680 * Modes Answer 2:: 16#f.e8fe15
6681 * Modes Answer 3:: Joe's rounding bug
6682 * Modes Answer 4:: Why floating point?
6683 * Arithmetic Answer 1:: Why the \ command?
6684 * Arithmetic Answer 2:: Tripping up the B command
6685 * Vector Answer 1:: Normalizing a vector
6686 * Vector Answer 2:: Average position
6687 * Matrix Answer 1:: Row and column sums
6688 * Matrix Answer 2:: Symbolic system of equations
6689 * Matrix Answer 3:: Over-determined system
6690 * List Answer 1:: Powers of two
6691 * List Answer 2:: Least-squares fit with matrices
6692 * List Answer 3:: Geometric mean
6693 * List Answer 4:: Divisor function
6694 * List Answer 5:: Duplicate factors
6695 * List Answer 6:: Triangular list
6696 * List Answer 7:: Another triangular list
6697 * List Answer 8:: Maximum of Bessel function
6698 * List Answer 9:: Integers the hard way
6699 * List Answer 10:: All elements equal
6700 * List Answer 11:: Estimating pi with darts
6701 * List Answer 12:: Estimating pi with matchsticks
6702 * List Answer 13:: Hash codes
6703 * List Answer 14:: Random walk
6704 * Types Answer 1:: Square root of pi times rational
6705 * Types Answer 2:: Infinities
6706 * Types Answer 3:: What can "nan" be?
6707 * Types Answer 4:: Abbey Road
6708 * Types Answer 5:: Friday the 13th
6709 * Types Answer 6:: Leap years
6710 * Types Answer 7:: Erroneous donut
6711 * Types Answer 8:: Dividing intervals
6712 * Types Answer 9:: Squaring intervals
6713 * Types Answer 10:: Fermat's primality test
6714 * Types Answer 11:: pi * 10^7 seconds
6715 * Types Answer 12:: Abbey Road on CD
6716 * Types Answer 13:: Not quite pi * 10^7 seconds
6717 * Types Answer 14:: Supercomputers and c
6718 * Types Answer 15:: Sam the Slug
6719 * Algebra Answer 1:: Squares and square roots
6720 * Algebra Answer 2:: Building polynomial from roots
6721 * Algebra Answer 3:: Integral of x sin(pi x)
6722 * Algebra Answer 4:: Simpson's rule
6723 * Rewrites Answer 1:: Multiplying by conjugate
6724 * Rewrites Answer 2:: Alternative fib rule
6725 * Rewrites Answer 3:: Rewriting opt(a) + opt(b) x
6726 * Rewrites Answer 4:: Sequence of integers
6727 * Rewrites Answer 5:: Number of terms in sum
6728 * Rewrites Answer 6:: Defining 0^0 = 1
6729 * Rewrites Answer 7:: Truncated Taylor series
6730 * Programming Answer 1:: Fresnel's C(x)
6731 * Programming Answer 2:: Negate third stack element
6732 * Programming Answer 3:: Compute sin(x) / x, etc.
6733 * Programming Answer 4:: Average value of a list
6734 * Programming Answer 5:: Continued fraction phi
6735 * Programming Answer 6:: Matrix Fibonacci numbers
6736 * Programming Answer 7:: Harmonic number greater than 4
6737 * Programming Answer 8:: Newton's method
6738 * Programming Answer 9:: Digamma function
6739 * Programming Answer 10:: Unpacking a polynomial
6740 * Programming Answer 11:: Recursive Stirling numbers
6741 * Programming Answer 12:: Stirling numbers with rewrites
6744 @c The following kludgery prevents the individual answers from
6745 @c being entered on the table of contents.
6747 \global\let\oldwrite=\write
6748 \gdef\skipwrite#1#2{\let\write=\oldwrite}
6749 \global\let\oldchapternofonts=\chapternofonts
6750 \gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
6753 @node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
6754 @subsection RPN Tutorial Exercise 1
6757 @kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
6759 The result is @c{$1 - (2 \times (3 + 4)) = -13$}
6760 @cite{1 - (2 * (3 + 4)) = -13}.
6762 @node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
6763 @subsection RPN Tutorial Exercise 2
6766 @c{$2\times4 + 7\times9.5 + {5\over4} = 75.75$}
6767 @cite{2*4 + 7*9.5 + 5/4 = 75.75}
6769 After computing the intermediate term @c{$2\times4 = 8$}
6770 @cite{2*4 = 8}, you can leave
6771 that result on the stack while you compute the second term. With
6772 both of these results waiting on the stack you can then compute the
6773 final term, then press @kbd{+ +} to add everything up.
6782 2 RET 4 * 7 RET 9.5 *
6789 4: 8 3: 8 2: 8 1: 75.75
6790 3: 66.5 2: 66.5 1: 67.75 .
6799 Alternatively, you could add the first two terms before going on
6800 with the third term.
6804 2: 8 1: 74.5 3: 74.5 2: 74.5 1: 75.75
6805 1: 66.5 . 2: 5 1: 1.25 .
6813 On an old-style RPN calculator this second method would have the
6814 advantage of using only three stack levels. But since Calc's stack
6815 can grow arbitrarily large this isn't really an issue. Which method
6816 you choose is purely a matter of taste.
6818 @node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
6819 @subsection RPN Tutorial Exercise 3
6822 The @key{TAB} key provides a way to operate on the number in level 2.
6826 3: 10 3: 10 4: 10 3: 10 3: 10
6827 2: 20 2: 30 3: 30 2: 30 2: 21
6828 1: 30 1: 20 2: 20 1: 21 1: 30
6836 Similarly, @key{M-TAB} gives you access to the number in level 3.
6840 3: 10 3: 21 3: 21 3: 30 3: 11
6841 2: 21 2: 30 2: 30 2: 11 2: 21
6842 1: 30 1: 10 1: 11 1: 21 1: 30
6845 M-TAB 1 + M-TAB M-TAB
6849 @node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
6850 @subsection RPN Tutorial Exercise 4
6853 Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
6854 but using both the comma and the space at once yields:
6858 1: ( ... 2: ( ... 1: (2, ... 2: (2, ... 2: (2, ...
6859 . 1: 2 . 1: (2, ... 1: (2, 3)
6866 Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
6867 extra incomplete object to the top of the stack and delete it.
6868 But a feature of Calc is that @key{DEL} on an incomplete object
6869 deletes just one component out of that object, so he had to press
6870 @key{DEL} twice to finish the job.
6874 2: (2, ... 2: (2, 3) 2: (2, 3) 1: (2, 3)
6875 1: (2, 3) 1: (2, ... 1: ( ... .
6882 (As it turns out, deleting the second-to-top stack entry happens often
6883 enough that Calc provides a special key, @kbd{M-DEL}, to do just that.
6884 @kbd{M-DEL} is just like @kbd{TAB DEL}, except that it doesn't exhibit
6885 the ``feature'' that tripped poor Joe.)
6887 @node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
6888 @subsection Algebraic Entry Tutorial Exercise 1
6891 Type @kbd{' sqrt($) @key{RET}}.
6893 If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
6894 Or, RPN style, @kbd{0.5 ^}.
6896 (Actually, @samp{$^1:2}, using the fraction one-half as the power, is
6897 a closer equivalent, since @samp{9^0.5} yields @cite{3.0} whereas
6898 @samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @cite{3}.)
6900 @node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
6901 @subsection Algebraic Entry Tutorial Exercise 2
6904 In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
6905 name with @samp{1+y} as its argument. Assigning a value to a variable
6906 has no relation to a function by the same name. Joe needed to use an
6907 explicit @samp{*} symbol here: @samp{2 x*(1+y)}.
6909 @node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
6910 @subsection Algebraic Entry Tutorial Exercise 3
6913 The result from @kbd{1 @key{RET} 0 /} will be the formula @cite{1 / 0}.
6914 The ``function'' @samp{/} cannot be evaluated when its second argument
6915 is zero, so it is left in symbolic form. When you now type @kbd{0 *},
6916 the result will be zero because Calc uses the general rule that ``zero
6917 times anything is zero.''
6919 @c [fix-ref Infinities]
6920 The @kbd{m i} command enables an @dfn{infinite mode} in which @cite{1 / 0}
6921 results in a special symbol that represents ``infinity.'' If you
6922 multiply infinity by zero, Calc uses another special new symbol to
6923 show that the answer is ``indeterminate.'' @xref{Infinities}, for
6924 further discussion of infinite and indeterminate values.
6926 @node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
6927 @subsection Modes Tutorial Exercise 1
6930 Calc always stores its numbers in decimal, so even though one-third has
6931 an exact base-3 representation (@samp{3#0.1}), it is still stored as
6932 0.3333333 (chopped off after 12 or however many decimal digits) inside
6933 the calculator's memory. When this inexact number is converted back
6934 to base 3 for display, it may still be slightly inexact. When we
6935 multiply this number by 3, we get 0.999999, also an inexact value.
6937 When Calc displays a number in base 3, it has to decide how many digits
6938 to show. If the current precision is 12 (decimal) digits, that corresponds
6939 to @samp{12 / log10(3) = 25.15} base-3 digits. Because 25.15 is not an
6940 exact integer, Calc shows only 25 digits, with the result that stored
6941 numbers carry a little bit of extra information that may not show up on
6942 the screen. When Joe entered @samp{3#0.2}, the stored number 0.666666
6943 happened to round to a pleasing value when it lost that last 0.15 of a
6944 digit, but it was still inexact in Calc's memory. When he divided by 2,
6945 he still got the dreaded inexact value 0.333333. (Actually, he divided
6946 0.666667 by 2 to get 0.333334, which is why he got something a little
6947 higher than @code{3#0.1} instead of a little lower.)
6949 If Joe didn't want to be bothered with all this, he could have typed
6950 @kbd{M-24 d n} to display with one less digit than the default. (If
6951 you give @kbd{d n} a negative argument, it uses default-minus-that,
6952 so @kbd{M-- d n} would be an easier way to get the same effect.) Those
6953 inexact results would still be lurking there, but they would now be
6954 rounded to nice, natural-looking values for display purposes. (Remember,
6955 @samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
6956 off one digit will round the number up to @samp{0.1}.) Depending on the
6957 nature of your work, this hiding of the inexactness may be a benefit or
6958 a danger. With the @kbd{d n} command, Calc gives you the choice.
6960 Incidentally, another consequence of all this is that if you type
6961 @kbd{M-30 d n} to display more digits than are ``really there,''
6962 you'll see garbage digits at the end of the number. (In decimal
6963 display mode, with decimally-stored numbers, these garbage digits are
6964 always zero so they vanish and you don't notice them.) Because Calc
6965 rounds off that 0.15 digit, there is the danger that two numbers could
6966 be slightly different internally but still look the same. If you feel
6967 uneasy about this, set the @kbd{d n} precision to be a little higher
6968 than normal; you'll get ugly garbage digits, but you'll always be able
6969 to tell two distinct numbers apart.
6971 An interesting side note is that most computers store their
6972 floating-point numbers in binary, and convert to decimal for display.
6973 Thus everyday programs have the same problem: Decimal 0.1 cannot be
6974 represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
6975 comes out as an inexact approximation to 1 on some machines (though
6976 they generally arrange to hide it from you by rounding off one digit as
6977 we did above). Because Calc works in decimal instead of binary, you can
6978 be sure that numbers that look exact @emph{are} exact as long as you stay
6979 in decimal display mode.
6981 It's not hard to show that any number that can be represented exactly
6982 in binary, octal, or hexadecimal is also exact in decimal, so the kinds
6983 of problems we saw in this exercise are likely to be severe only when
6984 you use a relatively unusual radix like 3.
6986 @node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
6987 @subsection Modes Tutorial Exercise 2
6989 If the radix is 15 or higher, we can't use the letter @samp{e} to mark
6990 the exponent because @samp{e} is interpreted as a digit. When Calc
6991 needs to display scientific notation in a high radix, it writes
6992 @samp{16#F.E8F*16.^15}. You can enter a number like this as an
6993 algebraic entry. Also, pressing @kbd{e} without any digits before it
6994 normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
6995 puts you in algebraic entry: @kbd{16#f.e8f RET e 15 RET *} is another
6996 way to enter this number.
6998 The reason Calc puts a decimal point in the @samp{16.^} is to prevent
6999 huge integers from being generated if the exponent is large (consider
7000 @samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
7001 exact integer and then throw away most of the digits when we multiply
7002 it by the floating-point @samp{16#1.23}). While this wouldn't normally
7003 matter for display purposes, it could give you a nasty surprise if you
7004 copied that number into a file and later moved it back into Calc.
7006 @node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
7007 @subsection Modes Tutorial Exercise 3
7010 The answer he got was @cite{0.5000000000006399}.
7012 The problem is not that the square operation is inexact, but that the
7013 sine of 45 that was already on the stack was accurate to only 12 places.
7014 Arbitrary-precision calculations still only give answers as good as
7017 The real problem is that there is no 12-digit number which, when
7018 squared, comes out to 0.5 exactly. The @kbd{f [} and @kbd{f ]}
7019 commands decrease or increase a number by one unit in the last
7020 place (according to the current precision). They are useful for
7021 determining facts like this.
7025 1: 0.707106781187 1: 0.500000000001
7035 1: 0.707106781187 1: 0.707106781186 1: 0.499999999999
7042 A high-precision calculation must be carried out in high precision
7043 all the way. The only number in the original problem which was known
7044 exactly was the quantity 45 degrees, so the precision must be raised
7045 before anything is done after the number 45 has been entered in order
7046 for the higher precision to be meaningful.
7048 @node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
7049 @subsection Modes Tutorial Exercise 4
7052 Many calculations involve real-world quantities, like the width and
7053 height of a piece of wood or the volume of a jar. Such quantities
7054 can't be measured exactly anyway, and if the data that is input to
7055 a calculation is inexact, doing exact arithmetic on it is a waste
7058 Fractions become unwieldy after too many calculations have been
7059 done with them. For example, the sum of the reciprocals of the
7060 integers from 1 to 10 is 7381:2520. The sum from 1 to 30 is
7061 9304682830147:2329089562800. After a point it will take a long
7062 time to add even one more term to this sum, but a floating-point
7063 calculation of the sum will not have this problem.
7065 Also, rational numbers cannot express the results of all calculations.
7066 There is no fractional form for the square root of two, so if you type
7067 @w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
7069 @node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
7070 @subsection Arithmetic Tutorial Exercise 1
7073 Dividing two integers that are larger than the current precision may
7074 give a floating-point result that is inaccurate even when rounded
7075 down to an integer. Consider @cite{123456789 / 2} when the current
7076 precision is 6 digits. The true answer is @cite{61728394.5}, but
7077 with a precision of 6 this will be rounded to @c{$12345700.0/2.0 = 61728500.0$}
7078 @cite{12345700.@: / 2.@: = 61728500.}.
7079 The result, when converted to an integer, will be off by 106.
7081 Here are two solutions: Raise the precision enough that the
7082 floating-point round-off error is strictly to the right of the
7083 decimal point. Or, convert to fraction mode so that @cite{123456789 / 2}
7084 produces the exact fraction @cite{123456789:2}, which can be rounded
7085 down by the @kbd{F} command without ever switching to floating-point
7088 @node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
7089 @subsection Arithmetic Tutorial Exercise 2
7092 @kbd{27 @key{RET} 9 B} could give the exact result @cite{3:2}, but it
7093 does a floating-point calculation instead and produces @cite{1.5}.
7095 Calc will find an exact result for a logarithm if the result is an integer
7096 or the reciprocal of an integer. But there is no efficient way to search
7097 the space of all possible rational numbers for an exact answer, so Calc
7100 @node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
7101 @subsection Vector Tutorial Exercise 1
7104 Duplicate the vector, compute its length, then divide the vector
7105 by its length: @kbd{@key{RET} A /}.
7109 1: [1, 2, 3] 2: [1, 2, 3] 1: [0.27, 0.53, 0.80] 1: 1.
7110 . 1: 3.74165738677 . .
7117 The final @kbd{A} command shows that the normalized vector does
7118 indeed have unit length.
7120 @node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
7121 @subsection Vector Tutorial Exercise 2
7124 The average position is equal to the sum of the products of the
7125 positions times their corresponding probabilities. This is the
7126 definition of the dot product operation. So all you need to do
7127 is to put the two vectors on the stack and press @kbd{*}.
7129 @node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
7130 @subsection Matrix Tutorial Exercise 1
7133 The trick is to multiply by a vector of ones. Use @kbd{r 4 [1 1 1] *} to
7134 get the row sum. Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
7136 @node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
7137 @subsection Matrix Tutorial Exercise 2
7150 $$ \eqalign{ x &+ a y = 6 \cr
7156 Just enter the righthand side vector, then divide by the lefthand side
7161 1: [6, 10] 2: [6, 10] 1: [6 - 4 a / (b - a), 4 / (b - a) ]
7166 ' [6 10] RET ' [1 a; 1 b] RET /
7170 This can be made more readable using @kbd{d B} to enable ``big'' display
7176 1: [6 - -----, -----]
7181 Type @kbd{d N} to return to ``normal'' display mode afterwards.
7183 @node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
7184 @subsection Matrix Tutorial Exercise 3
7187 To solve @c{$A^T A \, X = A^T B$}
7188 @cite{trn(A) * A * X = trn(A) * B}, first we compute
7190 @cite{A2 = trn(A) * A} and @c{$B' = A^T B$}
7191 @cite{B2 = trn(A) * B}; now, we have a
7192 system @c{$A' X = B'$}
7193 @cite{A2 * X = B2} which we can solve using Calc's @samp{/}
7209 $$ \openup1\jot \tabskip=0pt plus1fil
7210 \halign to\displaywidth{\tabskip=0pt
7211 $\hfil#$&$\hfil{}#{}$&
7212 $\hfil#$&$\hfil{}#{}$&
7213 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
7217 2a&+&4b&+&6c&=11 \cr}
7222 The first step is to enter the coefficient matrix. We'll store it in
7223 quick variable number 7 for later reference. Next, we compute the
7229 1: [ [ 1, 2, 3 ] 2: [ [ 1, 4, 7, 2 ] 1: [57, 84, 96]
7230 [ 4, 5, 6 ] [ 2, 5, 6, 4 ] .
7231 [ 7, 6, 0 ] [ 3, 6, 0, 6 ] ]
7232 [ 2, 4, 6 ] ] 1: [6, 2, 3, 11]
7235 ' [1 2 3; 4 5 6; 7 6 0; 2 4 6] RET s 7 v t [6 2 3 11] *
7240 Now we compute the matrix @c{$A'$}
7241 @cite{A2} and divide.
7245 2: [57, 84, 96] 1: [-11.64, 14.08, -3.64]
7246 1: [ [ 70, 72, 39 ] .
7256 (The actual computed answer will be slightly inexact due to
7259 Notice that the answers are similar to those for the @c{$3\times3$}
7261 solved in the text. That's because the fourth equation that was
7262 added to the system is almost identical to the first one multiplied
7263 by two. (If it were identical, we would have gotten the exact same
7264 answer since the @c{$4\times3$}
7265 @asis{4x3} system would be equivalent to the original @c{$3\times3$}
7269 Since the first and fourth equations aren't quite equivalent, they
7270 can't both be satisfied at once. Let's plug our answers back into
7271 the original system of equations to see how well they match.
7275 2: [-11.64, 14.08, -3.64] 1: [5.6, 2., 3., 11.2]
7287 This is reasonably close to our original @cite{B} vector,
7288 @cite{[6, 2, 3, 11]}.
7290 @node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
7291 @subsection List Tutorial Exercise 1
7294 We can use @kbd{v x} to build a vector of integers. This needs to be
7295 adjusted to get the range of integers we desire. Mapping @samp{-}
7296 across the vector will accomplish this, although it turns out the
7297 plain @samp{-} key will work just as well.
7302 1: [1, 2, 3, 4, 5, 6, 7, 8, 9] 1: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
7305 2 v x 9 RET 5 V M - or 5 -
7310 Now we use @kbd{V M ^} to map the exponentiation operator across the
7315 1: [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
7322 @node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
7323 @subsection List Tutorial Exercise 2
7326 Given @cite{x} and @cite{y} vectors in quick variables 1 and 2 as before,
7327 the first job is to form the matrix that describes the problem.
7337 $$ m \times x + b \times 1 = y $$
7341 Thus we want a @c{$19\times2$}
7342 @asis{19x2} matrix with our @cite{x} vector as one column and
7343 ones as the other column. So, first we build the column of ones, then
7344 we combine the two columns to form our @cite{A} matrix.
7348 2: [1.34, 1.41, 1.49, ... ] 1: [ [ 1.34, 1 ]
7349 1: [1, 1, 1, ...] [ 1.41, 1 ]
7353 r 1 1 v b 19 RET M-2 v p v t s 3
7358 Now we compute @c{$A^T y$}
7359 @cite{trn(A) * y} and @c{$A^T A$}
7360 @cite{trn(A) * A} and divide.
7364 1: [33.36554, 13.613] 2: [33.36554, 13.613]
7365 . 1: [ [ 98.0003, 41.63 ]
7369 v t r 2 * r 3 v t r 3 *
7374 (Hey, those numbers look familiar!)
7378 1: [0.52141679, -0.425978]
7385 Since we were solving equations of the form @c{$m \times x + b \times 1 = y$}
7386 @cite{m*x + b*1 = y}, these
7387 numbers should be @cite{m} and @cite{b}, respectively. Sure enough, they
7388 agree exactly with the result computed using @kbd{V M} and @kbd{V R}!
7390 The moral of this story: @kbd{V M} and @kbd{V R} will probably solve
7391 your problem, but there is often an easier way using the higher-level
7392 arithmetic functions!
7394 @c [fix-ref Curve Fitting]
7395 In fact, there is a built-in @kbd{a F} command that does least-squares
7396 fits. @xref{Curve Fitting}.
7398 @node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
7399 @subsection List Tutorial Exercise 3
7402 Move to one end of the list and press @kbd{C-@@} (or @kbd{C-SPC} or
7403 whatever) to set the mark, then move to the other end of the list
7404 and type @w{@kbd{M-# g}}.
7408 1: [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
7413 To make things interesting, let's assume we don't know at a glance
7414 how many numbers are in this list. Then we could type:
7418 2: [2.3, 6, 22, ... ] 2: [2.3, 6, 22, ... ]
7419 1: [2.3, 6, 22, ... ] 1: 126356422.5
7429 2: 126356422.5 2: 126356422.5 1: 7.94652913734
7430 1: [2.3, 6, 22, ... ] 1: 9 .
7438 (The @kbd{I ^} command computes the @var{n}th root of a number.
7439 You could also type @kbd{& ^} to take the reciprocal of 9 and
7440 then raise the number to that power.)
7442 @node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
7443 @subsection List Tutorial Exercise 4
7446 A number @cite{j} is a divisor of @cite{n} if @c{$n \mathbin{\hbox{\code{\%}}} j = 0$}
7447 @samp{n % j = 0}. The first
7448 step is to get a vector that identifies the divisors.
7452 2: 30 2: [0, 0, 0, 2, ...] 1: [1, 1, 1, 0, ...]
7453 1: [1, 2, 3, 4, ...] 1: 0 .
7456 30 RET v x 30 RET s 1 V M % 0 V M a = s 2
7461 This vector has 1's marking divisors of 30 and 0's marking non-divisors.
7463 The zeroth divisor function is just the total number of divisors.
7464 The first divisor function is the sum of the divisors.
7469 2: [1, 2, 3, 4, ...] 1: [1, 2, 3, 0, ...] 1: 72
7470 1: [1, 1, 1, 0, ...] . .
7473 V R + r 1 r 2 V M * V R +
7478 Once again, the last two steps just compute a dot product for which
7479 a simple @kbd{*} would have worked equally well.
7481 @node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
7482 @subsection List Tutorial Exercise 5
7485 The obvious first step is to obtain the list of factors with @kbd{k f}.
7486 This list will always be in sorted order, so if there are duplicates
7487 they will be right next to each other. A suitable method is to compare
7488 the list with a copy of itself shifted over by one.
7492 1: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19, 0]
7493 . 1: [3, 7, 7, 7, 19, 0] 1: [0, 3, 7, 7, 7, 19]
7496 19551 k f RET 0 | TAB 0 TAB |
7503 1: [0, 0, 1, 1, 0, 0] 1: 2 1: 0
7511 Note that we have to arrange for both vectors to have the same length
7512 so that the mapping operation works; no prime factor will ever be
7513 zero, so adding zeros on the left and right is safe. From then on
7514 the job is pretty straightforward.
7516 Incidentally, Calc provides the @c{\dfn{M\"obius} $\mu$}
7517 @dfn{Moebius mu} function which is
7518 zero if and only if its argument is square-free. It would be a much
7519 more convenient way to do the above test in practice.
7521 @node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
7522 @subsection List Tutorial Exercise 6
7525 First use @kbd{v x 6 RET} to get a list of integers, then @kbd{V M v x}
7526 to get a list of lists of integers!
7528 @node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
7529 @subsection List Tutorial Exercise 7
7532 Here's one solution. First, compute the triangular list from the previous
7533 exercise and type @kbd{1 -} to subtract one from all the elements.
7546 The numbers down the lefthand edge of the list we desire are called
7547 the ``triangular numbers'' (now you know why!). The @cite{n}th
7548 triangular number is the sum of the integers from 1 to @cite{n}, and
7549 can be computed directly by the formula @c{$n (n+1) \over 2$}
7550 @cite{n * (n+1) / 2}.
7554 2: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
7555 1: [0, 1, 2, 3, 4, 5] 1: [0, 1, 3, 6, 10, 15]
7558 v x 6 RET 1 - V M ' $ ($+1)/2 RET
7563 Adding this list to the above list of lists produces the desired
7572 [10, 11, 12, 13, 14],
7573 [15, 16, 17, 18, 19, 20] ]
7580 If we did not know the formula for triangular numbers, we could have
7581 computed them using a @kbd{V U +} command. We could also have
7582 gotten them the hard way by mapping a reduction across the original
7587 2: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
7588 1: [ [0], [0, 1], ... ] 1: [0, 1, 3, 6, 10, 15]
7596 (This means ``map a @kbd{V R +} command across the vector,'' and
7597 since each element of the main vector is itself a small vector,
7598 @kbd{V R +} computes the sum of its elements.)
7600 @node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
7601 @subsection List Tutorial Exercise 8
7604 The first step is to build a list of values of @cite{x}.
7608 1: [1, 2, 3, ..., 21] 1: [0, 1, 2, ..., 20] 1: [0, 0.25, 0.5, ..., 5]
7611 v x 21 RET 1 - 4 / s 1
7615 Next, we compute the Bessel function values.
7619 1: [0., 0.124, 0.242, ..., -0.328]
7627 (Another way to do this would be @kbd{1 TAB V M f j}.)
7629 A way to isolate the maximum value is to compute the maximum using
7630 @kbd{V R X}, then compare all the Bessel values with that maximum.
7634 2: [0., 0.124, 0.242, ... ] 1: [0, 0, 0, ... ] 2: [0, 0, 0, ... ]
7638 RET V R X V M a = RET V R + DEL
7643 It's a good idea to verify, as in the last step above, that only
7644 one value is equal to the maximum. (After all, a plot of @c{$\sin x$}
7646 might have many points all equal to the maximum value, 1.)
7648 The vector we have now has a single 1 in the position that indicates
7649 the maximum value of @cite{x}. Now it is a simple matter to convert
7650 this back into the corresponding value itself.
7654 2: [0, 0, 0, ... ] 1: [0, 0., 0., ... ] 1: 1.75
7655 1: [0, 0.25, 0.5, ... ] . .
7662 If @kbd{a =} had produced more than one @cite{1} value, this method
7663 would have given the sum of all maximum @cite{x} values; not very
7664 useful! In this case we could have used @kbd{v m} (@code{calc-mask-vector})
7665 instead. This command deletes all elements of a ``data'' vector that
7666 correspond to zeros in a ``mask'' vector, leaving us with, in this
7667 example, a vector of maximum @cite{x} values.
7669 The built-in @kbd{a X} command maximizes a function using more
7670 efficient methods. Just for illustration, let's use @kbd{a X}
7671 to maximize @samp{besJ(1,x)} over this same interval.
7675 2: besJ(1, x) 1: [1.84115, 0.581865]
7679 ' besJ(1,x), [0..5] RET a X x RET
7684 The output from @kbd{a X} is a vector containing the value of @cite{x}
7685 that maximizes the function, and the function's value at that maximum.
7686 As you can see, our simple search got quite close to the right answer.
7688 @node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
7689 @subsection List Tutorial Exercise 9
7692 Step one is to convert our integer into vector notation.
7696 1: 25129925999 3: 25129925999
7698 1: [11, 10, 9, ..., 1, 0]
7701 25129925999 RET 10 RET 12 RET v x 12 RET -
7708 1: 25129925999 1: [0, 2, 25, 251, 2512, ... ]
7709 2: [100000000000, ... ] .
7717 (Recall, the @kbd{\} command computes an integer quotient.)
7721 1: [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
7728 Next we must increment this number. This involves adding one to
7729 the last digit, plus handling carries. There is a carry to the
7730 left out of a digit if that digit is a nine and all the digits to
7731 the right of it are nines.
7735 1: [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1] 1: [1, 1, 1, 0, 0, 1, ... ]
7745 1: [1, 1, 1, 0, 0, 0, ... ] 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
7753 Accumulating @kbd{*} across a vector of ones and zeros will preserve
7754 only the initial run of ones. These are the carries into all digits
7755 except the rightmost digit. Concatenating a one on the right takes
7756 care of aligning the carries properly, and also adding one to the
7761 2: [0, 0, 0, 0, ... ] 1: [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
7762 1: [0, 0, 2, 5, ... ] .
7765 0 r 2 | V M + 10 V M %
7770 Here we have concatenated 0 to the @emph{left} of the original number;
7771 this takes care of shifting the carries by one with respect to the
7772 digits that generated them.
7774 Finally, we must convert this list back into an integer.
7778 3: [0, 0, 2, 5, ... ] 2: [0, 0, 2, 5, ... ]
7779 2: 1000000000000 1: [1000000000000, 100000000000, ... ]
7780 1: [100000000000, ... ] .
7790 1: [0, 0, 20000000000, 5000000000, ... ] 1: 25129926000
7798 Another way to do this final step would be to reduce the formula
7799 @w{@samp{10 $$ + $}} across the vector of digits.
7803 1: [0, 0, 2, 5, ... ] 1: 25129926000
7810 @node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
7811 @subsection List Tutorial Exercise 10
7814 For the list @cite{[a, b, c, d]}, the result is @cite{((a = b) = c) = d},
7815 which will compare @cite{a} and @cite{b} to produce a 1 or 0, which is
7816 then compared with @cite{c} to produce another 1 or 0, which is then
7817 compared with @cite{d}. This is not at all what Joe wanted.
7819 Here's a more correct method:
7823 1: [7, 7, 7, 8, 7] 2: [7, 7, 7, 8, 7]
7827 ' [7,7,7,8,7] RET RET v r 1 RET
7834 1: [1, 1, 1, 0, 1] 1: 0
7841 @node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
7842 @subsection List Tutorial Exercise 11
7845 The circle of unit radius consists of those points @cite{(x,y)} for which
7846 @cite{x^2 + y^2 < 1}. We start by generating a vector of @cite{x^2}
7847 and a vector of @cite{y^2}.
7849 We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7854 2: [2., 2., ..., 2.] 2: [2., 2., ..., 2.]
7855 1: [2., 2., ..., 2.] 1: [1.16, 1.98, ..., 0.81]
7858 v . t . 2. v b 100 RET RET V M k r
7865 2: [2., 2., ..., 2.] 1: [0.026, 0.96, ..., 0.036]
7866 1: [0.026, 0.96, ..., 0.036] 2: [0.53, 0.81, ..., 0.094]
7869 1 - 2 V M ^ TAB V M k r 1 - 2 V M ^
7873 Now we sum the @cite{x^2} and @cite{y^2} values, compare with 1 to
7874 get a vector of 1/0 truth values, then sum the truth values.
7878 1: [0.56, 1.78, ..., 0.13] 1: [1, 0, ..., 1] 1: 84
7886 The ratio @cite{84/100} should approximate the ratio @c{$\pi/4$}
7891 1: 0.84 1: 3.36 2: 3.36 1: 1.0695
7899 Our estimate, 3.36, is off by about 7%. We could get a better estimate
7900 by taking more points (say, 1000), but it's clear that this method is
7903 (Naturally, since this example uses random numbers your own answer
7904 will be slightly different from the one shown here!)
7906 If you typed @kbd{v .} and @kbd{t .} before, type them again to
7907 return to full-sized display of vectors.
7909 @node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
7910 @subsection List Tutorial Exercise 12
7913 This problem can be made a lot easier by taking advantage of some
7914 symmetries. First of all, after some thought it's clear that the
7915 @cite{y} axis can be ignored altogether. Just pick a random @cite{x}
7916 component for one end of the match, pick a random direction @c{$\theta$}
7918 and see if @cite{x} and @c{$x + \cos \theta$}
7919 @cite{x + cos(theta)} (which is the @cite{x}
7920 coordinate of the other endpoint) cross a line. The lines are at
7921 integer coordinates, so this happens when the two numbers surround
7924 Since the two endpoints are equivalent, we may as well choose the leftmost
7925 of the two endpoints as @cite{x}. Then @cite{theta} is an angle pointing
7926 to the right, in the range -90 to 90 degrees. (We could use radians, but
7927 it would feel like cheating to refer to @c{$\pi/2$}
7928 @cite{pi/2} radians while trying
7929 to estimate @c{$\pi$}
7932 In fact, since the field of lines is infinite we can choose the
7933 coordinates 0 and 1 for the lines on either side of the leftmost
7934 endpoint. The rightmost endpoint will be between 0 and 1 if the
7935 match does not cross a line, or between 1 and 2 if it does. So:
7936 Pick random @cite{x} and @c{$\theta$}
7937 @cite{theta}, compute @c{$x + \cos \theta$}
7938 @cite{x + cos(theta)},
7939 and count how many of the results are greater than one. Simple!
7941 We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7946 1: [0.52, 0.71, ..., 0.72] 2: [0.52, 0.71, ..., 0.72]
7947 . 1: [78.4, 64.5, ..., -42.9]
7950 v . t . 1. v b 100 RET V M k r 180. v b 100 RET V M k r 90 -
7955 (The next step may be slow, depending on the speed of your computer.)
7959 2: [0.52, 0.71, ..., 0.72] 1: [0.72, 1.14, ..., 1.45]
7960 1: [0.20, 0.43, ..., 0.73] .
7970 1: [0, 1, ..., 1] 1: 0.64 1: 3.125
7973 1 V M a > V R + 100 / 2 TAB /
7977 Let's try the third method, too. We'll use random integers up to
7978 one million. The @kbd{k r} command with an integer argument picks
7983 2: [1000000, 1000000, ..., 1000000] 2: [78489, 527587, ..., 814975]
7984 1: [1000000, 1000000, ..., 1000000] 1: [324014, 358783, ..., 955450]
7987 1000000 v b 100 RET RET V M k r TAB V M k r
7994 1: [1, 1, ..., 25] 1: [1, 1, ..., 0] 1: 0.56
7997 V M k g 1 V M a = V R + 100 /
8011 For a proof of this property of the GCD function, see section 4.5.2,
8012 exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
8014 If you typed @kbd{v .} and @kbd{t .} before, type them again to
8015 return to full-sized display of vectors.
8017 @node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
8018 @subsection List Tutorial Exercise 13
8021 First, we put the string on the stack as a vector of ASCII codes.
8025 1: [84, 101, 115, ..., 51]
8028 "Testing, 1, 2, 3 RET
8033 Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
8034 there was no need to type an apostrophe. Also, Calc didn't mind that
8035 we omitted the closing @kbd{"}. (The same goes for all closing delimiters
8036 like @kbd{)} and @kbd{]} at the end of a formula.
8038 We'll show two different approaches here. In the first, we note that
8039 if the input vector is @cite{[a, b, c, d]}, then the hash code is
8040 @cite{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}. In other words,
8041 it's a sum of descending powers of three times the ASCII codes.
8045 2: [84, 101, 115, ..., 51] 2: [84, 101, 115, ..., 51]
8046 1: 16 1: [15, 14, 13, ..., 0]
8049 RET v l v x 16 RET -
8056 2: [84, 101, 115, ..., 51] 1: 1960915098 1: 121
8057 1: [14348907, ..., 1] . .
8065 Once again, @kbd{*} elegantly summarizes most of the computation.
8066 But there's an even more elegant approach: Reduce the formula
8067 @kbd{3 $$ + $} across the vector. Recall that this represents a
8068 function of two arguments that computes its first argument times three
8069 plus its second argument.
8073 1: [84, 101, 115, ..., 51] 1: 1960915098
8076 "Testing, 1, 2, 3 RET V R ' 3$$+$ RET
8081 If you did the decimal arithmetic exercise, this will be familiar.
8082 Basically, we're turning a base-3 vector of digits into an integer,
8083 except that our ``digits'' are much larger than real digits.
8085 Instead of typing @kbd{511 %} again to reduce the result, we can be
8086 cleverer still and notice that rather than computing a huge integer
8087 and taking the modulo at the end, we can take the modulo at each step
8088 without affecting the result. While this means there are more
8089 arithmetic operations, the numbers we operate on remain small so
8090 the operations are faster.
8094 1: [84, 101, 115, ..., 51] 1: 121
8097 "Testing, 1, 2, 3 RET V R ' (3$$+$)%511 RET
8101 Why does this work? Think about a two-step computation:
8102 @w{@cite{3 (3a + b) + c}}. Taking a result modulo 511 basically means
8103 subtracting off enough 511's to put the result in the desired range.
8104 So the result when we take the modulo after every step is,
8108 3 (3 a + b - 511 m) + c - 511 n
8114 $$ 3 (3 a + b - 511 m) + c - 511 n $$
8119 for some suitable integers @cite{m} and @cite{n}. Expanding out by
8120 the distributive law yields
8124 9 a + 3 b + c - 511*3 m - 511 n
8130 $$ 9 a + 3 b + c - 511\times3 m - 511 n $$
8135 The @cite{m} term in the latter formula is redundant because any
8136 contribution it makes could just as easily be made by the @cite{n}
8137 term. So we can take it out to get an equivalent formula with
8142 9 a + 3 b + c - 511 n'
8148 $$ 9 a + 3 b + c - 511 n' $$
8153 which is just the formula for taking the modulo only at the end of
8154 the calculation. Therefore the two methods are essentially the same.
8156 Later in the tutorial we will encounter @dfn{modulo forms}, which
8157 basically automate the idea of reducing every intermediate result
8158 modulo some value @i{M}.
8160 @node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
8161 @subsection List Tutorial Exercise 14
8163 We want to use @kbd{H V U} to nest a function which adds a random
8164 step to an @cite{(x,y)} coordinate. The function is a bit long, but
8165 otherwise the problem is quite straightforward.
8169 2: [0, 0] 1: [ [ 0, 0 ]
8170 1: 50 [ 0.4288, -0.1695 ]
8171 . [ -0.4787, -0.9027 ]
8174 [0,0] 50 H V U ' <# + [random(2.0)-1, random(2.0)-1]> RET
8178 Just as the text recommended, we used @samp{< >} nameless function
8179 notation to keep the two @code{random} calls from being evaluated
8180 before nesting even begins.
8182 We now have a vector of @cite{[x, y]} sub-vectors, which by Calc's
8183 rules acts like a matrix. We can transpose this matrix and unpack
8184 to get a pair of vectors, @cite{x} and @cite{y}, suitable for graphing.
8188 2: [ 0, 0.4288, -0.4787, ... ]
8189 1: [ 0, -0.1696, -0.9027, ... ]
8196 Incidentally, because the @cite{x} and @cite{y} are completely
8197 independent in this case, we could have done two separate commands
8198 to create our @cite{x} and @cite{y} vectors of numbers directly.
8200 To make a random walk of unit steps, we note that @code{sincos} of
8201 a random direction exactly gives us an @cite{[x, y]} step of unit
8202 length; in fact, the new nesting function is even briefer, though
8203 we might want to lower the precision a bit for it.
8207 2: [0, 0] 1: [ [ 0, 0 ]
8208 1: 50 [ 0.1318, 0.9912 ]
8209 . [ -0.5965, 0.3061 ]
8212 [0,0] 50 m d p 6 RET H V U ' <# + sincos(random(360.0))> RET
8216 Another @kbd{v t v u g f} sequence will graph this new random walk.
8218 An interesting twist on these random walk functions would be to use
8219 complex numbers instead of 2-vectors to represent points on the plane.
8220 In the first example, we'd use something like @samp{random + random*(0,1)},
8221 and in the second we could use polar complex numbers with random phase
8222 angles. (This exercise was first suggested in this form by Randal
8225 @node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
8226 @subsection Types Tutorial Exercise 1
8229 If the number is the square root of @c{$\pi$}
8230 @cite{pi} times a rational number,
8231 then its square, divided by @c{$\pi$}
8232 @cite{pi}, should be a rational number.
8236 1: 1.26508260337 1: 0.509433962268 1: 2486645810:4881193627
8244 Technically speaking this is a rational number, but not one that is
8245 likely to have arisen in the original problem. More likely, it just
8246 happens to be the fraction which most closely represents some
8247 irrational number to within 12 digits.
8249 But perhaps our result was not quite exact. Let's reduce the
8250 precision slightly and try again:
8254 1: 0.509433962268 1: 27:53
8262 Aha! It's unlikely that an irrational number would equal a fraction
8263 this simple to within ten digits, so our original number was probably
8264 @c{$\sqrt{27 \pi / 53}$}
8265 @cite{sqrt(27 pi / 53)}.
8267 Notice that we didn't need to re-round the number when we reduced the
8268 precision. Remember, arithmetic operations always round their inputs
8269 to the current precision before they begin.
8271 @node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
8272 @subsection Types Tutorial Exercise 2
8275 @samp{inf / inf = nan}. Perhaps @samp{1} is the ``obvious'' answer.
8276 But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
8278 @samp{exp(inf) = inf}. It's tempting to say that the exponential
8279 of infinity must be ``bigger'' than ``regular'' infinity, but as
8280 far as Calc is concerned all infinities are as just as big.
8281 In other words, as @cite{x} goes to infinity, @cite{e^x} also goes
8282 to infinity, but the fact the @cite{e^x} grows much faster than
8283 @cite{x} is not relevant here.
8285 @samp{exp(-inf) = 0}. Here we have a finite answer even though
8286 the input is infinite.
8288 @samp{sqrt(-inf) = (0, 1) inf}. Remember that @cite{(0, 1)}
8289 represents the imaginary number @cite{i}. Here's a derivation:
8290 @samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
8291 The first part is, by definition, @cite{i}; the second is @code{inf}
8292 because, once again, all infinities are the same size.
8294 @samp{sqrt(uinf) = uinf}. In fact, we do know something about the
8295 direction because @code{sqrt} is defined to return a value in the
8296 right half of the complex plane. But Calc has no notation for this,
8297 so it settles for the conservative answer @code{uinf}.
8299 @samp{abs(uinf) = inf}. No matter which direction @cite{x} points,
8300 @samp{abs(x)} always points along the positive real axis.
8302 @samp{ln(0) = -inf}. Here we have an infinite answer to a finite
8303 input. As in the @cite{1 / 0} case, Calc will only use infinities
8304 here if you have turned on ``infinite'' mode. Otherwise, it will
8305 treat @samp{ln(0)} as an error.
8307 @node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
8308 @subsection Types Tutorial Exercise 3
8311 We can make @samp{inf - inf} be any real number we like, say,
8312 @cite{a}, just by claiming that we added @cite{a} to the first
8313 infinity but not to the second. This is just as true for complex
8314 values of @cite{a}, so @code{nan} can stand for a complex number.
8315 (And, similarly, @code{uinf} can stand for an infinity that points
8316 in any direction in the complex plane, such as @samp{(0, 1) inf}).
8318 In fact, we can multiply the first @code{inf} by two. Surely
8319 @w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
8320 So @code{nan} can even stand for infinity. Obviously it's just
8321 as easy to make it stand for minus infinity as for plus infinity.
8323 The moral of this story is that ``infinity'' is a slippery fish
8324 indeed, and Calc tries to handle it by having a very simple model
8325 for infinities (only the direction counts, not the ``size''); but
8326 Calc is careful to write @code{nan} any time this simple model is
8327 unable to tell what the true answer is.
8329 @node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
8330 @subsection Types Tutorial Exercise 4
8334 2: 0@@ 47' 26" 1: 0@@ 2' 47.411765"
8338 0@@ 47' 26" RET 17 /
8343 The average song length is two minutes and 47.4 seconds.
8347 2: 0@@ 2' 47.411765" 1: 0@@ 3' 7.411765" 1: 0@@ 53' 6.000005"
8356 The album would be 53 minutes and 6 seconds long.
8358 @node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
8359 @subsection Types Tutorial Exercise 5
8362 Let's suppose it's January 14, 1991. The easiest thing to do is
8363 to keep trying 13ths of months until Calc reports a Friday.
8364 We can do this by manually entering dates, or by using @kbd{t I}:
8368 1: <Wed Feb 13, 1991> 1: <Wed Mar 13, 1991> 1: <Sat Apr 13, 1991>
8371 ' <2/13> RET DEL ' <3/13> RET t I
8376 (Calc assumes the current year if you don't say otherwise.)
8378 This is getting tedious---we can keep advancing the date by typing
8379 @kbd{t I} over and over again, but let's automate the job by using
8380 vector mapping. The @kbd{t I} command actually takes a second
8381 ``how-many-months'' argument, which defaults to one. This
8382 argument is exactly what we want to map over:
8386 2: <Sat Apr 13, 1991> 1: [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
8387 1: [1, 2, 3, 4, 5, 6] <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
8388 . <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
8397 Et voila, September 13, 1991 is a Friday.
8401 {\it Et voil{\accent"12 a}}, September 13, 1991 is a Friday.
8409 ' <sep 13> - <jan 14> RET
8414 And the answer to our original question: 242 days to go.
8416 @node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
8417 @subsection Types Tutorial Exercise 6
8420 The full rule for leap years is that they occur in every year divisible
8421 by four, except that they don't occur in years divisible by 100, except
8422 that they @emph{do} in years divisible by 400. We could work out the
8423 answer by carefully counting the years divisible by four and the
8424 exceptions, but there is a much simpler way that works even if we
8425 don't know the leap year rule.
8427 Let's assume the present year is 1991. Years have 365 days, except
8428 that leap years (whenever they occur) have 366 days. So let's count
8429 the number of days between now and then, and compare that to the
8430 number of years times 365. The number of extra days we find must be
8431 equal to the number of leap years there were.
8435 1: <Mon Jan 1, 10001> 2: <Mon Jan 1, 10001> 1: 2925593
8436 . 1: <Tue Jan 1, 1991> .
8439 ' <jan 1 10001> RET ' <jan 1 1991> RET -
8446 3: 2925593 2: 2925593 2: 2925593 1: 1943
8447 2: 10001 1: 8010 1: 2923650 .
8451 10001 RET 1991 - 365 * -
8455 @c [fix-ref Date Forms]
8457 There will be 1943 leap years before the year 10001. (Assuming,
8458 of course, that the algorithm for computing leap years remains
8459 unchanged for that long. @xref{Date Forms}, for some interesting
8460 background information in that regard.)
8462 @node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
8463 @subsection Types Tutorial Exercise 7
8466 The relative errors must be converted to absolute errors so that
8467 @samp{+/-} notation may be used.
8475 20 RET .05 * 4 RET .05 *
8479 Now we simply chug through the formula.
8483 1: 19.7392088022 1: 394.78 +/- 19.739 1: 6316.5 +/- 706.21
8486 2 P 2 ^ * 20 p 1 * 4 p .2 RET 2 ^ *
8490 It turns out the @kbd{v u} command will unpack an error form as
8491 well as a vector. This saves us some retyping of numbers.
8495 3: 6316.5 +/- 706.21 2: 6316.5 +/- 706.21
8505 Thus the volume is 6316 cubic centimeters, within about 11 percent.
8507 @node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
8508 @subsection Types Tutorial Exercise 8
8511 The first answer is pretty simple: @samp{1 / (0 .. 10) = (0.1 .. inf)}.
8512 Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
8513 close to zero, its reciprocal can get arbitrarily large, so the answer
8514 is an interval that effectively means, ``any number greater than 0.1''
8515 but with no upper bound.
8517 The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
8519 Calc normally treats division by zero as an error, so that the formula
8520 @w{@samp{1 / 0}} is left unsimplified. Our third problem,
8521 @w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
8522 is now a member of the interval. So Calc leaves this one unevaluated, too.
8524 If you turn on ``infinite'' mode by pressing @kbd{m i}, you will
8525 instead get the answer @samp{[0.1 .. inf]}, which includes infinity
8526 as a possible value.
8528 The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
8529 Zero is buried inside the interval, but it's still a possible value.
8530 It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
8531 will be either greater than @i{0.1}, or less than @i{-0.1}. Thus
8532 the interval goes from minus infinity to plus infinity, with a ``hole''
8533 in it from @i{-0.1} to @i{0.1}. Calc doesn't have any way to
8534 represent this, so it just reports @samp{[-inf .. inf]} as the answer.
8535 It may be disappointing to hear ``the answer lies somewhere between
8536 minus infinity and plus infinity, inclusive,'' but that's the best
8537 that interval arithmetic can do in this case.
8539 @node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
8540 @subsection Types Tutorial Exercise 9
8544 1: [-3 .. 3] 2: [-3 .. 3] 2: [0 .. 9]
8545 . 1: [0 .. 9] 1: [-9 .. 9]
8548 [ 3 n .. 3 ] RET 2 ^ TAB RET *
8553 In the first case the result says, ``if a number is between @i{-3} and
8554 3, its square is between 0 and 9.'' The second case says, ``the product
8555 of two numbers each between @i{-3} and 3 is between @i{-9} and 9.''
8557 An interval form is not a number; it is a symbol that can stand for
8558 many different numbers. Two identical-looking interval forms can stand
8559 for different numbers.
8561 The same issue arises when you try to square an error form.
8563 @node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
8564 @subsection Types Tutorial Exercise 10
8567 Testing the first number, we might arbitrarily choose 17 for @cite{x}.
8571 1: 17 mod 811749613 2: 17 mod 811749613 1: 533694123 mod 811749613
8575 17 M 811749613 RET 811749612 ^
8580 Since 533694123 is (considerably) different from 1, the number 811749613
8583 It's awkward to type the number in twice as we did above. There are
8584 various ways to avoid this, and algebraic entry is one. In fact, using
8585 a vector mapping operation we can perform several tests at once. Let's
8586 use this method to test the second number.
8590 2: [17, 42, 100000] 1: [1 mod 15485863, 1 mod ... ]
8594 [17 42 100000] 15485863 RET V M ' ($$ mod $)^($-1) RET
8599 The result is three ones (modulo @cite{n}), so it's very probable that
8600 15485863 is prime. (In fact, this number is the millionth prime.)
8602 Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
8603 would have been hopelessly inefficient, since they would have calculated
8604 the power using full integer arithmetic.
8606 Calc has a @kbd{k p} command that does primality testing. For small
8607 numbers it does an exact test; for large numbers it uses a variant
8608 of the Fermat test we used here. You can use @kbd{k p} repeatedly
8609 to prove that a large integer is prime with any desired probability.
8611 @node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
8612 @subsection Types Tutorial Exercise 11
8615 There are several ways to insert a calculated number into an HMS form.
8616 One way to convert a number of seconds to an HMS form is simply to
8617 multiply the number by an HMS form representing one second:
8621 1: 31415926.5359 2: 31415926.5359 1: 8726@@ 38' 46.5359"
8632 2: 8726@@ 38' 46.5359" 1: 6@@ 6' 2.5359" mod 24@@ 0' 0"
8633 1: 15@@ 27' 16" mod 24@@ 0' 0" .
8641 It will be just after six in the morning.
8643 The algebraic @code{hms} function can also be used to build an
8648 1: hms(0, 0, 10000000. pi) 1: 8726@@ 38' 46.5359"
8651 ' hms(0, 0, 1e7 pi) RET =
8656 The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
8657 the actual number 3.14159...
8659 @node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
8660 @subsection Types Tutorial Exercise 12
8663 As we recall, there are 17 songs of about 2 minutes and 47 seconds
8668 2: 0@@ 2' 47" 1: [0@@ 3' 7" .. 0@@ 3' 47"]
8669 1: [0@@ 0' 20" .. 0@@ 1' 0"] .
8672 [ 0@@ 20" .. 0@@ 1' ] +
8679 1: [0@@ 52' 59." .. 1@@ 4' 19."]
8687 No matter how long it is, the album will fit nicely on one CD.
8689 @node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
8690 @subsection Types Tutorial Exercise 13
8693 Type @kbd{' 1 yr RET u c s RET}. The answer is 31557600 seconds.
8695 @node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
8696 @subsection Types Tutorial Exercise 14
8699 How long will it take for a signal to get from one end of the computer
8704 1: m / c 1: 3.3356 ns
8707 ' 1 m / c RET u c ns RET
8712 (Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
8716 1: 3.3356 ns 1: 0.81356 ns / ns 1: 0.81356
8725 Thus a signal could take up to 81 percent of a clock cycle just to
8726 go from one place to another inside the computer, assuming the signal
8727 could actually attain the full speed of light. Pretty tight!
8729 @node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
8730 @subsection Types Tutorial Exercise 15
8733 The speed limit is 55 miles per hour on most highways. We want to
8734 find the ratio of Sam's speed to the US speed limit.
8738 1: 55 mph 2: 55 mph 3: 11 hr mph / yd
8742 ' 55 mph RET ' 5 yd/hr RET /
8746 The @kbd{u s} command cancels out these units to get a plain
8747 number. Now we take the logarithm base two to find the final
8748 answer, assuming that each successive pill doubles his speed.
8752 1: 19360. 2: 19360. 1: 14.24
8761 Thus Sam can take up to 14 pills without a worry.
8763 @node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
8764 @subsection Algebra Tutorial Exercise 1
8767 @c [fix-ref Declarations]
8768 The result @samp{sqrt(x)^2} is simplified back to @cite{x} by the
8769 Calculator, but @samp{sqrt(x^2)} is not. (Consider what happens
8770 if @w{@cite{x = -4}}.) If @cite{x} is real, this formula could be
8771 simplified to @samp{abs(x)}, but for general complex arguments even
8772 that is not safe. (@xref{Declarations}, for a way to tell Calc
8773 that @cite{x} is known to be real.)
8775 @node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
8776 @subsection Algebra Tutorial Exercise 2
8779 Suppose our roots are @cite{[a, b, c]}. We want a polynomial which
8780 is zero when @cite{x} is any of these values. The trivial polynomial
8781 @cite{x-a} is zero when @cite{x=a}, so the product @cite{(x-a)(x-b)(x-c)}
8782 will do the job. We can use @kbd{a c x} to write this in a more
8787 1: 34 x - 24 x^3 1: [1.19023, -1.19023, 0]
8797 1: [x - 1.19023, x + 1.19023, x] 1: (x - 1.19023) (x + 1.19023) x
8807 1: x^3 - 1.41666 x 1: 34 x - 24 x^3
8810 a c x RET 24 n * a x
8815 Sure enough, our answer (multiplied by a suitable constant) is the
8816 same as the original polynomial.
8818 @node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
8819 @subsection Algebra Tutorial Exercise 3
8823 1: x sin(pi x) 1: (sin(pi x) - pi x cos(pi x)) / pi^2
8826 ' x sin(pi x) RET m r a i x RET
8834 2: (sin(pi x) - pi x cos(pi x)) / pi^2
8844 1: [(sin(pi y) - pi y cos(pi y)) / pi^2, (sin(pi) - pi cos(pi)) / pi^2]
8854 1: (sin(pi y) - pi y cos(pi y)) / pi^2 + (pi cos(pi) - sin(pi)) / pi^2
8864 1: (sin(3.14159 y) - 3.14159 y cos(3.14159 y)) / 9.8696 - 0.3183
8874 1: [0., -0.95493, 0.63662, -1.5915, 1.2732]
8877 v x 5 RET TAB V M $ RET
8881 @node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
8882 @subsection Algebra Tutorial Exercise 4
8885 The hard part is that @kbd{V R +} is no longer sufficient to add up all
8886 the contributions from the slices, since the slices have varying
8887 coefficients. So first we must come up with a vector of these
8888 coefficients. Here's one way:
8892 2: -1 2: 3 1: [4, 2, ..., 4]
8893 1: [1, 2, ..., 9] 1: [-1, 1, ..., -1] .
8896 1 n v x 9 RET V M ^ 3 TAB -
8903 1: [4, 2, ..., 4, 1] 1: [1, 4, 2, ..., 4, 1]
8911 Now we compute the function values. Note that for this method we need
8912 eleven values, including both endpoints of the desired interval.
8916 2: [1, 4, 2, ..., 4, 1]
8917 1: [1, 1.1, 1.2, ... , 1.8, 1.9, 2.]
8920 11 RET 1 RET .1 RET C-u v x
8927 2: [1, 4, 2, ..., 4, 1]
8928 1: [0., 0.084941, 0.16993, ... ]
8931 ' sin(x) ln(x) RET m r p 5 RET V M $ RET
8936 Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
8941 1: 11.22 1: 1.122 1: 0.374
8949 Wow! That's even better than the result from the Taylor series method.
8951 @node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
8952 @subsection Rewrites Tutorial Exercise 1
8955 We'll use Big mode to make the formulas more readable.
8961 1: (2 + sqrt(2)) / (1 + sqrt(2)) 1: --------
8967 ' (2+sqrt(2)) / (1+sqrt(2)) RET d B
8972 Multiplying by the conjugate helps because @cite{(a+b) (a-b) = a^2 - b^2}.
8977 1: (2 + V 2 ) (V 2 - 1)
8980 a r a/(b+c) := a*(b-c) / (b^2-c^2) RET
8988 1: 2 + V 2 - 2 1: V 2
8991 a r a*(b+c) := a*b + a*c a s
8996 (We could have used @kbd{a x} instead of a rewrite rule for the
8999 The multiply-by-conjugate rule turns out to be useful in many
9000 different circumstances, such as when the denominator involves
9001 sines and cosines or the imaginary constant @code{i}.
9003 @node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
9004 @subsection Rewrites Tutorial Exercise 2
9007 Here is the rule set:
9011 [ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
9013 fib(n, x, y) := fib(n-1, y, x+y) ]
9018 The first rule turns a one-argument @code{fib} that people like to write
9019 into a three-argument @code{fib} that makes computation easier. The
9020 second rule converts back from three-argument form once the computation
9021 is done. The third rule does the computation itself. It basically
9022 says that if @cite{x} and @cite{y} are two consecutive Fibonacci numbers,
9023 then @cite{y} and @cite{x+y} are the next (overlapping) pair of Fibonacci
9026 Notice that because the number @cite{n} was ``validated'' by the
9027 conditions on the first rule, there is no need to put conditions on
9028 the other rules because the rule set would never get that far unless
9029 the input were valid. That further speeds computation, since no
9030 extra conditions need to be checked at every step.
9032 Actually, a user with a nasty sense of humor could enter a bad
9033 three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
9034 which would get the rules into an infinite loop. One thing that would
9035 help keep this from happening by accident would be to use something like
9036 @samp{ZzFib} instead of @code{fib} as the name of the three-argument
9039 @node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
9040 @subsection Rewrites Tutorial Exercise 3
9043 He got an infinite loop. First, Calc did as expected and rewrote
9044 @w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}. Then it looked for ways to
9045 apply the rule again, and found that @samp{f(2, 3, x)} looks like
9046 @samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
9047 @samp{f(0, 1, f(2, 3, x))}. It then wrapped another @samp{f(0, 1, ...)}
9048 around that, and so on, ad infinitum. Joe should have used @kbd{M-1 a r}
9049 to make sure the rule applied only once.
9051 (Actually, even the first step didn't work as he expected. What Calc
9052 really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
9053 treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
9054 to it. While this may seem odd, it's just as valid a solution as the
9055 ``obvious'' one. One way to fix this would be to add the condition
9056 @samp{:: variable(x)} to the rule, to make sure the thing that matches
9057 @samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
9058 on the lefthand side, so that the rule matches the actual variable
9059 @samp{x} rather than letting @samp{x} stand for something else.)
9061 @node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
9062 @subsection Rewrites Tutorial Exercise 4
9067 Here is a suitable set of rules to solve the first part of the problem:
9071 [ seq(n, c) := seq(n/2, c+1) :: n%2 = 0,
9072 seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
9076 Given the initial formula @samp{seq(6, 0)}, application of these
9077 rules produces the following sequence of formulas:
9091 whereupon neither of the rules match, and rewriting stops.
9093 We can pretty this up a bit with a couple more rules:
9097 [ seq(n) := seq(n, 0),
9104 Now, given @samp{seq(6)} as the starting configuration, we get 8
9107 The change to return a vector is quite simple:
9111 [ seq(n) := seq(n, []) :: integer(n) :: n > 0,
9113 seq(n, v) := seq(n/2, v | n) :: n%2 = 0,
9114 seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
9119 Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
9121 Notice that the @cite{n > 1} guard is no longer necessary on the last
9122 rule since the @cite{n = 1} case is now detected by another rule.
9123 But a guard has been added to the initial rule to make sure the
9124 initial value is suitable before the computation begins.
9126 While still a good idea, this guard is not as vitally important as it
9127 was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
9128 will not get into an infinite loop. Calc will not be able to prove
9129 the symbol @samp{x} is either even or odd, so none of the rules will
9130 apply and the rewrites will stop right away.
9132 @node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
9133 @subsection Rewrites Tutorial Exercise 5
9138 If @cite{x} is the sum @cite{a + b}, then `@t{nterms(}@i{x}@t{)}' must
9139 be `@t{nterms(}@i{a}@t{)}' plus `@t{nterms(}@i{b}@t{)}'. If @cite{x}
9140 is not a sum, then `@t{nterms(}@i{x}@t{)}' = 1.
9144 [ nterms(a + b) := nterms(a) + nterms(b),
9150 Here we have taken advantage of the fact that earlier rules always
9151 match before later rules; @samp{nterms(x)} will only be tried if we
9152 already know that @samp{x} is not a sum.
9154 @node Rewrites Answer 6, Rewrites Answer 7, Rewrites Answer 5, Answers to Exercises
9155 @subsection Rewrites Tutorial Exercise 6
9157 Just put the rule @samp{0^0 := 1} into @code{EvalRules}. For example,
9158 before making this definition we have:
9162 2: [-2, -1, 0, 1, 2] 1: [1, 1, 0^0, 1, 1]
9166 v x 5 RET 3 - 0 V M ^
9175 2: [-2, -1, 0, 1, 2] 1: [1, 1, 1, 1, 1]
9179 U ' 0^0:=1 RET s t EvalRules RET V M ^
9183 Perhaps more surprisingly, this rule still works with infinite mode
9184 turned on. Calc tries @code{EvalRules} before any built-in rules for
9185 a function. This allows you to override the default behavior of any
9186 Calc feature: Even though Calc now wants to evaluate @cite{0^0} to
9187 @code{nan}, your rule gets there first and evaluates it to 1 instead.
9189 Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
9190 What happens? (Be sure to remove this rule afterward, or you might get
9191 a nasty surprise when you use Calc to balance your checkbook!)
9193 @node Rewrites Answer 7, Programming Answer 1, Rewrites Answer 6, Answers to Exercises
9194 @subsection Rewrites Tutorial Exercise 7
9197 Here is a rule set that will do the job:
9201 [ a*(b + c) := a*b + a*c,
9202 opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
9203 :: constant(a) :: constant(b),
9204 opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
9205 :: constant(a) :: constant(b),
9206 a O(x^n) := O(x^n) :: constant(a),
9207 x^opt(m) O(x^n) := O(x^(n+m)),
9208 O(x^n) O(x^m) := O(x^(n+m)) ]
9212 If we really want the @kbd{+} and @kbd{*} keys to operate naturally
9213 on power series, we should put these rules in @code{EvalRules}. For
9214 testing purposes, it is better to put them in a different variable,
9215 say, @code{O}, first.
9217 The first rule just expands products of sums so that the rest of the
9218 rules can assume they have an expanded-out polynomial to work with.
9219 Note that this rule does not mention @samp{O} at all, so it will
9220 apply to any product-of-sum it encounters---this rule may surprise
9221 you if you put it into @code{EvalRules}!
9223 In the second rule, the sum of two O's is changed to the smaller O.
9224 The optional constant coefficients are there mostly so that
9225 @samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
9226 as well as @samp{O(x^2) + O(x^3)}.
9228 The third rule absorbs higher powers of @samp{x} into O's.
9230 The fourth rule says that a constant times a negligible quantity
9231 is still negligible. (This rule will also match @samp{O(x^3) / 4},
9232 with @samp{a = 1/4}.)
9234 The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
9235 (It is easy to see that if one of these forms is negligible, the other
9236 is, too.) Notice the @samp{x^opt(m)} to pick up terms like
9237 @w{@samp{x O(x^3)}}. Optional powers will match @samp{x} as @samp{x^1}
9238 but not 1 as @samp{x^0}. This turns out to be exactly what we want here.
9240 The sixth rule is the corresponding rule for products of two O's.
9242 Another way to solve this problem would be to create a new ``data type''
9243 that represents truncated power series. We might represent these as
9244 function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
9245 a vector of coefficients for @cite{x^0}, @cite{x^1}, @cite{x^2}, and so
9246 on. Rules would exist for sums and products of such @code{series}
9247 objects, and as an optional convenience could also know how to combine a
9248 @code{series} object with a normal polynomial. (With this, and with a
9249 rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
9250 you could still enter power series in exactly the same notation as
9251 before.) Operations on such objects would probably be more efficient,
9252 although the objects would be a bit harder to read.
9254 @c [fix-ref Compositions]
9255 Some other symbolic math programs provide a power series data type
9256 similar to this. Mathematica, for example, has an object that looks
9257 like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
9258 @var{nmax}, @var{den}]}, where @var{x0} is the point about which the
9259 power series is taken (we've been assuming this was always zero),
9260 and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
9261 with fractional or negative powers. Also, the @code{PowerSeries}
9262 objects have a special display format that makes them look like
9263 @samp{2 x^2 + O(x^4)} when they are printed out. (@xref{Compositions},
9264 for a way to do this in Calc, although for something as involved as
9265 this it would probably be better to write the formatting routine
9268 @node Programming Answer 1, Programming Answer 2, Rewrites Answer 7, Answers to Exercises
9269 @subsection Programming Tutorial Exercise 1
9272 Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
9273 @kbd{Z F}, and answer the questions. Since this formula contains two
9274 variables, the default argument list will be @samp{(t x)}. We want to
9275 change this to @samp{(x)} since @cite{t} is really a dummy variable
9276 to be used within @code{ninteg}.
9278 The exact keystrokes are @kbd{Z F s Si RET RET C-b C-b DEL DEL RET y}.
9279 (The @kbd{C-b C-b DEL DEL} are what fix the argument list.)
9281 @node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
9282 @subsection Programming Tutorial Exercise 2
9285 One way is to move the number to the top of the stack, operate on
9286 it, then move it back: @kbd{C-x ( M-TAB n M-TAB M-TAB C-x )}.
9288 Another way is to negate the top three stack entries, then negate
9289 again the top two stack entries: @kbd{C-x ( M-3 n M-2 n C-x )}.
9291 Finally, it turns out that a negative prefix argument causes a
9292 command like @kbd{n} to operate on the specified stack entry only,
9293 which is just what we want: @kbd{C-x ( M-- 3 n C-x )}.
9295 Just for kicks, let's also do it algebraically:
9296 @w{@kbd{C-x ( ' -$$$, $$, $ RET C-x )}}.
9298 @node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
9299 @subsection Programming Tutorial Exercise 3
9302 Each of these functions can be computed using the stack, or using
9303 algebraic entry, whichever way you prefer:
9306 Computing @c{$\displaystyle{\sin x \over x}$}
9309 Using the stack: @kbd{C-x ( RET S TAB / C-x )}.
9311 Using algebraic entry: @kbd{C-x ( ' sin($)/$ RET C-x )}.
9314 Computing the logarithm:
9316 Using the stack: @kbd{C-x ( TAB B C-x )}
9318 Using algebraic entry: @kbd{C-x ( ' log($,$$) RET C-x )}.
9321 Computing the vector of integers:
9323 Using the stack: @kbd{C-x ( 1 RET 1 C-u v x C-x )}. (Recall that
9324 @kbd{C-u v x} takes the vector size, starting value, and increment
9327 Alternatively: @kbd{C-x ( ~ v x C-x )}. (The @kbd{~} key pops a
9328 number from the stack and uses it as the prefix argument for the
9331 Using algebraic entry: @kbd{C-x ( ' index($) RET C-x )}.
9333 @node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
9334 @subsection Programming Tutorial Exercise 4
9337 Here's one way: @kbd{C-x ( RET V R + TAB v l / C-x )}.
9339 @node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
9340 @subsection Programming Tutorial Exercise 5
9344 2: 1 1: 1.61803398502 2: 1.61803398502
9345 1: 20 . 1: 1.61803398875
9348 1 RET 20 Z < & 1 + Z > I H P
9353 This answer is quite accurate.
9355 @node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
9356 @subsection Programming Tutorial Exercise 6
9362 [ [ 0, 1 ] * [a, b] = [b, a + b]
9367 Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @cite{n+1}
9368 and @cite{n+2}. Here's one program that does the job:
9371 C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] RET v u DEL C-x )
9375 This program is quite efficient because Calc knows how to raise a
9376 matrix (or other value) to the power @cite{n} in only @c{$\log_2 n$}
9378 steps. For example, this program can compute the 1000th Fibonacci
9379 number (a 209-digit integer!) in about 10 steps; even though the
9380 @kbd{Z < ... Z >} solution had much simpler steps, it would have
9381 required so many steps that it would not have been practical.
9383 @node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
9384 @subsection Programming Tutorial Exercise 7
9387 The trick here is to compute the harmonic numbers differently, so that
9388 the loop counter itself accumulates the sum of reciprocals. We use
9389 a separate variable to hold the integer counter.
9397 1 t 1 1 RET 4 Z ( t 2 r 1 1 + s 1 & Z )
9402 The body of the loop goes as follows: First save the harmonic sum
9403 so far in variable 2. Then delete it from the stack; the for loop
9404 itself will take care of remembering it for us. Next, recall the
9405 count from variable 1, add one to it, and feed its reciprocal to
9406 the for loop to use as the step value. The for loop will increase
9407 the ``loop counter'' by that amount and keep going until the
9408 loop counter exceeds 4.
9413 1: 3.99498713092 2: 3.99498713092
9421 Thus we find that the 30th harmonic number is 3.99, and the 31st
9422 harmonic number is 4.02.
9424 @node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
9425 @subsection Programming Tutorial Exercise 8
9428 The first step is to compute the derivative @cite{f'(x)} and thus
9429 the formula @c{$\displaystyle{x - {f(x) \over f'(x)}}$}
9430 @cite{x - f(x)/f'(x)}.
9432 (Because this definition is long, it will be repeated in concise form
9433 below. You can use @w{@kbd{M-# m}} to load it from there. While you are
9434 entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9435 keystrokes without executing them. In the following diagrams we'll
9436 pretend Calc actually executed the keystrokes as you typed them,
9437 just for purposes of illustration.)
9441 2: sin(cos(x)) - 0.5 3: 4.5
9442 1: 4.5 2: sin(cos(x)) - 0.5
9443 . 1: -(sin(x) cos(cos(x)))
9446 ' sin(cos(x))-0.5 RET 4.5 m r C-x ( Z ` TAB RET a d x RET
9454 1: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
9461 Now, we enter the loop. We'll use a repeat loop with a 20-repetition
9462 limit just in case the method fails to converge for some reason.
9463 (Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
9464 repetitions are done.)
9468 1: 4.5 3: 4.5 2: 4.5
9469 . 2: x + (sin(cos(x)) ... 1: 5.24196456928
9473 20 Z < RET r 1 TAB s l x RET
9477 This is the new guess for @cite{x}. Now we compare it with the
9478 old one to see if we've converged.
9482 3: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348
9487 RET M-TAB a = Z / Z > Z ' C-x )
9491 The loop converges in just a few steps to this value. To check
9492 the result, we can simply substitute it back into the equation.
9500 RET ' sin(cos($)) RET
9504 Let's test the new definition again:
9516 Once again, here's the full Newton's Method definition:
9520 C-x ( Z ` TAB RET a d x RET / ' x RET TAB - t 1
9521 20 Z < RET r 1 TAB s l x RET
9529 @c [fix-ref Nesting and Fixed Points]
9530 It turns out that Calc has a built-in command for applying a formula
9531 repeatedly until it converges to a number. @xref{Nesting and Fixed Points},
9532 to see how to use it.
9534 @c [fix-ref Root Finding]
9535 Also, of course, @kbd{a R} is a built-in command that uses Newton's
9536 method (among others) to look for numerical solutions to any equation.
9537 @xref{Root Finding}.
9539 @node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
9540 @subsection Programming Tutorial Exercise 9
9543 The first step is to adjust @cite{z} to be greater than 5. A simple
9544 ``for'' loop will do the job here. If @cite{z} is less than 5, we
9545 reduce the problem using @c{$\psi(z) = \psi(z+1) - 1/z$}
9546 @cite{psi(z) = psi(z+1) - 1/z}. We go
9547 on to compute @c{$\psi(z+1)$}
9548 @cite{psi(z+1)}, and remember to add back a factor of
9549 @cite{-1/z} when we're done. This step is repeated until @cite{z > 5}.
9551 (Because this definition is long, it will be repeated in concise form
9552 below. You can use @w{@kbd{M-# m}} to load it from there. While you are
9553 entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9554 keystrokes without executing them. In the following diagrams we'll
9555 pretend Calc actually executed the keystrokes as you typed them,
9556 just for purposes of illustration.)
9563 1.0 RET C-x ( Z ` s 1 0 t 2
9567 Here, variable 1 holds @cite{z} and variable 2 holds the adjustment
9568 factor. If @cite{z < 5}, we use a loop to increase it.
9570 (By the way, we started with @samp{1.0} instead of the integer 1 because
9571 otherwise the calculation below will try to do exact fractional arithmetic,
9572 and will never converge because fractions compare equal only if they
9573 are exactly equal, not just equal to within the current precision.)
9582 RET 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9586 Now we compute the initial part of the sum: @c{$\ln z - {1 \over 2z}$}
9588 minus the adjustment factor.
9592 2: 1.79175946923 2: 1.7084261359 1: -0.57490719743
9593 1: 0.0833333333333 1: 2.28333333333 .
9600 Now we evaluate the series. We'll use another ``for'' loop counting
9601 up the value of @cite{2 n}. (Calc does have a summation command,
9602 @kbd{a +}, but we'll use loops just to get more practice with them.)
9606 3: -0.5749 3: -0.5749 4: -0.5749 2: -0.5749
9607 2: 2 2: 1:6 3: 1:6 1: 2.3148e-3
9612 2 RET 40 Z ( RET k b TAB RET r 1 TAB ^ * /
9619 3: -0.5749 3: -0.5772 2: -0.5772 1: -0.577215664892
9620 2: -0.5749 2: -0.5772 1: 0 .
9621 1: 2.3148e-3 1: -0.5749 .
9624 TAB RET M-TAB - RET M-TAB a = Z / 2 Z ) Z ' C-x )
9628 This is the value of @c{$-\gamma$}
9629 @cite{- gamma}, with a slight bit of roundoff error.
9630 To get a full 12 digits, let's use a higher precision:
9634 2: -0.577215664892 2: -0.577215664892
9635 1: 1. 1: -0.577215664901532
9641 Here's the complete sequence of keystrokes:
9646 RET 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9648 2 RET 40 Z ( RET k b TAB RET r 1 TAB ^ * /
9649 TAB RET M-TAB - RET M-TAB a = Z /
9656 @node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
9657 @subsection Programming Tutorial Exercise 10
9660 Taking the derivative of a term of the form @cite{x^n} will produce
9661 a term like @c{$n x^{n-1}$}
9662 @cite{n x^(n-1)}. Taking the derivative of a constant
9663 produces zero. From this it is easy to see that the @cite{n}th
9664 derivative of a polynomial, evaluated at @cite{x = 0}, will equal the
9665 coefficient on the @cite{x^n} term times @cite{n!}.
9667 (Because this definition is long, it will be repeated in concise form
9668 below. You can use @w{@kbd{M-# m}} to load it from there. While you are
9669 entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9670 keystrokes without executing them. In the following diagrams we'll
9671 pretend Calc actually executed the keystrokes as you typed them,
9672 just for purposes of illustration.)
9676 2: 5 x^4 + (x + 1)^2 3: 5 x^4 + (x + 1)^2
9681 ' 5 x^4 + (x+1)^2 RET 6 C-x ( Z ` [ ] t 1 0 TAB
9686 Variable 1 will accumulate the vector of coefficients.
9690 2: 0 3: 0 2: 5 x^4 + ...
9691 1: 5 x^4 + ... 2: 5 x^4 + ... 1: 1
9695 Z ( TAB RET 0 s l x RET M-TAB ! / s | 1
9700 Note that @kbd{s | 1} appends the top-of-stack value to the vector
9701 in a variable; it is completely analogous to @kbd{s + 1}. We could
9702 have written instead, @kbd{r 1 TAB | t 1}.
9706 1: 20 x^3 + 2 x + 2 1: 0 1: [1, 2, 1, 0, 5, 0, 0]
9709 a d x RET 1 Z ) DEL r 1 Z ' C-x )
9713 To convert back, a simple method is just to map the coefficients
9714 against a table of powers of @cite{x}.
9718 2: [1, 2, 1, 0, 5, 0, 0] 2: [1, 2, 1, 0, 5, 0, 0]
9719 1: 6 1: [0, 1, 2, 3, 4, 5, 6]
9722 6 RET 1 + 0 RET 1 C-u v x
9729 2: [1, 2, 1, 0, 5, 0, 0] 2: 1 + 2 x + x^2 + 5 x^4
9730 1: [1, x, x^2, x^3, ... ] .
9737 Once again, here are the whole polynomial to/from vector programs:
9741 C-x ( Z ` [ ] t 1 0 TAB
9742 Z ( TAB RET 0 s l x RET M-TAB ! / s | 1
9748 C-x ( 1 + 0 RET 1 C-u v x ' x RET TAB V M ^ * C-x )
9752 @node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
9753 @subsection Programming Tutorial Exercise 11
9756 First we define a dummy program to go on the @kbd{z s} key. The true
9757 @w{@kbd{z s}} key is supposed to take two numbers from the stack and
9758 return one number, so @kbd{DEL} as a dummy definition will make
9759 sure the stack comes out right.
9767 4 RET 2 C-x ( DEL C-x ) Z K s RET 2
9771 The last step replaces the 2 that was eaten during the creation
9772 of the dummy @kbd{z s} command. Now we move on to the real
9773 definition. The recurrence needs to be rewritten slightly,
9774 to the form @cite{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
9776 (Because this definition is long, it will be repeated in concise form
9777 below. You can use @kbd{M-# m} to load it from there.)
9787 C-x ( M-2 RET a = Z [ DEL DEL 1 Z :
9794 4: 4 2: 4 2: 3 4: 3 4: 3 3: 3
9795 3: 2 1: 2 1: 2 3: 2 3: 2 2: 2
9796 2: 2 . . 2: 3 2: 3 1: 3
9800 RET 0 a = Z [ DEL DEL 0 Z : TAB 1 - TAB M-2 RET 1 - z s
9805 (Note that the value 3 that our dummy @kbd{z s} produces is not correct;
9806 it is merely a placeholder that will do just as well for now.)
9810 3: 3 4: 3 3: 3 2: 3 1: -6
9811 2: 3 3: 3 2: 3 1: 9 .
9816 M-TAB M-TAB TAB RET M-TAB z s * -
9823 1: -6 2: 4 1: 11 2: 11
9827 Z ] Z ] C-x ) Z K s RET DEL 4 RET 2 z s M-RET k s
9831 Even though the result that we got during the definition was highly
9832 bogus, once the definition is complete the @kbd{z s} command gets
9835 Here's the full program once again:
9843 Z : TAB 1 - TAB M-2 RET 1 - z s
9844 M-TAB M-TAB TAB RET M-TAB z s * -
9851 You can read this definition using @kbd{M-# m} (@code{read-kbd-macro})
9852 followed by @kbd{Z K s}, without having to make a dummy definition
9853 first, because @code{read-kbd-macro} doesn't need to execute the
9854 definition as it reads it in. For this reason, @code{M-# m} is often
9855 the easiest way to create recursive programs in Calc.
9857 @node Programming Answer 12, , Programming Answer 11, Answers to Exercises
9858 @subsection Programming Tutorial Exercise 12
9861 This turns out to be a much easier way to solve the problem. Let's
9862 denote Stirling numbers as calls of the function @samp{s}.
9864 First, we store the rewrite rules corresponding to the definition of
9865 Stirling numbers in a convenient variable:
9868 s e StirlingRules RET
9869 [ s(n,n) := 1 :: n >= 0,
9870 s(n,0) := 0 :: n > 0,
9871 s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
9875 Now, it's just a matter of applying the rules:
9879 2: 4 1: s(4, 2) 1: 11
9883 4 RET 2 C-x ( ' s($$,$) RET a r StirlingRules RET C-x )
9887 As in the case of the @code{fib} rules, it would be useful to put these
9888 rules in @code{EvalRules} and to add a @samp{:: remember} condition to
9891 @c This ends the table-of-contents kludge from above:
9893 \global\let\chapternofonts=\oldchapternofonts
9898 @node Introduction, Data Types, Tutorial, Top
9899 @chapter Introduction
9902 This chapter is the beginning of the Calc reference manual.
9903 It covers basic concepts such as the stack, algebraic and
9904 numeric entry, undo, numeric prefix arguments, etc.
9907 @c (Chapter 2, the Tutorial, has been printed in a separate volume.)
9915 * Quick Calculator::
9917 * Prefix Arguments::
9920 * Multiple Calculators::
9921 * Troubleshooting Commands::
9924 @node Basic Commands, Help Commands, Introduction, Introduction
9925 @section Basic Commands
9930 @cindex Starting the Calculator
9931 @cindex Running the Calculator
9932 To start the Calculator in its standard interface, type @kbd{M-x calc}.
9933 By default this creates a pair of small windows, @samp{*Calculator*}
9934 and @samp{*Calc Trail*}. The former displays the contents of the
9935 Calculator stack and is manipulated exclusively through Calc commands.
9936 It is possible (though not usually necessary) to create several Calc
9937 Mode buffers each of which has an independent stack, undo list, and
9938 mode settings. There is exactly one Calc Trail buffer; it records a
9939 list of the results of all calculations that have been done. The
9940 Calc Trail buffer uses a variant of Calc Mode, so Calculator commands
9941 still work when the trail buffer's window is selected. It is possible
9942 to turn the trail window off, but the @samp{*Calc Trail*} buffer itself
9943 still exists and is updated silently. @xref{Trail Commands}.@refill
9949 In most installations, the @kbd{M-# c} key sequence is a more
9950 convenient way to start the Calculator. Also, @kbd{M-# M-#} and
9951 @kbd{M-# #} are synonyms for @kbd{M-# c} unless you last used Calc
9952 in its ``keypad'' mode.
9956 @pindex calc-execute-extended-command
9957 Most Calc commands use one or two keystrokes. Lower- and upper-case
9958 letters are distinct. Commands may also be entered in full @kbd{M-x} form;
9959 for some commands this is the only form. As a convenience, the @kbd{x}
9960 key (@code{calc-execute-extended-command})
9961 is like @kbd{M-x} except that it enters the initial string @samp{calc-}
9962 for you. For example, the following key sequences are equivalent:
9963 @kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.@refill
9965 @cindex Extensions module
9966 @cindex @file{calc-ext} module
9967 The Calculator exists in many parts. When you type @kbd{M-# c}, the
9968 Emacs ``auto-load'' mechanism will bring in only the first part, which
9969 contains the basic arithmetic functions. The other parts will be
9970 auto-loaded the first time you use the more advanced commands like trig
9971 functions or matrix operations. This is done to improve the response time
9972 of the Calculator in the common case when all you need to do is a
9973 little arithmetic. If for some reason the Calculator fails to load an
9974 extension module automatically, you can force it to load all the
9975 extensions by using the @kbd{M-# L} (@code{calc-load-everything})
9976 command. @xref{Mode Settings}.@refill
9978 If you type @kbd{M-x calc} or @kbd{M-# c} with any numeric prefix argument,
9979 the Calculator is loaded if necessary, but it is not actually started.
9980 If the argument is positive, the @file{calc-ext} extensions are also
9981 loaded if necessary. User-written Lisp code that wishes to make use
9982 of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
9983 to auto-load the Calculator.@refill
9987 If you type @kbd{M-# b}, then next time you use @kbd{M-# c} you
9988 will get a Calculator that uses the full height of the Emacs screen.
9989 When full-screen mode is on, @kbd{M-# c} runs the @code{full-calc}
9990 command instead of @code{calc}. From the Unix shell you can type
9991 @samp{emacs -f full-calc} to start a new Emacs specifically for use
9992 as a calculator. When Calc is started from the Emacs command line
9993 like this, Calc's normal ``quit'' commands actually quit Emacs itself.
9996 @pindex calc-other-window
9997 The @kbd{M-# o} command is like @kbd{M-# c} except that the Calc
9998 window is not actually selected. If you are already in the Calc
9999 window, @kbd{M-# o} switches you out of it. (The regular Emacs
10000 @kbd{C-x o} command would also work for this, but it has a
10001 tendency to drop you into the Calc Trail window instead, which
10002 @kbd{M-# o} takes care not to do.)
10005 For one quick calculation, you can type @kbd{M-# q} (@code{quick-calc})
10006 which prompts you for a formula (like @samp{2+3/4}). The result is
10007 displayed at the bottom of the Emacs screen without ever creating
10008 any special Calculator windows. @xref{Quick Calculator}.
10011 Finally, if you are using the X window system you may want to try
10012 @kbd{M-# k} (@code{calc-keypad}) which runs Calc with a
10013 ``calculator keypad'' picture as well as a stack display. Click on
10014 the keys with the mouse to operate the calculator. @xref{Keypad Mode}.
10018 @cindex Quitting the Calculator
10019 @cindex Exiting the Calculator
10020 The @kbd{q} key (@code{calc-quit}) exits Calc Mode and closes the
10021 Calculator's window(s). It does not delete the Calculator buffers.
10022 If you type @kbd{M-x calc} again, the Calculator will reappear with the
10023 contents of the stack intact. Typing @kbd{M-# c} or @kbd{M-# M-#}
10024 again from inside the Calculator buffer is equivalent to executing
10025 @code{calc-quit}; you can think of @kbd{M-# M-#} as toggling the
10026 Calculator on and off.@refill
10029 The @kbd{M-# x} command also turns the Calculator off, no matter which
10030 user interface (standard, Keypad, or Embedded) is currently active.
10031 It also cancels @code{calc-edit} mode if used from there.
10034 @pindex calc-refresh
10035 @cindex Refreshing a garbled display
10036 @cindex Garbled displays, refreshing
10037 The @kbd{d SPC} key sequence (@code{calc-refresh}) redraws the contents
10038 of the Calculator buffer from memory. Use this if the contents of the
10039 buffer have been damaged somehow.
10042 The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
10043 ``home'' position at the bottom of the Calculator buffer.
10047 @pindex calc-scroll-left
10048 @pindex calc-scroll-right
10049 @cindex Horizontal scrolling
10051 @cindex Wide text, scrolling
10052 The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
10053 @code{calc-scroll-right}. These are just like the normal horizontal
10054 scrolling commands except that they scroll one half-screen at a time by
10055 default. (Calc formats its output to fit within the bounds of the
10056 window whenever it can.)@refill
10060 @pindex calc-scroll-down
10061 @pindex calc-scroll-up
10062 @cindex Vertical scrolling
10063 The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
10064 and @code{calc-scroll-up}. They scroll up or down by one-half the
10065 height of the Calc window.@refill
10069 The @kbd{M-# 0} command (@code{calc-reset}; that's @kbd{M-#} followed
10070 by a zero) resets the Calculator to its default state. This clears
10071 the stack, resets all the modes, clears the caches (@pxref{Caches}),
10072 and so on. (It does @emph{not} erase the values of any variables.)
10073 With a numeric prefix argument, @kbd{M-# 0} preserves the contents
10074 of the stack but resets everything else.
10076 @pindex calc-version
10077 The @kbd{M-x calc-version} command displays the current version number
10078 of Calc and the name of the person who installed it on your system.
10079 (This information is also present in the @samp{*Calc Trail*} buffer,
10080 and in the output of the @kbd{h h} command.)
10082 @node Help Commands, Stack Basics, Basic Commands, Introduction
10083 @section Help Commands
10086 @cindex Help commands
10089 The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
10090 Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs'
10091 @key{ESC} and @kbd{C-x} prefixes. You can type
10092 @kbd{?} after a prefix to see a list of commands beginning with that
10093 prefix. (If the message includes @samp{[MORE]}, press @kbd{?} again
10094 to see additional commands for that prefix.)
10097 @pindex calc-full-help
10098 The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
10099 responses at once. When printed, this makes a nice, compact (three pages)
10100 summary of Calc keystrokes.
10102 In general, the @kbd{h} key prefix introduces various commands that
10103 provide help within Calc. Many of the @kbd{h} key functions are
10104 Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
10110 The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
10111 to read this manual on-line. This is basically the same as typing
10112 @kbd{C-h i} (the regular way to run the Info system), then, if Info
10113 is not already in the Calc manual, selecting the beginning of the
10114 manual. The @kbd{M-# i} command is another way to read the Calc
10115 manual; it is different from @kbd{h i} in that it works any time,
10116 not just inside Calc. The plain @kbd{i} key is also equivalent to
10117 @kbd{h i}, though this key is obsolete and may be replaced with a
10118 different command in a future version of Calc.
10122 @pindex calc-tutorial
10123 The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
10124 the Tutorial section of the Calc manual. It is like @kbd{h i},
10125 except that it selects the starting node of the tutorial rather
10126 than the beginning of the whole manual. (It actually selects the
10127 node ``Interactive Tutorial'' which tells a few things about
10128 using the Info system before going on to the actual tutorial.)
10129 The @kbd{M-# t} key is equivalent to @kbd{h t} (but it works at
10134 @pindex calc-info-summary
10135 The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
10136 on the Summary node of the Calc manual. @xref{Summary}. The @kbd{M-# s}
10137 key is equivalent to @kbd{h s}.
10140 @pindex calc-describe-key
10141 The @kbd{h k} (@code{calc-describe-key}) command looks up a key
10142 sequence in the Calc manual. For example, @kbd{h k H a S} looks
10143 up the documentation on the @kbd{H a S} (@code{calc-solve-for})
10144 command. This works by looking up the textual description of
10145 the key(s) in the Key Index of the manual, then jumping to the
10146 node indicated by the index.
10148 Most Calc commands do not have traditional Emacs documentation
10149 strings, since the @kbd{h k} command is both more convenient and
10150 more instructive. This means the regular Emacs @kbd{C-h k}
10151 (@code{describe-key}) command will not be useful for Calc keystrokes.
10154 @pindex calc-describe-key-briefly
10155 The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
10156 key sequence and displays a brief one-line description of it at
10157 the bottom of the screen. It looks for the key sequence in the
10158 Summary node of the Calc manual; if it doesn't find the sequence
10159 there, it acts just like its regular Emacs counterpart @kbd{C-h c}
10160 (@code{describe-key-briefly}). For example, @kbd{h c H a S}
10161 gives the description:
10164 H a S runs calc-solve-for: a `H a S' v => fsolve(a,v) (?=notes)
10168 which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
10169 takes a value @cite{a} from the stack, prompts for a value @cite{v},
10170 then applies the algebraic function @code{fsolve} to these values.
10171 The @samp{?=notes} message means you can now type @kbd{?} to see
10172 additional notes from the summary that apply to this command.
10175 @pindex calc-describe-function
10176 The @kbd{h f} (@code{calc-describe-function}) command looks up an
10177 algebraic function or a command name in the Calc manual. The
10178 prompt initially contains @samp{calcFunc-}; follow this with an
10179 algebraic function name to look up that function in the Function
10180 Index. Or, backspace and enter a command name beginning with
10181 @samp{calc-} to look it up in the Command Index. This command
10182 will also look up operator symbols that can appear in algebraic
10183 formulas, like @samp{%} and @samp{=>}.
10186 @pindex calc-describe-variable
10187 The @kbd{h v} (@code{calc-describe-variable}) command looks up a
10188 variable in the Calc manual. The prompt initially contains the
10189 @samp{var-} prefix; just add a variable name like @code{pi} or
10190 @code{PlotRejects}.
10193 @pindex describe-bindings
10194 The @kbd{h b} (@code{calc-describe-bindings}) command is just like
10195 @kbd{C-h b}, except that only local (Calc-related) key bindings are
10199 The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
10200 the ``news'' or change history of Calc. This is kept in the file
10201 @file{README}, which Calc looks for in the same directory as the Calc
10207 The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
10208 distribution, and warranty information about Calc. These work by
10209 pulling up the appropriate parts of the ``Copying'' or ``Reporting
10210 Bugs'' sections of the manual.
10212 @node Stack Basics, Numeric Entry, Help Commands, Introduction
10213 @section Stack Basics
10216 @cindex Stack basics
10217 @c [fix-tut RPN Calculations and the Stack]
10218 Calc uses RPN notation. If you are not familar with RPN, @pxref{RPN
10221 To add the numbers 1 and 2 in Calc you would type the keys:
10222 @kbd{1 @key{RET} 2 +}.
10223 (@key{RET} corresponds to the @key{ENTER} key on most calculators.)
10224 The first three keystrokes ``push'' the numbers 1 and 2 onto the stack. The
10225 @kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
10226 and pushes the result (3) back onto the stack. This number is ready for
10227 further calculations: @kbd{5 -} pushes 5 onto the stack, then pops the
10228 3 and 5, subtracts them, and pushes the result (@i{-2}).@refill
10230 Note that the ``top'' of the stack actually appears at the @emph{bottom}
10231 of the buffer. A line containing a single @samp{.} character signifies
10232 the end of the buffer; Calculator commands operate on the number(s)
10233 directly above this line. The @kbd{d t} (@code{calc-truncate-stack})
10234 command allows you to move the @samp{.} marker up and down in the stack;
10235 @pxref{Truncating the Stack}.
10238 @pindex calc-line-numbering
10239 Stack elements are numbered consecutively, with number 1 being the top of
10240 the stack. These line numbers are ordinarily displayed on the lefthand side
10241 of the window. The @kbd{d l} (@code{calc-line-numbering}) command controls
10242 whether these numbers appear. (Line numbers may be turned off since they
10243 slow the Calculator down a bit and also clutter the display.)
10246 @pindex calc-realign
10247 The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
10248 the cursor to its top-of-stack ``home'' position. It also undoes any
10249 horizontal scrolling in the window. If you give it a numeric prefix
10250 argument, it instead moves the cursor to the specified stack element.
10252 The @key{RET} (or equivalent @key{SPC}) key is only required to separate
10253 two consecutive numbers.
10254 (After all, if you typed @kbd{1 2} by themselves the Calculator
10255 would enter the number 12.) If you press @kbd{RET} or @kbd{SPC} @emph{not}
10256 right after typing a number, the key duplicates the number on the top of
10257 the stack. @kbd{@key{RET} *} is thus a handy way to square a number.@refill
10259 The @key{DEL} key pops and throws away the top number on the stack.
10260 The @key{TAB} key swaps the top two objects on the stack.
10261 @xref{Stack and Trail}, for descriptions of these and other stack-related
10264 @node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
10265 @section Numeric Entry
10271 @cindex Numeric entry
10272 @cindex Entering numbers
10273 Pressing a digit or other numeric key begins numeric entry using the
10274 minibuffer. The number is pushed on the stack when you press the @key{RET}
10275 or @key{SPC} keys. If you press any other non-numeric key, the number is
10276 pushed onto the stack and the appropriate operation is performed. If
10277 you press a numeric key which is not valid, the key is ignored.
10279 @cindex Minus signs
10280 @cindex Negative numbers, entering
10282 There are three different concepts corresponding to the word ``minus,''
10283 typified by @cite{a-b} (subtraction), @cite{-x}
10284 (change-sign), and @cite{-5} (negative number). Calc uses three
10285 different keys for these operations, respectively:
10286 @kbd{-}, @kbd{n}, and @kbd{_} (the underscore). The @kbd{-} key subtracts
10287 the two numbers on the top of the stack. The @kbd{n} key changes the sign
10288 of the number on the top of the stack or the number currently being entered.
10289 The @kbd{_} key begins entry of a negative number or changes the sign of
10290 the number currently being entered. The following sequences all enter the
10291 number @i{-5} onto the stack: @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
10292 @kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.@refill
10294 Some other keys are active during numeric entry, such as @kbd{#} for
10295 non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
10296 These notations are described later in this manual with the corresponding
10297 data types. @xref{Data Types}.
10299 During numeric entry, the only editing key available is @kbd{DEL}.
10301 @node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
10302 @section Algebraic Entry
10306 @pindex calc-algebraic-entry
10307 @cindex Algebraic notation
10308 @cindex Formulas, entering
10309 Calculations can also be entered in algebraic form. This is accomplished
10310 by typing the apostrophe key, @kbd{'}, followed by the expression in
10311 standard format: @kbd{@key{'} 2+3*4 @key{RET}} computes
10312 @c{$2+(3\times4) = 14$}
10313 @cite{2+(3*4) = 14} and pushes that on the stack. If you wish you can
10314 ignore the RPN aspect of Calc altogether and simply enter algebraic
10315 expressions in this way. You may want to use @key{DEL} every so often to
10316 clear previous results off the stack.@refill
10318 You can press the apostrophe key during normal numeric entry to switch
10319 the half-entered number into algebraic entry mode. One reason to do this
10320 would be to use the full Emacs cursor motion and editing keys, which are
10321 available during algebraic entry but not during numeric entry.
10323 In the same vein, during either numeric or algebraic entry you can
10324 press @kbd{`} (backquote) to switch to @code{calc-edit} mode, where
10325 you complete your half-finished entry in a separate buffer.
10326 @xref{Editing Stack Entries}.
10329 @pindex calc-algebraic-mode
10330 @cindex Algebraic mode
10331 If you prefer algebraic entry, you can use the command @kbd{m a}
10332 (@code{calc-algebraic-mode}) to set Algebraic mode. In this mode,
10333 digits and other keys that would normally start numeric entry instead
10334 start full algebraic entry; as long as your formula begins with a digit
10335 you can omit the apostrophe. Open parentheses and square brackets also
10336 begin algebraic entry. You can still do RPN calculations in this mode,
10337 but you will have to press @key{RET} to terminate every number:
10338 @kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
10339 thing as @kbd{2*3+4 @key{RET}}.@refill
10341 @cindex Incomplete algebraic mode
10342 If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
10343 command, it enables Incomplete Algebraic mode; this is like regular
10344 Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
10345 only. Numeric keys still begin a numeric entry in this mode.
10348 @pindex calc-total-algebraic-mode
10349 @cindex Total algebraic mode
10350 The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
10351 stronger algebraic-entry mode, in which @emph{all} regular letter and
10352 punctuation keys begin algebraic entry. Use this if you prefer typing
10353 @w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
10354 @kbd{a f}, and so on. To type regular Calc commands when you are in
10355 ``total'' algebraic mode, hold down the @key{META} key. Thus @kbd{M-q}
10356 is the command to quit Calc, @kbd{M-p} sets the precision, and
10357 @kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns total algebraic
10358 mode back off again. Meta keys also terminate algebraic entry, so
10359 that @kbd{2+3 M-S} is equivalent to @kbd{2+3 RET M-S}. The symbol
10360 @samp{Alg*} will appear in the mode line whenever you are in this mode.
10362 Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
10363 algebraic formula. You can then use the normal Emacs editing keys to
10364 modify this formula to your liking before pressing @key{RET}.
10367 @cindex Formulas, referring to stack
10368 Within a formula entered from the keyboard, the symbol @kbd{$}
10369 represents the number on the top of the stack. If an entered formula
10370 contains any @kbd{$} characters, the Calculator replaces the top of
10371 stack with that formula rather than simply pushing the formula onto the
10372 stack. Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
10373 @key{RET}} replaces it with 6. Note that the @kbd{$} key always
10374 initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
10375 first character in the new formula.@refill
10377 Higher stack elements can be accessed from an entered formula with the
10378 symbols @kbd{$$}, @kbd{$$$}, and so on. The number of stack elements
10379 removed (to be replaced by the entered values) equals the number of dollar
10380 signs in the longest such symbol in the formula. For example, @samp{$$+$$$}
10381 adds the second and third stack elements, replacing the top three elements
10382 with the answer. (All information about the top stack element is thus lost
10383 since no single @samp{$} appears in this formula.)@refill
10385 A slightly different way to refer to stack elements is with a dollar
10386 sign followed by a number: @samp{$1}, @samp{$2}, and so on are much
10387 like @samp{$}, @samp{$$}, etc., except that stack entries referred
10388 to numerically are not replaced by the algebraic entry. That is, while
10389 @samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
10390 on the stack and pushes an additional 6.
10392 If a sequence of formulas are entered separated by commas, each formula
10393 is pushed onto the stack in turn. For example, @samp{1,2,3} pushes
10394 those three numbers onto the stack (leaving the 3 at the top), and
10395 @samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6. Also,
10396 @samp{$,$$} exchanges the top two elements of the stack, just like the
10399 You can finish an algebraic entry with @kbd{M-=} or @kbd{M-RET} instead
10400 of @key{RET}. This uses @kbd{=} to evaluate the variables in each
10401 formula that goes onto the stack. (Thus @kbd{' pi @key{RET}} pushes
10402 the variable @samp{pi}, but @kbd{' pi M-RET} pushes 3.1415.)
10404 If you finish your algebraic entry by pressing @kbd{LFD} (or @kbd{C-j})
10405 instead of @key{RET}, Calc disables the default simplifications
10406 (as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
10407 is being pushed on the stack. Thus @kbd{' 1+2 @key{RET}} pushes 3
10408 on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @cite{1+2};
10409 you might then press @kbd{=} when it is time to evaluate this formula.
10411 @node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
10412 @section ``Quick Calculator'' Mode
10417 @cindex Quick Calculator
10418 There is another way to invoke the Calculator if all you need to do
10419 is make one or two quick calculations. Type @kbd{M-# q} (or
10420 @kbd{M-x quick-calc}), then type any formula as an algebraic entry.
10421 The Calculator will compute the result and display it in the echo
10422 area, without ever actually putting up a Calc window.
10424 You can use the @kbd{$} character in a Quick Calculator formula to
10425 refer to the previous Quick Calculator result. Older results are
10426 not retained; the Quick Calculator has no effect on the full
10427 Calculator's stack or trail. If you compute a result and then
10428 forget what it was, just run @code{M-# q} again and enter
10429 @samp{$} as the formula.
10431 If this is the first time you have used the Calculator in this Emacs
10432 session, the @kbd{M-# q} command will create the @code{*Calculator*}
10433 buffer and perform all the usual initializations; it simply will
10434 refrain from putting that buffer up in a new window. The Quick
10435 Calculator refers to the @code{*Calculator*} buffer for all mode
10436 settings. Thus, for example, to set the precision that the Quick
10437 Calculator uses, simply run the full Calculator momentarily and use
10438 the regular @kbd{p} command.
10440 If you use @code{M-# q} from inside the Calculator buffer, the
10441 effect is the same as pressing the apostrophe key (algebraic entry).
10443 The result of a Quick calculation is placed in the Emacs ``kill ring''
10444 as well as being displayed. A subsequent @kbd{C-y} command will
10445 yank the result into the editing buffer. You can also use this
10446 to yank the result into the next @kbd{M-# q} input line as a more
10447 explicit alternative to @kbd{$} notation, or to yank the result
10448 into the Calculator stack after typing @kbd{M-# c}.
10450 If you finish your formula by typing @key{LFD} (or @kbd{C-j}) instead
10451 of @key{RET}, the result is inserted immediately into the current
10452 buffer rather than going into the kill ring.
10454 Quick Calculator results are actually evaluated as if by the @kbd{=}
10455 key (which replaces variable names by their stored values, if any).
10456 If the formula you enter is an assignment to a variable using the
10457 @samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
10458 then the result of the evaluation is stored in that Calc variable.
10459 @xref{Store and Recall}.
10461 If the result is an integer and the current display radix is decimal,
10462 the number will also be displayed in hex and octal formats. If the
10463 integer is in the range from 1 to 126, it will also be displayed as
10464 an ASCII character.
10466 For example, the quoted character @samp{"x"} produces the vector
10467 result @samp{[120]} (because 120 is the ASCII code of the lower-case
10468 `x'; @pxref{Strings}). Since this is a vector, not an integer, it
10469 is displayed only according to the current mode settings. But
10470 running Quick Calc again and entering @samp{120} will produce the
10471 result @samp{120 (16#78, 8#170, x)} which shows the number in its
10472 decimal, hexadecimal, octal, and ASCII forms.
10474 Please note that the Quick Calculator is not any faster at loading
10475 or computing the answer than the full Calculator; the name ``quick''
10476 merely refers to the fact that it's much less hassle to use for
10477 small calculations.
10479 @node Prefix Arguments, Undo, Quick Calculator, Introduction
10480 @section Numeric Prefix Arguments
10483 Many Calculator commands use numeric prefix arguments. Some, such as
10484 @kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
10485 the prefix argument or use a default if you don't use a prefix.
10486 Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
10487 and prompt for a number if you don't give one as a prefix.@refill
10489 As a rule, stack-manipulation commands accept a numeric prefix argument
10490 which is interpreted as an index into the stack. A positive argument
10491 operates on the top @var{n} stack entries; a negative argument operates
10492 on the @var{n}th stack entry in isolation; and a zero argument operates
10493 on the entire stack.
10495 Most commands that perform computations (such as the arithmetic and
10496 scientific functions) accept a numeric prefix argument that allows the
10497 operation to be applied across many stack elements. For unary operations
10498 (that is, functions of one argument like absolute value or complex
10499 conjugate), a positive prefix argument applies that function to the top
10500 @var{n} stack entries simultaneously, and a negative argument applies it
10501 to the @var{n}th stack entry only. For binary operations (functions of
10502 two arguments like addition, GCD, and vector concatenation), a positive
10503 prefix argument ``reduces'' the function across the top @var{n}
10504 stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
10505 @pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
10506 @var{n} stack elements with the top stack element as a second argument
10507 (for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
10508 This feature is not available for operations which use the numeric prefix
10509 argument for some other purpose.
10511 Numeric prefixes are specified the same way as always in Emacs: Press
10512 a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
10513 or press @kbd{C-u} followed by digits. Some commands treat plain
10514 @kbd{C-u} (without any actual digits) specially.@refill
10517 @pindex calc-num-prefix
10518 You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
10519 top of the stack and enter it as the numeric prefix for the next command.
10520 For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
10521 (silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
10522 to the fourth power and set the precision to that value.@refill
10524 Conversely, if you have typed a numeric prefix argument the @kbd{~} key
10525 pushes it onto the stack in the form of an integer.
10527 @node Undo, Error Messages, Prefix Arguments, Introduction
10528 @section Undoing Mistakes
10534 @cindex Mistakes, undoing
10535 @cindex Undoing mistakes
10536 @cindex Errors, undoing
10537 The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
10538 If that operation added or dropped objects from the stack, those objects
10539 are removed or restored. If it was a ``store'' operation, you are
10540 queried whether or not to restore the variable to its original value.
10541 The @kbd{U} key may be pressed any number of times to undo successively
10542 farther back in time; with a numeric prefix argument it undoes a
10543 specified number of operations. The undo history is cleared only by the
10544 @kbd{q} (@code{calc-quit}) command. (Recall that @kbd{M-# c} is
10545 synonymous with @code{calc-quit} while inside the Calculator; this
10546 also clears the undo history.)
10548 Currently the mode-setting commands (like @code{calc-precision}) are not
10549 undoable. You can undo past a point where you changed a mode, but you
10550 will need to reset the mode yourself.
10554 @cindex Redoing after an Undo
10555 The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
10556 mistakenly undone. Pressing @kbd{U} with a negative prefix argument is
10557 equivalent to executing @code{calc-redo}. You can redo any number of
10558 times, up to the number of recent consecutive undo commands. Redo
10559 information is cleared whenever you give any command that adds new undo
10560 information, i.e., if you undo, then enter a number on the stack or make
10561 any other change, then it will be too late to redo.
10564 @pindex calc-last-args
10565 @cindex Last-arguments feature
10566 @cindex Arguments, restoring
10567 The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
10568 it restores the arguments of the most recent command onto the stack;
10569 however, it does not remove the result of that command. Given a numeric
10570 prefix argument, this command applies to the @cite{n}th most recent
10571 command which removed items from the stack; it pushes those items back
10574 The @kbd{K} (@code{calc-keep-args}) command provides a related function
10575 to @kbd{M-@key{RET}}. @xref{Stack and Trail}.
10577 It is also possible to recall previous results or inputs using the trail.
10578 @xref{Trail Commands}.
10580 The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
10582 @node Error Messages, Multiple Calculators, Undo, Introduction
10583 @section Error Messages
10588 @cindex Errors, messages
10589 @cindex Why did an error occur?
10590 Many situations that would produce an error message in other calculators
10591 simply create unsimplified formulas in the Emacs Calculator. For example,
10592 @kbd{1 @key{RET} 0 /} pushes the formula @cite{1 / 0}; @w{@kbd{0 L}} pushes
10593 the formula @samp{ln(0)}. Floating-point overflow and underflow are also
10594 reasons for this to happen.
10596 When a function call must be left in symbolic form, Calc usually
10597 produces a message explaining why. Messages that are probably
10598 surprising or indicative of user errors are displayed automatically.
10599 Other messages are simply kept in Calc's memory and are displayed only
10600 if you type @kbd{w} (@code{calc-why}). You can also press @kbd{w} if
10601 the same computation results in several messages. (The first message
10602 will end with @samp{[w=more]} in this case.)
10605 @pindex calc-auto-why
10606 The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
10607 are displayed automatically. (Calc effectively presses @kbd{w} for you
10608 after your computation finishes.) By default, this occurs only for
10609 ``important'' messages. The other possible modes are to report
10610 @emph{all} messages automatically, or to report none automatically (so
10611 that you must always press @kbd{w} yourself to see the messages).
10613 @node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
10614 @section Multiple Calculators
10617 @pindex another-calc
10618 It is possible to have any number of Calc Mode buffers at once.
10619 Usually this is done by executing @kbd{M-x another-calc}, which
10620 is similar to @kbd{M-# c} except that if a @samp{*Calculator*}
10621 buffer already exists, a new, independent one with a name of the
10622 form @samp{*Calculator*<@var{n}>} is created. You can also use the
10623 command @code{calc-mode} to put any buffer into Calculator mode, but
10624 this would ordinarily never be done.
10626 The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
10627 it only closes its window. Use @kbd{M-x kill-buffer} to destroy a
10630 Each Calculator buffer keeps its own stack, undo list, and mode settings
10631 such as precision, angular mode, and display formats. In Emacs terms,
10632 variables such as @code{calc-stack} are buffer-local variables. The
10633 global default values of these variables are used only when a new
10634 Calculator buffer is created. The @code{calc-quit} command saves
10635 the stack and mode settings of the buffer being quit as the new defaults.
10637 There is only one trail buffer, @samp{*Calc Trail*}, used by all
10638 Calculator buffers.
10640 @node Troubleshooting Commands, , Multiple Calculators, Introduction
10641 @section Troubleshooting Commands
10644 This section describes commands you can use in case a computation
10645 incorrectly fails or gives the wrong answer.
10647 @xref{Reporting Bugs}, if you find a problem that appears to be due
10648 to a bug or deficiency in Calc.
10651 * Autoloading Problems::
10652 * Recursion Depth::
10657 @node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
10658 @subsection Autoloading Problems
10661 The Calc program is split into many component files; components are
10662 loaded automatically as you use various commands that require them.
10663 Occasionally Calc may lose track of when a certain component is
10664 necessary; typically this means you will type a command and it won't
10665 work because some function you've never heard of was undefined.
10668 @pindex calc-load-everything
10669 If this happens, the easiest workaround is to type @kbd{M-# L}
10670 (@code{calc-load-everything}) to force all the parts of Calc to be
10671 loaded right away. This will cause Emacs to take up a lot more
10672 memory than it would otherwise, but it's guaranteed to fix the problem.
10674 If you seem to run into this problem no matter what you do, or if
10675 even the @kbd{M-# L} command crashes, Calc may have been improperly
10676 installed. @xref{Installation}, for details of the installation
10679 @node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
10680 @subsection Recursion Depth
10685 @pindex calc-more-recursion-depth
10686 @pindex calc-less-recursion-depth
10687 @cindex Recursion depth
10688 @cindex ``Computation got stuck'' message
10689 @cindex @code{max-lisp-eval-depth}
10690 @cindex @code{max-specpdl-size}
10691 Calc uses recursion in many of its calculations. Emacs Lisp keeps a
10692 variable @code{max-lisp-eval-depth} which limits the amount of recursion
10693 possible in an attempt to recover from program bugs. If a calculation
10694 ever halts incorrectly with the message ``Computation got stuck or
10695 ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
10696 to increase this limit. (Of course, this will not help if the
10697 calculation really did get stuck due to some problem inside Calc.)@refill
10699 The limit is always increased (multiplied) by a factor of two. There
10700 is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
10701 decreases this limit by a factor of two, down to a minimum value of 200.
10702 The default value is 1000.
10704 These commands also double or halve @code{max-specpdl-size}, another
10705 internal Lisp recursion limit. The minimum value for this limit is 600.
10707 @node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
10712 @cindex Flushing caches
10713 Calc saves certain values after they have been computed once. For
10714 example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
10716 @cite{pi} to about 20 decimal places; if the current precision
10717 is greater than this, it will recompute @c{$\pi$}
10718 @cite{pi} using a series
10719 approximation. This value will not need to be recomputed ever again
10720 unless you raise the precision still further. Many operations such as
10721 logarithms and sines make use of similarly cached values such as
10723 @cite{pi/4} and @c{$\ln 2$}
10724 @cite{ln(2)}. The visible effect of caching is that
10725 high-precision computations may seem to do extra work the first time.
10726 Other things cached include powers of two (for the binary arithmetic
10727 functions), matrix inverses and determinants, symbolic integrals, and
10728 data points computed by the graphing commands.
10730 @pindex calc-flush-caches
10731 If you suspect a Calculator cache has become corrupt, you can use the
10732 @code{calc-flush-caches} command to reset all caches to the empty state.
10733 (This should only be necessary in the event of bugs in the Calculator.)
10734 The @kbd{M-# 0} (with the zero key) command also resets caches along
10735 with all other aspects of the Calculator's state.
10737 @node Debugging Calc, , Caches, Troubleshooting Commands
10738 @subsection Debugging Calc
10741 A few commands exist to help in the debugging of Calc commands.
10742 @xref{Programming}, to see the various ways that you can write
10743 your own Calc commands.
10746 @pindex calc-timing
10747 The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
10748 in which the timing of slow commands is reported in the Trail.
10749 Any Calc command that takes two seconds or longer writes a line
10750 to the Trail showing how many seconds it took. This value is
10751 accurate only to within one second.
10753 All steps of executing a command are included; in particular, time
10754 taken to format the result for display in the stack and trail is
10755 counted. Some prompts also count time taken waiting for them to
10756 be answered, while others do not; this depends on the exact
10757 implementation of the command. For best results, if you are timing
10758 a sequence that includes prompts or multiple commands, define a
10759 keyboard macro to run the whole sequence at once. Calc's @kbd{X}
10760 command (@pxref{Keyboard Macros}) will then report the time taken
10761 to execute the whole macro.
10763 Another advantage of the @kbd{X} command is that while it is
10764 executing, the stack and trail are not updated from step to step.
10765 So if you expect the output of your test sequence to leave a result
10766 that may take a long time to format and you don't wish to count
10767 this formatting time, end your sequence with a @key{DEL} keystroke
10768 to clear the result from the stack. When you run the sequence with
10769 @kbd{X}, Calc will never bother to format the large result.
10771 Another thing @kbd{Z T} does is to increase the Emacs variable
10772 @code{gc-cons-threshold} to a much higher value (two million; the
10773 usual default in Calc is 250,000) for the duration of each command.
10774 This generally prevents garbage collection during the timing of
10775 the command, though it may cause your Emacs process to grow
10776 abnormally large. (Garbage collection time is a major unpredictable
10777 factor in the timing of Emacs operations.)
10779 Another command that is useful when debugging your own Lisp
10780 extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
10781 the error handler that changes the ``@code{max-lisp-eval-depth}
10782 exceeded'' message to the much more friendly ``Computation got
10783 stuck or ran too long.'' This handler interferes with the Emacs
10784 Lisp debugger's @code{debug-on-error} mode. Errors are reported
10785 in the handler itself rather than at the true location of the
10786 error. After you have executed @code{calc-pass-errors}, Lisp
10787 errors will be reported correctly but the user-friendly message
10790 @node Data Types, Stack and Trail, Introduction, Top
10791 @chapter Data Types
10794 This chapter discusses the various types of objects that can be placed
10795 on the Calculator stack, how they are displayed, and how they are
10796 entered. (@xref{Data Type Formats}, for information on how these data
10797 types are represented as underlying Lisp objects.)@refill
10799 Integers, fractions, and floats are various ways of describing real
10800 numbers. HMS forms also for many purposes act as real numbers. These
10801 types can be combined to form complex numbers, modulo forms, error forms,
10802 or interval forms. (But these last four types cannot be combined
10803 arbitrarily:@: error forms may not contain modulo forms, for example.)
10804 Finally, all these types of numbers may be combined into vectors,
10805 matrices, or algebraic formulas.
10808 * Integers:: The most basic data type.
10809 * Fractions:: This and above are called @dfn{rationals}.
10810 * Floats:: This and above are called @dfn{reals}.
10811 * Complex Numbers:: This and above are called @dfn{numbers}.
10813 * Vectors and Matrices::
10820 * Incomplete Objects::
10825 @node Integers, Fractions, Data Types, Data Types
10830 The Calculator stores integers to arbitrary precision. Addition,
10831 subtraction, and multiplication of integers always yields an exact
10832 integer result. (If the result of a division or exponentiation of
10833 integers is not an integer, it is expressed in fractional or
10834 floating-point form according to the current Fraction Mode.
10835 @xref{Fraction Mode}.)
10837 A decimal integer is represented as an optional sign followed by a
10838 sequence of digits. Grouping (@pxref{Grouping Digits}) can be used to
10839 insert a comma at every third digit for display purposes, but you
10840 must not type commas during the entry of numbers.@refill
10843 A non-decimal integer is represented as an optional sign, a radix
10844 between 2 and 36, a @samp{#} symbol, and one or more digits. For radix 11
10845 and above, the letters A through Z (upper- or lower-case) count as
10846 digits and do not terminate numeric entry mode. @xref{Radix Modes}, for how
10847 to set the default radix for display of integers. Numbers of any radix
10848 may be entered at any time. If you press @kbd{#} at the beginning of a
10849 number, the current display radix is used.@refill
10851 @node Fractions, Floats, Integers, Data Types
10856 A @dfn{fraction} is a ratio of two integers. Fractions are traditionally
10857 written ``2/3'' but Calc uses the notation @samp{2:3}. (The @kbd{/} key
10858 performs RPN division; the following two sequences push the number
10859 @samp{2:3} on the stack: @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
10860 assuming Fraction Mode has been enabled.)
10861 When the Calculator produces a fractional result it always reduces it to
10862 simplest form, which may in fact be an integer.@refill
10864 Fractions may also be entered in a three-part form, where @samp{2:3:4}
10865 represents two-and-three-quarters. @xref{Fraction Formats}, for fraction
10866 display formats.@refill
10868 Non-decimal fractions are entered and displayed as
10869 @samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
10870 form). The numerator and denominator always use the same radix.@refill
10872 @node Floats, Complex Numbers, Fractions, Data Types
10876 @cindex Floating-point numbers
10877 A floating-point number or @dfn{float} is a number stored in scientific
10878 notation. The number of significant digits in the fractional part is
10879 governed by the current floating precision (@pxref{Precision}). The
10880 range of acceptable values is from @c{$10^{-3999999}$}
10881 @cite{10^-3999999} (inclusive)
10882 to @c{$10^{4000000}$}
10884 (exclusive), plus the corresponding negative
10887 Calculations that would exceed the allowable range of values (such
10888 as @samp{exp(exp(20))}) are left in symbolic form by Calc. The
10889 messages ``floating-point overflow'' or ``floating-point underflow''
10890 indicate that during the calculation a number would have been produced
10891 that was too large or too close to zero, respectively, to be represented
10892 by Calc. This does not necessarily mean the final result would have
10893 overflowed, just that an overflow occurred while computing the result.
10894 (In fact, it could report an underflow even though the final result
10895 would have overflowed!)
10897 If a rational number and a float are mixed in a calculation, the result
10898 will in general be expressed as a float. Commands that require an integer
10899 value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
10900 floats, i.e., floating-point numbers with nothing after the decimal point.
10902 Floats are identified by the presence of a decimal point and/or an
10903 exponent. In general a float consists of an optional sign, digits
10904 including an optional decimal point, and an optional exponent consisting
10905 of an @samp{e}, an optional sign, and up to seven exponent digits.
10906 For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
10909 Floating-point numbers are normally displayed in decimal notation with
10910 all significant figures shown. Exceedingly large or small numbers are
10911 displayed in scientific notation. Various other display options are
10912 available. @xref{Float Formats}.
10914 @cindex Accuracy of calculations
10915 Floating-point numbers are stored in decimal, not binary. The result
10916 of each operation is rounded to the nearest value representable in the
10917 number of significant digits specified by the current precision,
10918 rounding away from zero in the case of a tie. Thus (in the default
10919 display mode) what you see is exactly what you get. Some operations such
10920 as square roots and transcendental functions are performed with several
10921 digits of extra precision and then rounded down, in an effort to make the
10922 final result accurate to the full requested precision. However,
10923 accuracy is not rigorously guaranteed. If you suspect the validity of a
10924 result, try doing the same calculation in a higher precision. The
10925 Calculator's arithmetic is not intended to be IEEE-conformant in any
10928 While floats are always @emph{stored} in decimal, they can be entered
10929 and displayed in any radix just like integers and fractions. The
10930 notation @samp{@var{radix}#@var{ddd}.@var{ddd}} is a floating-point
10931 number whose digits are in the specified radix. Note that the @samp{.}
10932 is more aptly referred to as a ``radix point'' than as a decimal
10933 point in this case. The number @samp{8#123.4567} is defined as
10934 @samp{8#1234567 * 8^-4}. If the radix is 14 or less, you can use
10935 @samp{e} notation to write a non-decimal number in scientific notation.
10936 The exponent is written in decimal, and is considered to be a power
10937 of the radix: @samp{8#1234567e-4}. If the radix is 15 or above, the
10938 letter @samp{e} is a digit, so scientific notation must be written
10939 out, e.g., @samp{16#123.4567*16^2}. The first two exercises of the
10940 Modes Tutorial explore some of the properties of non-decimal floats.
10942 @node Complex Numbers, Infinities, Floats, Data Types
10943 @section Complex Numbers
10946 @cindex Complex numbers
10947 There are two supported formats for complex numbers: rectangular and
10948 polar. The default format is rectangular, displayed in the form
10949 @samp{(@var{real},@var{imag})} where @var{real} is the real part and
10950 @var{imag} is the imaginary part, each of which may be any real number.
10951 Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
10952 notation; @pxref{Complex Formats}.@refill
10954 Polar complex numbers are displayed in the form `@t{(}@var{r}@t{;}@c{$\theta$}
10956 where @var{r} is the nonnegative magnitude and @c{$\theta$}
10957 @var{theta} is the argument
10958 or phase angle. The range of @c{$\theta$}
10959 @var{theta} depends on the current angular
10960 mode (@pxref{Angular Modes}); it is generally between @i{-180} and
10961 @i{+180} degrees or the equivalent range in radians.@refill
10963 Complex numbers are entered in stages using incomplete objects.
10964 @xref{Incomplete Objects}.
10966 Operations on rectangular complex numbers yield rectangular complex
10967 results, and similarly for polar complex numbers. Where the two types
10968 are mixed, or where new complex numbers arise (as for the square root of
10969 a negative real), the current @dfn{Polar Mode} is used to determine the
10970 type. @xref{Polar Mode}.
10972 A complex result in which the imaginary part is zero (or the phase angle
10973 is 0 or 180 degrees or @c{$\pi$}
10974 @cite{pi} radians) is automatically converted to a real
10977 @node Infinities, Vectors and Matrices, Complex Numbers, Data Types
10978 @section Infinities
10982 @cindex @code{inf} variable
10983 @cindex @code{uinf} variable
10984 @cindex @code{nan} variable
10988 The word @code{inf} represents the mathematical concept of @dfn{infinity}.
10989 Calc actually has three slightly different infinity-like values:
10990 @code{inf}, @code{uinf}, and @code{nan}. These are just regular
10991 variable names (@pxref{Variables}); you should avoid using these
10992 names for your own variables because Calc gives them special
10993 treatment. Infinities, like all variable names, are normally
10994 entered using algebraic entry.
10996 Mathematically speaking, it is not rigorously correct to treat
10997 ``infinity'' as if it were a number, but mathematicians often do
10998 so informally. When they say that @samp{1 / inf = 0}, what they
10999 really mean is that @cite{1 / x}, as @cite{x} becomes larger and
11000 larger, becomes arbitrarily close to zero. So you can imagine
11001 that if @cite{x} got ``all the way to infinity,'' then @cite{1 / x}
11002 would go all the way to zero. Similarly, when they say that
11003 @samp{exp(inf) = inf}, they mean that @c{$e^x$}
11004 @cite{exp(x)} grows without
11005 bound as @cite{x} grows. The symbol @samp{-inf} likewise stands
11006 for an infinitely negative real value; for example, we say that
11007 @samp{exp(-inf) = 0}. You can have an infinity pointing in any
11008 direction on the complex plane: @samp{sqrt(-inf) = i inf}.
11010 The same concept of limits can be used to define @cite{1 / 0}. We
11011 really want the value that @cite{1 / x} approaches as @cite{x}
11012 approaches zero. But if all we have is @cite{1 / 0}, we can't
11013 tell which direction @cite{x} was coming from. If @cite{x} was
11014 positive and decreasing toward zero, then we should say that
11015 @samp{1 / 0 = inf}. But if @cite{x} was negative and increasing
11016 toward zero, the answer is @samp{1 / 0 = -inf}. In fact, @cite{x}
11017 could be an imaginary number, giving the answer @samp{i inf} or
11018 @samp{-i inf}. Calc uses the special symbol @samp{uinf} to mean
11019 @dfn{undirected infinity}, i.e., a value which is infinitely
11020 large but with an unknown sign (or direction on the complex plane).
11022 Calc actually has three modes that say how infinities are handled.
11023 Normally, infinities never arise from calculations that didn't
11024 already have them. Thus, @cite{1 / 0} is treated simply as an
11025 error and left unevaluated. The @kbd{m i} (@code{calc-infinite-mode})
11026 command (@pxref{Infinite Mode}) enables a mode in which
11027 @cite{1 / 0} evaluates to @code{uinf} instead. There is also
11028 an alternative type of infinite mode which says to treat zeros
11029 as if they were positive, so that @samp{1 / 0 = inf}. While this
11030 is less mathematically correct, it may be the answer you want in
11033 Since all infinities are ``as large'' as all others, Calc simplifies,
11034 e.g., @samp{5 inf} to @samp{inf}. Another example is
11035 @samp{5 - inf = -inf}, where the @samp{-inf} is so large that
11036 adding a finite number like five to it does not affect it.
11037 Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
11038 that variables like @code{a} always stand for finite quantities.
11039 Just to show that infinities really are all the same size,
11040 note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
11043 It's not so easy to define certain formulas like @samp{0 * inf} and
11044 @samp{inf / inf}. Depending on where these zeros and infinities
11045 came from, the answer could be literally anything. The latter
11046 formula could be the limit of @cite{x / x} (giving a result of one),
11047 or @cite{2 x / x} (giving two), or @cite{x^2 / x} (giving @code{inf}),
11048 or @cite{x / x^2} (giving zero). Calc uses the symbol @code{nan}
11049 to represent such an @dfn{indeterminate} value. (The name ``nan''
11050 comes from analogy with the ``NAN'' concept of IEEE standard
11051 arithmetic; it stands for ``Not A Number.'' This is somewhat of a
11052 misnomer, since @code{nan} @emph{does} stand for some number or
11053 infinity, it's just that @emph{which} number it stands for
11054 cannot be determined.) In Calc's notation, @samp{0 * inf = nan}
11055 and @samp{inf / inf = nan}. A few other common indeterminate
11056 expressions are @samp{inf - inf} and @samp{inf ^ 0}. Also,
11057 @samp{0 / 0 = nan} if you have turned on ``infinite mode''
11058 (as described above).
11060 Infinities are especially useful as parts of @dfn{intervals}.
11061 @xref{Interval Forms}.
11063 @node Vectors and Matrices, Strings, Infinities, Data Types
11064 @section Vectors and Matrices
11068 @cindex Plain vectors
11070 The @dfn{vector} data type is flexible and general. A vector is simply a
11071 list of zero or more data objects. When these objects are numbers, the
11072 whole is a vector in the mathematical sense. When these objects are
11073 themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
11074 A vector which is not a matrix is referred to here as a @dfn{plain vector}.
11076 A vector is displayed as a list of values separated by commas and enclosed
11077 in square brackets: @samp{[1, 2, 3]}. Thus the following is a 2 row by
11078 3 column matrix: @samp{[[1, 2, 3], [4, 5, 6]]}. Vectors, like complex
11079 numbers, are entered as incomplete objects. @xref{Incomplete Objects}.
11080 During algebraic entry, vectors are entered all at once in the usual
11081 brackets-and-commas form. Matrices may be entered algebraically as nested
11082 vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
11083 with rows separated by semicolons. The commas may usually be omitted
11084 when entering vectors: @samp{[1 2 3]}. Curly braces may be used in
11085 place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
11088 Traditional vector and matrix arithmetic is also supported;
11089 @pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
11090 Many other operations are applied to vectors element-wise. For example,
11091 the complex conjugate of a vector is a vector of the complex conjugates
11092 of its elements.@refill
11096 Algebraic functions for building vectors include @samp{vec(a, b, c)}
11097 to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an @c{$n\times m$}
11098 @asis{@var{n}x@var{m}}
11099 matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
11100 from 1 to @samp{n}.
11102 @node Strings, HMS Forms, Vectors and Matrices, Data Types
11108 @cindex Character strings
11109 Character strings are not a special data type in the Calculator.
11110 Rather, a string is represented simply as a vector all of whose
11111 elements are integers in the range 0 to 255 (ASCII codes). You can
11112 enter a string at any time by pressing the @kbd{"} key. Quotation
11113 marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
11114 inside strings. Other notations introduced by backslashes are:
11130 Finally, a backslash followed by three octal digits produces any
11131 character from its ASCII code.
11134 @pindex calc-display-strings
11135 Strings are normally displayed in vector-of-integers form. The
11136 @w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
11137 which any vectors of small integers are displayed as quoted strings
11140 The backslash notations shown above are also used for displaying
11141 strings. Characters 128 and above are not translated by Calc; unless
11142 you have an Emacs modified for 8-bit fonts, these will show up in
11143 backslash-octal-digits notation. For characters below 32, and
11144 for character 127, Calc uses the backslash-letter combination if
11145 there is one, or otherwise uses a @samp{\^} sequence.
11147 The only Calc feature that uses strings is @dfn{compositions};
11148 @pxref{Compositions}. Strings also provide a convenient
11149 way to do conversions between ASCII characters and integers.
11153 There is a @code{string} function which provides a different display
11154 format for strings. Basically, @samp{string(@var{s})}, where @var{s}
11155 is a vector of integers in the proper range, is displayed as the
11156 corresponding string of characters with no surrounding quotation
11157 marks or other modifications. Thus @samp{string("ABC")} (or
11158 @samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
11159 This happens regardless of whether @w{@kbd{d "}} has been used. The
11160 only way to turn it off is to use @kbd{d U} (unformatted language
11161 mode) which will display @samp{string("ABC")} instead.
11163 Control characters are displayed somewhat differently by @code{string}.
11164 Characters below 32, and character 127, are shown using @samp{^} notation
11165 (same as shown above, but without the backslash). The quote and
11166 backslash characters are left alone, as are characters 128 and above.
11170 The @code{bstring} function is just like @code{string} except that
11171 the resulting string is breakable across multiple lines if it doesn't
11172 fit all on one line. Potential break points occur at every space
11173 character in the string.
11175 @node HMS Forms, Date Forms, Strings, Data Types
11179 @cindex Hours-minutes-seconds forms
11180 @cindex Degrees-minutes-seconds forms
11181 @dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
11182 argument, the interpretation is Degrees-Minutes-Seconds. All functions
11183 that operate on angles accept HMS forms. These are interpreted as
11184 degrees regardless of the current angular mode. It is also possible to
11185 use HMS as the angular mode so that calculated angles are expressed in
11186 degrees, minutes, and seconds.
11190 @kindex ' (HMS forms)
11192 @kindex " (HMS forms)
11194 @kindex h (HMS forms)
11196 @kindex o (HMS forms)
11198 @kindex m (HMS forms)
11200 @kindex s (HMS forms)
11201 The default format for HMS values is
11202 @samp{@var{hours}@@ @var{mins}' @var{secs}"}. During entry, the letters
11203 @samp{h} (for ``hours'') or
11204 @samp{o} (approximating the ``degrees'' symbol) are accepted as well as
11205 @samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
11206 accepted in place of @samp{"}.
11207 The @var{hours} value is an integer (or integer-valued float).
11208 The @var{mins} value is an integer or integer-valued float between 0 and 59.
11209 The @var{secs} value is a real number between 0 (inclusive) and 60
11210 (exclusive). A positive HMS form is interpreted as @var{hours} +
11211 @var{mins}/60 + @var{secs}/3600. A negative HMS form is interpreted
11212 as @i{- @var{hours}} @i{-} @var{mins}/60 @i{-} @var{secs}/3600.
11213 Display format for HMS forms is quite flexible. @xref{HMS Formats}.@refill
11215 HMS forms can be added and subtracted. When they are added to numbers,
11216 the numbers are interpreted according to the current angular mode. HMS
11217 forms can also be multiplied and divided by real numbers. Dividing
11218 two HMS forms produces a real-valued ratio of the two angles.
11221 @cindex Time of day
11222 Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
11223 the stack as an HMS form.
11225 @node Date Forms, Modulo Forms, HMS Forms, Data Types
11226 @section Date Forms
11230 A @dfn{date form} represents a date and possibly an associated time.
11231 Simple date arithmetic is supported: Adding a number to a date
11232 produces a new date shifted by that many days; adding an HMS form to
11233 a date shifts it by that many hours. Subtracting two date forms
11234 computes the number of days between them (represented as a simple
11235 number). Many other operations, such as multiplying two date forms,
11236 are nonsensical and are not allowed by Calc.
11238 Date forms are entered and displayed enclosed in @samp{< >} brackets.
11239 The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
11240 or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
11241 Input is flexible; date forms can be entered in any of the usual
11242 notations for dates and times. @xref{Date Formats}.
11244 Date forms are stored internally as numbers, specifically the number
11245 of days since midnight on the morning of January 1 of the year 1 AD.
11246 If the internal number is an integer, the form represents a date only;
11247 if the internal number is a fraction or float, the form represents
11248 a date and time. For example, @samp{<6:00am Wed Jan 9, 1991>}
11249 is represented by the number 726842.25. The standard precision of
11250 12 decimal digits is enough to ensure that a (reasonable) date and
11251 time can be stored without roundoff error.
11253 If the current precision is greater than 12, date forms will keep
11254 additional digits in the seconds position. For example, if the
11255 precision is 15, the seconds will keep three digits after the
11256 decimal point. Decreasing the precision below 12 may cause the
11257 time part of a date form to become inaccurate. This can also happen
11258 if astronomically high years are used, though this will not be an
11259 issue in everyday (or even everymillenium) use. Note that date
11260 forms without times are stored as exact integers, so roundoff is
11261 never an issue for them.
11263 You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
11264 (@code{calc-unpack}) commands to get at the numerical representation
11265 of a date form. @xref{Packing and Unpacking}.
11267 Date forms can go arbitrarily far into the future or past. Negative
11268 year numbers represent years BC. Calc uses a combination of the
11269 Gregorian and Julian calendars, following the history of Great
11270 Britain and the British colonies. This is the same calendar that
11271 is used by the @code{cal} program in most Unix implementations.
11273 @cindex Julian calendar
11274 @cindex Gregorian calendar
11275 Some historical background: The Julian calendar was created by
11276 Julius Caesar in the year 46 BC as an attempt to fix the gradual
11277 drift caused by the lack of leap years in the calendar used
11278 until that time. The Julian calendar introduced an extra day in
11279 all years divisible by four. After some initial confusion, the
11280 calendar was adopted around the year we call 8 AD. Some centuries
11281 later it became apparent that the Julian year of 365.25 days was
11282 itself not quite right. In 1582 Pope Gregory XIII introduced the
11283 Gregorian calendar, which added the new rule that years divisible
11284 by 100, but not by 400, were not to be considered leap years
11285 despite being divisible by four. Many countries delayed adoption
11286 of the Gregorian calendar because of religious differences;
11287 in Britain it was put off until the year 1752, by which time
11288 the Julian calendar had fallen eleven days behind the true
11289 seasons. So the switch to the Gregorian calendar in early
11290 September 1752 introduced a discontinuity: The day after
11291 Sep 2, 1752 is Sep 14, 1752. Calc follows this convention.
11292 To take another example, Russia waited until 1918 before
11293 adopting the new calendar, and thus needed to remove thirteen
11294 days (between Feb 1, 1918 and Feb 14, 1918). This means that
11295 Calc's reckoning will be inconsistent with Russian history between
11296 1752 and 1918, and similarly for various other countries.
11298 Today's timekeepers introduce an occasional ``leap second'' as
11299 well, but Calc does not take these minor effects into account.
11300 (If it did, it would have to report a non-integer number of days
11301 between, say, @samp{<12:00am Mon Jan 1, 1900>} and
11302 @samp{<12:00am Sat Jan 1, 2000>}.)
11304 Calc uses the Julian calendar for all dates before the year 1752,
11305 including dates BC when the Julian calendar technically had not
11306 yet been invented. Thus the claim that day number @i{-10000} is
11307 called ``August 16, 28 BC'' should be taken with a grain of salt.
11309 Please note that there is no ``year 0''; the day before
11310 @samp{<Sat Jan 1, +1>} is @samp{<Fri Dec 31, -1>}. These are
11311 days 0 and @i{-1} respectively in Calc's internal numbering scheme.
11313 @cindex Julian day counting
11314 Another day counting system in common use is, confusingly, also
11315 called ``Julian.'' It was invented in 1583 by Joseph Justus
11316 Scaliger, who named it in honor of his father Julius Caesar
11317 Scaliger. For obscure reasons he chose to start his day
11318 numbering on Jan 1, 4713 BC at noon, which in Calc's scheme
11319 is @i{-1721423.5} (recall that Calc starts at midnight instead
11320 of noon). Thus to convert a Calc date code obtained by
11321 unpacking a date form into a Julian day number, simply add
11322 1721423.5. The Julian code for @samp{6:00am Jan 9, 1991}
11323 is 2448265.75. The built-in @kbd{t J} command performs
11324 this conversion for you.
11326 @cindex Unix time format
11327 The Unix operating system measures time as an integer number of
11328 seconds since midnight, Jan 1, 1970. To convert a Calc date
11329 value into a Unix time stamp, first subtract 719164 (the code
11330 for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
11331 seconds in a day) and press @kbd{R} to round to the nearest
11332 integer. If you have a date form, you can simply subtract the
11333 day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
11334 719164. Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
11335 to convert from Unix time to a Calc date form. (Note that
11336 Unix normally maintains the time in the GMT time zone; you may
11337 need to subtract five hours to get New York time, or eight hours
11338 for California time. The same is usually true of Julian day
11339 counts.) The built-in @kbd{t U} command performs these
11342 @node Modulo Forms, Error Forms, Date Forms, Data Types
11343 @section Modulo Forms
11346 @cindex Modulo forms
11347 A @dfn{modulo form} is a real number which is taken modulo (i.e., within
11348 an integer multiple of) some value @cite{M}. Arithmetic modulo @cite{M}
11349 often arises in number theory. Modulo forms are written
11350 `@i{a} @t{mod} @i{M}',
11351 where @cite{a} and @cite{M} are real numbers or HMS forms, and
11353 @cite{0 <= a < @var{M}}.
11354 In many applications @cite{a} and @cite{M} will be
11355 integers but this is not required.@refill
11357 Modulo forms are not to be confused with the modulo operator @samp{%}.
11358 The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
11359 the result 7. Further computations treat this 7 as just a regular integer.
11360 The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
11361 further computations with this value are again reduced modulo 10 so that
11362 the result always lies in the desired range.
11364 When two modulo forms with identical @cite{M}'s are added or multiplied,
11365 the Calculator simply adds or multiplies the values, then reduces modulo
11366 @cite{M}. If one argument is a modulo form and the other a plain number,
11367 the plain number is treated like a compatible modulo form. It is also
11368 possible to raise modulo forms to powers; the result is the value raised
11369 to the power, then reduced modulo @cite{M}. (When all values involved
11370 are integers, this calculation is done much more efficiently than
11371 actually computing the power and then reducing.)
11373 @cindex Modulo division
11374 Two modulo forms `@i{a} @t{mod} @i{M}' and `@i{b} @t{mod} @i{M}'
11375 can be divided if @cite{a}, @cite{b}, and @cite{M} are all
11376 integers. The result is the modulo form which, when multiplied by
11377 `@i{b} @t{mod} @i{M}', produces `@i{a} @t{mod} @i{M}'. If
11378 there is no solution to this equation (which can happen only when
11379 @cite{M} is non-prime), or if any of the arguments are non-integers, the
11380 division is left in symbolic form. Other operations, such as square
11381 roots, are not yet supported for modulo forms. (Note that, although
11382 @w{`@t{(}@i{a} @t{mod} @i{M}@t{)^.5}'} will compute a ``modulo square root''
11383 in the sense of reducing @c{$\sqrt a$}
11384 @cite{sqrt(a)} modulo @cite{M}, this is not a
11385 useful definition from the number-theoretical point of view.)@refill
11388 @kindex M (modulo forms)
11390 @tindex mod (operator)
11391 To create a modulo form during numeric entry, press the shift-@kbd{M}
11392 key to enter the word @samp{mod}. As a special convenience, pressing
11393 shift-@kbd{M} a second time automatically enters the value of @cite{M}
11394 that was most recently used before. During algebraic entry, either
11395 type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
11396 Once again, pressing this a second time enters the current modulo.@refill
11398 You can also use @kbd{v p} and @kbd{%} to modify modulo forms.
11399 @xref{Building Vectors}. @xref{Basic Arithmetic}.
11401 It is possible to mix HMS forms and modulo forms. For example, an
11402 HMS form modulo 24 could be used to manipulate clock times; an HMS
11403 form modulo 360 would be suitable for angles. Making the modulo @cite{M}
11404 also be an HMS form eliminates troubles that would arise if the angular
11405 mode were inadvertently set to Radians, in which case
11406 @w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
11409 Modulo forms cannot have variables or formulas for components. If you
11410 enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
11411 to each of the coefficients: @samp{(1 mod 5) x + (2 mod 5)}.
11415 The algebraic function @samp{makemod(a, m)} builds the modulo form
11416 @w{@samp{a mod m}}.
11418 @node Error Forms, Interval Forms, Modulo Forms, Data Types
11419 @section Error Forms
11422 @cindex Error forms
11423 @cindex Standard deviations
11424 An @dfn{error form} is a number with an associated standard
11425 deviation, as in @samp{2.3 +/- 0.12}. The notation
11426 `@i{x} @t{+/-} @c{$\sigma$}
11427 @asis{sigma}' stands for an uncertain value which follows a normal or
11428 Gaussian distribution of mean @cite{x} and standard deviation or
11429 ``error'' @c{$\sigma$}
11430 @cite{sigma}. Both the mean and the error can be either numbers or
11431 formulas. Generally these are real numbers but the mean may also be
11432 complex. If the error is negative or complex, it is changed to its
11433 absolute value. An error form with zero error is converted to a
11434 regular number by the Calculator.@refill
11436 All arithmetic and transcendental functions accept error forms as input.
11437 Operations on the mean-value part work just like operations on regular
11438 numbers. The error part for any function @cite{f(x)} (such as @c{$\sin x$}
11440 is defined by the error of @cite{x} times the derivative of @cite{f}
11441 evaluated at the mean value of @cite{x}. For a two-argument function
11442 @cite{f(x,y)} (such as addition) the error is the square root of the sum
11443 of the squares of the errors due to @cite{x} and @cite{y}.
11446 f(x \hbox{\code{ +/- }} \sigma)
11447 &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
11448 f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
11449 &= f(x,y) \hbox{\code{ +/- }}
11450 \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
11452 +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
11453 \right| \right)^2 } \cr
11457 definition assumes the errors in @cite{x} and @cite{y} are uncorrelated.
11458 A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
11459 is not the same as @samp{(2 +/- 1)^2}; the former represents the product
11460 of two independent values which happen to have the same probability
11461 distributions, and the latter is the product of one random value with itself.
11462 The former will produce an answer with less error, since on the average
11463 the two independent errors can be expected to cancel out.@refill
11465 Consult a good text on error analysis for a discussion of the proper use
11466 of standard deviations. Actual errors often are neither Gaussian-distributed
11467 nor uncorrelated, and the above formulas are valid only when errors
11468 are small. As an example, the error arising from
11469 `@t{sin(}@i{x} @t{+/-} @c{$\sigma$}
11471 `@c{$\sigma$\nobreak}
11472 @i{sigma} @t{abs(cos(}@i{x}@t{))}'. When @cite{x} is close to zero,
11475 close to one so the error in the sine is close to @c{$\sigma$}
11476 @cite{sigma}; this makes sense, since @c{$\sin x$}
11477 @cite{sin(x)} is approximately @cite{x} near zero, so a given
11478 error in @cite{x} will produce about the same error in the sine. Likewise,
11479 near 90 degrees @c{$\cos x$}
11480 @cite{cos(x)} is nearly zero and so the computed error is
11481 small: The sine curve is nearly flat in that region, so an error in @cite{x}
11482 has relatively little effect on the value of @c{$\sin x$}
11483 @cite{sin(x)}. However, consider
11484 @samp{sin(90 +/- 1000)}. The cosine of 90 is zero, so Calc will report
11485 zero error! We get an obviously wrong result because we have violated
11486 the small-error approximation underlying the error analysis. If the error
11487 in @cite{x} had been small, the error in @c{$\sin x$}
11488 @cite{sin(x)} would indeed have been negligible.@refill
11491 @kindex p (error forms)
11493 To enter an error form during regular numeric entry, use the @kbd{p}
11494 (``plus-or-minus'') key to type the @samp{+/-} symbol. (If you try actually
11495 typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
11496 @kbd{+} command!) Within an algebraic formula, you can press @kbd{M-p} to
11497 type the @samp{+/-} symbol, or type it out by hand.
11499 Error forms and complex numbers can be mixed; the formulas shown above
11500 are used for complex numbers, too; note that if the error part evaluates
11501 to a complex number its absolute value (or the square root of the sum of
11502 the squares of the absolute values of the two error contributions) is
11503 used. Mathematically, this corresponds to a radially symmetric Gaussian
11504 distribution of numbers on the complex plane. However, note that Calc
11505 considers an error form with real components to represent a real number,
11506 not a complex distribution around a real mean.
11508 Error forms may also be composed of HMS forms. For best results, both
11509 the mean and the error should be HMS forms if either one is.
11513 The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
11515 @node Interval Forms, Incomplete Objects, Error Forms, Data Types
11516 @section Interval Forms
11519 @cindex Interval forms
11520 An @dfn{interval} is a subset of consecutive real numbers. For example,
11521 the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
11522 inclusive. If you multiply it by the interval @samp{[0.5 ..@: 2]} you
11523 obtain @samp{[1 ..@: 8]}. This calculation represents the fact that if
11524 you multiply some number in the range @samp{[2 ..@: 4]} by some other
11525 number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
11526 from 1 to 8. Interval arithmetic is used to get a worst-case estimate
11527 of the possible range of values a computation will produce, given the
11528 set of possible values of the input.
11531 Calc supports several varieties of intervals, including @dfn{closed}
11532 intervals of the type shown above, @dfn{open} intervals such as
11533 @samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
11534 @emph{exclusive}, and @dfn{semi-open} intervals in which one end
11535 uses a round parenthesis and the other a square bracket. In mathematical
11537 @samp{[2 ..@: 4]} means @cite{2 <= x <= 4}, whereas
11538 @samp{[2 ..@: 4)} represents @cite{2 <= x < 4},
11539 @samp{(2 ..@: 4]} represents @cite{2 < x <= 4}, and
11540 @samp{(2 ..@: 4)} represents @cite{2 < x < 4}.@refill
11543 Calc supports several varieties of intervals, including \dfn{closed}
11544 intervals of the type shown above, \dfn{open} intervals such as
11545 \samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
11546 \emph{exclusive}, and \dfn{semi-open} intervals in which one end
11547 uses a round parenthesis and the other a square bracket. In mathematical
11550 [2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 \le x \le 4 \cr
11551 [2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 \le x < 4 \cr
11552 (2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 < x \le 4 \cr
11553 (2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 < x < 4 \cr
11557 The lower and upper limits of an interval must be either real numbers
11558 (or HMS or date forms), or symbolic expressions which are assumed to be
11559 real-valued, or @samp{-inf} and @samp{inf}. In general the lower limit
11560 must be less than the upper limit. A closed interval containing only
11561 one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
11562 automatically. An interval containing no values at all (such as
11563 @samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
11564 guaranteed to behave well when used in arithmetic. Note that the
11565 interval @samp{[3 .. inf)} represents all real numbers greater than
11566 or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
11567 In fact, @samp{[-inf .. inf]} represents all real numbers including
11568 the real infinities.
11570 Intervals are entered in the notation shown here, either as algebraic
11571 formulas, or using incomplete forms. (@xref{Incomplete Objects}.)
11572 In algebraic formulas, multiple periods in a row are collected from
11573 left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
11574 rather than @samp{1 ..@: 0.1e2}. Add spaces or zeros if you want to
11575 get the other interpretation. If you omit the lower or upper limit,
11576 a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
11578 ``Infinite mode'' also affects operations on intervals
11579 (@pxref{Infinities}). Calc will always introduce an open infinity,
11580 as in @samp{1 / (0 .. 2] = [0.5 .. inf)}. But closed infinities,
11581 @w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in infinite mode;
11582 otherwise they are left unevaluated. Note that the ``direction'' of
11583 a zero is not an issue in this case since the zero is always assumed
11584 to be continuous with the rest of the interval. For intervals that
11585 contain zero inside them Calc is forced to give the result,
11586 @samp{1 / (-2 .. 2) = [-inf .. inf]}.
11588 While it may seem that intervals and error forms are similar, they are
11589 based on entirely different concepts of inexact quantities. An error
11590 form `@i{x} @t{+/-} @c{$\sigma$}
11591 @i{sigma}' means a variable is random, and its value could
11592 be anything but is ``probably'' within one @c{$\sigma$}
11593 @i{sigma} of the mean value @cite{x}.
11594 An interval `@t{[}@i{a} @t{..@:} @i{b}@t{]}' means a variable's value
11595 is unknown, but guaranteed to lie in the specified range. Error forms
11596 are statistical or ``average case'' approximations; interval arithmetic
11597 tends to produce ``worst case'' bounds on an answer.@refill
11599 Intervals may not contain complex numbers, but they may contain
11600 HMS forms or date forms.
11602 @xref{Set Operations}, for commands that interpret interval forms
11603 as subsets of the set of real numbers.
11607 The algebraic function @samp{intv(n, a, b)} builds an interval form
11608 from @samp{a} to @samp{b}; @samp{n} is an integer code which must
11609 be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
11612 Please note that in fully rigorous interval arithmetic, care would be
11613 taken to make sure that the computation of the lower bound rounds toward
11614 minus infinity, while upper bound computations round toward plus
11615 infinity. Calc's arithmetic always uses a round-to-nearest mode,
11616 which means that roundoff errors could creep into an interval
11617 calculation to produce intervals slightly smaller than they ought to
11618 be. For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
11619 should yield the interval @samp{[1..2]} again, but in fact it yields the
11620 (slightly too small) interval @samp{[1..1.9999999]} due to roundoff
11623 @node Incomplete Objects, Variables, Interval Forms, Data Types
11624 @section Incomplete Objects
11636 @cindex Incomplete vectors
11637 @cindex Incomplete complex numbers
11638 @cindex Incomplete interval forms
11639 When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
11640 vector, respectively, the effect is to push an @dfn{incomplete} complex
11641 number or vector onto the stack. The @kbd{,} key adds the value(s) at
11642 the top of the stack onto the current incomplete object. The @kbd{)}
11643 and @kbd{]} keys ``close'' the incomplete object after adding any values
11644 on the top of the stack in front of the incomplete object.
11646 As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
11647 pushes the vector @samp{[2, 6, 9]} onto the stack. Likewise, @kbd{( 1 , 2 Q )}
11648 pushes the complex number @samp{(1, 1.414)} (approximately).
11650 If several values lie on the stack in front of the incomplete object,
11651 all are collected and appended to the object. Thus the @kbd{,} key
11652 is redundant: @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}. Some people
11653 prefer the equivalent @key{SPC} key to @key{RET}.@refill
11655 As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
11656 @kbd{,} adds a zero or duplicates the preceding value in the list being
11657 formed. Typing @key{DEL} during incomplete entry removes the last item
11661 The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
11662 numbers: @kbd{( 1 ; 2 )}. When entering a vector, @kbd{;} is useful for
11663 creating a matrix. In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
11664 equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
11668 Incomplete entry is also used to enter intervals. For example,
11669 @kbd{[ 2 ..@: 4 )} enters a semi-open interval. Note that when you type
11670 the first period, it will be interpreted as a decimal point, but when
11671 you type a second period immediately afterward, it is re-interpreted as
11672 part of the interval symbol. Typing @kbd{..} corresponds to executing
11673 the @code{calc-dots} command.
11675 If you find incomplete entry distracting, you may wish to enter vectors
11676 and complex numbers as algebraic formulas by pressing the apostrophe key.
11678 @node Variables, Formulas, Incomplete Objects, Data Types
11682 @cindex Variables, in formulas
11683 A @dfn{variable} is somewhere between a storage register on a conventional
11684 calculator, and a variable in a programming language. (In fact, a Calc
11685 variable is really just an Emacs Lisp variable that contains a Calc number
11686 or formula.) A variable's name is normally composed of letters and digits.
11687 Calc also allows apostrophes and @code{#} signs in variable names.
11688 The Calc variable @code{foo} corresponds to the Emacs Lisp variable
11689 @code{var-foo}. Commands like @kbd{s s} (@code{calc-store}) that operate
11690 on variables can be made to use any arbitrary Lisp variable simply by
11691 backspacing over the @samp{var-} prefix in the minibuffer.@refill
11693 In a command that takes a variable name, you can either type the full
11694 name of a variable, or type a single digit to use one of the special
11695 convenience variables @code{var-q0} through @code{var-q9}. For example,
11696 @kbd{3 s s 2} stores the number 3 in variable @code{var-q2}, and
11697 @w{@kbd{3 s s foo @key{RET}}} stores that number in variable
11698 @code{var-foo}.@refill
11700 To push a variable itself (as opposed to the variable's value) on the
11701 stack, enter its name as an algebraic expression using the apostrophe
11702 (@key{'}) key. Variable names in algebraic formulas implicitly have
11703 @samp{var-} prefixed to their names. The @samp{#} character in variable
11704 names used in algebraic formulas corresponds to a dash @samp{-} in the
11705 Lisp variable name. If the name contains any dashes, the prefix @samp{var-}
11706 is @emph{not} automatically added. Thus the two formulas @samp{foo + 1}
11707 and @samp{var#foo + 1} both refer to the same variable.
11710 @pindex calc-evaluate
11711 @cindex Evaluation of variables in a formula
11712 @cindex Variables, evaluation
11713 @cindex Formulas, evaluation
11714 The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
11715 replacing all variables in the formula which have been given values by a
11716 @code{calc-store} or @code{calc-let} command by their stored values.
11717 Other variables are left alone. Thus a variable that has not been
11718 stored acts like an abstract variable in algebra; a variable that has
11719 been stored acts more like a register in a traditional calculator.
11720 With a positive numeric prefix argument, @kbd{=} evaluates the top
11721 @var{n} stack entries; with a negative argument, @kbd{=} evaluates
11722 the @var{n}th stack entry.
11724 @cindex @code{e} variable
11725 @cindex @code{pi} variable
11726 @cindex @code{i} variable
11727 @cindex @code{phi} variable
11728 @cindex @code{gamma} variable
11734 A few variables are called @dfn{special constants}. Their names are
11735 @samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
11736 (@xref{Scientific Functions}.) When they are evaluated with @kbd{=},
11737 their values are calculated if necessary according to the current precision
11738 or complex polar mode. If you wish to use these symbols for other purposes,
11739 simply undefine or redefine them using @code{calc-store}.@refill
11741 The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
11742 infinite or indeterminate values. It's best not to use them as
11743 regular variables, since Calc uses special algebraic rules when
11744 it manipulates them. Calc displays a warning message if you store
11745 a value into any of these special variables.
11747 @xref{Store and Recall}, for a discussion of commands dealing with variables.
11749 @node Formulas, , Variables, Data Types
11754 @cindex Expressions
11755 @cindex Operators in formulas
11756 @cindex Precedence of operators
11757 When you press the apostrophe key you may enter any expression or formula
11758 in algebraic form. (Calc uses the terms ``expression'' and ``formula''
11759 interchangeably.) An expression is built up of numbers, variable names,
11760 and function calls, combined with various arithmetic operators.
11762 be used to indicate grouping. Spaces are ignored within formulas, except
11763 that spaces are not permitted within variable names or numbers.
11764 Arithmetic operators, in order from highest to lowest precedence, and
11765 with their equivalent function names, are:
11767 @samp{_} [@code{subscr}] (subscripts);
11769 postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
11771 prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x})
11772 and prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
11774 @samp{+/-} [@code{sdev}] (the standard deviation symbol) and
11775 @samp{mod} [@code{makemod}] (the symbol for modulo forms);
11777 postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
11778 and postfix @samp{!!} [@code{dfact}] (double factorial);
11780 @samp{^} [@code{pow}] (raised-to-the-power-of);
11782 @samp{*} [@code{mul}];
11784 @samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
11785 @samp{\} [@code{idiv}] (integer division);
11787 infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
11789 @samp{|} [@code{vconcat}] (vector concatenation);
11791 relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
11792 @samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
11794 @samp{&&} [@code{land}] (logical ``and'');
11796 @samp{||} [@code{lor}] (logical ``or'');
11798 the C-style ``if'' operator @samp{a?b:c} [@code{if}];
11800 @samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
11802 @samp{&&&} [@code{pand}] (rewrite pattern ``and'');
11804 @samp{|||} [@code{por}] (rewrite pattern ``or'');
11806 @samp{:=} [@code{assign}] (for assignments and rewrite rules);
11808 @samp{::} [@code{condition}] (rewrite pattern condition);
11810 @samp{=>} [@code{evalto}].
11812 Note that, unlike in usual computer notation, multiplication binds more
11813 strongly than division: @samp{a*b/c*d} is equivalent to @c{$a b \over c d$}
11814 @cite{(a*b)/(c*d)}.
11816 @cindex Multiplication, implicit
11817 @cindex Implicit multiplication
11818 The multiplication sign @samp{*} may be omitted in many cases. In particular,
11819 if the righthand side is a number, variable name, or parenthesized
11820 expression, the @samp{*} may be omitted. Implicit multiplication has the
11821 same precedence as the explicit @samp{*} operator. The one exception to
11822 the rule is that a variable name followed by a parenthesized expression,
11824 is interpreted as a function call, not an implicit @samp{*}. In many
11825 cases you must use a space if you omit the @samp{*}: @samp{2a} is the
11826 same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
11827 is a variable called @code{ab}, @emph{not} the product of @samp{a} and
11828 @samp{b}! Also note that @samp{f (x)} is still a function call.@refill
11830 @cindex Implicit comma in vectors
11831 The rules are slightly different for vectors written with square brackets.
11832 In vectors, the space character is interpreted (like the comma) as a
11833 separator of elements of the vector. Thus @w{@samp{[ 2a b+c d ]}} is
11834 equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
11835 to @samp{2*a*b + c*d}.
11836 Note that spaces around the brackets, and around explicit commas, are
11837 ignored. To force spaces to be interpreted as multiplication you can
11838 enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
11839 interpreted as @samp{[a*b, 2*c*d]}. An implicit comma is also inserted
11840 between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.@refill
11842 Vectors that contain commas (not embedded within nested parentheses or
11843 brackets) do not treat spaces specially: @samp{[a b, 2 c d]} is a vector
11844 of two elements. Also, if it would be an error to treat spaces as
11845 separators, but not otherwise, then Calc will ignore spaces:
11846 @w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
11847 a vector of two elements. Finally, vectors entered with curly braces
11848 instead of square brackets do not give spaces any special treatment.
11849 When Calc displays a vector that does not contain any commas, it will
11850 insert parentheses if necessary to make the meaning clear:
11851 @w{@samp{[(a b)]}}.
11853 The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
11854 or five modulo minus-two? Calc always interprets the leftmost symbol as
11855 an infix operator preferentially (modulo, in this case), so you would
11856 need to write @samp{(5%)-2} to get the former interpretation.
11858 @cindex Function call notation
11859 A function call is, e.g., @samp{sin(1+x)}. Function names follow the same
11860 rules as variable names except that the default prefix @samp{calcFunc-} is
11861 used (instead of @samp{var-}) for the internal Lisp form.
11862 Most mathematical Calculator commands like
11863 @code{calc-sin} have function equivalents like @code{sin}.
11864 If no Lisp function is defined for a function called by a formula, the
11865 call is left as it is during algebraic manipulation: @samp{f(x+y)} is
11866 left alone. Beware that many innocent-looking short names like @code{in}
11867 and @code{re} have predefined meanings which could surprise you; however,
11868 single letters or single letters followed by digits are always safe to
11869 use for your own function names. @xref{Function Index}.@refill
11871 In the documentation for particular commands, the notation @kbd{H S}
11872 (@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
11873 command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
11874 represent the same operation.@refill
11876 Commands that interpret (``parse'') text as algebraic formulas include
11877 algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
11878 the contents of the editing buffer when you finish, the @kbd{M-# g}
11879 and @w{@kbd{M-# r}} commands, the @kbd{C-y} command, the X window system
11880 ``paste'' mouse operation, and Embedded Mode. All of these operations
11881 use the same rules for parsing formulas; in particular, language modes
11882 (@pxref{Language Modes}) affect them all in the same way.
11884 When you read a large amount of text into the Calculator (say a vector
11885 which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
11886 you may wish to include comments in the text. Calc's formula parser
11887 ignores the symbol @samp{%%} and anything following it on a line:
11890 [ a + b, %% the sum of "a" and "b"
11892 %% last line is coming up:
11897 This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
11899 @xref{Syntax Tables}, for a way to create your own operators and other
11900 input notations. @xref{Compositions}, for a way to create new display
11903 @xref{Algebra}, for commands for manipulating formulas symbolically.
11905 @node Stack and Trail, Mode Settings, Data Types, Top
11906 @chapter Stack and Trail Commands
11909 This chapter describes the Calc commands for manipulating objects on the
11910 stack and in the trail buffer. (These commands operate on objects of any
11911 type, such as numbers, vectors, formulas, and incomplete objects.)
11914 * Stack Manipulation::
11915 * Editing Stack Entries::
11920 @node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
11921 @section Stack Manipulation Commands
11927 @cindex Duplicating stack entries
11928 To duplicate the top object on the stack, press @key{RET} or @key{SPC}
11929 (two equivalent keys for the @code{calc-enter} command).
11930 Given a positive numeric prefix argument, these commands duplicate
11931 several elements at the top of the stack.
11932 Given a negative argument,
11933 these commands duplicate the specified element of the stack.
11934 Given an argument of zero, they duplicate the entire stack.
11935 For example, with @samp{10 20 30} on the stack,
11936 @key{RET} creates @samp{10 20 30 30},
11937 @kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
11938 @kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
11939 @kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.@refill
11943 The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
11944 have it, else on @kbd{C-j}) is like @code{calc-enter}
11945 except that the sign of the numeric prefix argument is interpreted
11946 oppositely. Also, with no prefix argument the default argument is 2.
11947 Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
11948 are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
11949 @samp{10 20 30 20}.@refill
11954 @cindex Removing stack entries
11955 @cindex Deleting stack entries
11956 To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
11957 The @kbd{C-d} key is a synonym for @key{DEL}.
11958 (If the top element is an incomplete object with at least one element, the
11959 last element is removed from it.) Given a positive numeric prefix argument,
11960 several elements are removed. Given a negative argument, the specified
11961 element of the stack is deleted. Given an argument of zero, the entire
11963 For example, with @samp{10 20 30} on the stack,
11964 @key{DEL} leaves @samp{10 20},
11965 @kbd{C-u 2 @key{DEL}} leaves @samp{10},
11966 @kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
11967 @kbd{C-u 0 @key{DEL}} leaves an empty stack.@refill
11970 @pindex calc-pop-above
11971 The @key{M-DEL} (@code{calc-pop-above}) command is to @key{DEL} what
11972 @key{LFD} is to @key{RET}: It interprets the sign of the numeric
11973 prefix argument in the opposite way, and the default argument is 2.
11974 Thus @key{M-DEL} by itself removes the second-from-top stack element,
11975 leaving the first, third, fourth, and so on; @kbd{M-3 M-DEL} deletes
11976 the third stack element.
11979 @pindex calc-roll-down
11980 To exchange the top two elements of the stack, press @key{TAB}
11981 (@code{calc-roll-down}). Given a positive numeric prefix argument, the
11982 specified number of elements at the top of the stack are rotated downward.
11983 Given a negative argument, the entire stack is rotated downward the specified
11984 number of times. Given an argument of zero, the entire stack is reversed
11986 For example, with @samp{10 20 30 40 50} on the stack,
11987 @key{TAB} creates @samp{10 20 30 50 40},
11988 @kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
11989 @kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
11990 @kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.@refill
11993 @pindex calc-roll-up
11994 The command @key{M-TAB} (@code{calc-roll-up}) is analogous to @key{TAB}
11995 except that it rotates upward instead of downward. Also, the default
11996 with no prefix argument is to rotate the top 3 elements.
11997 For example, with @samp{10 20 30 40 50} on the stack,
11998 @key{M-TAB} creates @samp{10 20 40 50 30},
11999 @kbd{C-u 4 @key{M-TAB}} creates @samp{10 30 40 50 20},
12000 @kbd{C-u - 2 @key{M-TAB}} creates @samp{30 40 50 10 20}, and
12001 @kbd{C-u 0 @key{M-TAB}} creates @samp{50 40 30 20 10}.@refill
12003 A good way to view the operation of @key{TAB} and @key{M-TAB} is in
12004 terms of moving a particular element to a new position in the stack.
12005 With a positive argument @i{n}, @key{TAB} moves the top stack
12006 element down to level @i{n}, making room for it by pulling all the
12007 intervening stack elements toward the top. @key{M-TAB} moves the
12008 element at level @i{n} up to the top. (Compare with @key{LFD},
12009 which copies instead of moving the element in level @i{n}.)
12011 With a negative argument @i{-n}, @key{TAB} rotates the stack
12012 to move the object in level @i{n} to the deepest place in the
12013 stack, and the object in level @i{n+1} to the top. @key{M-TAB}
12014 rotates the deepest stack element to be in level @i{n}, also
12015 putting the top stack element in level @i{n+1}.
12017 @xref{Selecting Subformulas}, for a way to apply these commands to
12018 any portion of a vector or formula on the stack.
12020 @node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
12021 @section Editing Stack Entries
12026 @pindex calc-edit-finish
12027 @cindex Editing the stack with Emacs
12028 The backquote, @kbd{`} (@code{calc-edit}) command creates a temporary
12029 buffer (@samp{*Calc Edit*}) for editing the top-of-stack value using
12030 regular Emacs commands. With a numeric prefix argument, it edits the
12031 specified number of stack entries at once. (An argument of zero edits
12032 the entire stack; a negative argument edits one specific stack entry.)
12034 When you are done editing, press @kbd{M-# M-#} to finish and return
12035 to Calc. The @key{RET} and @key{LFD} keys also work to finish most
12036 sorts of editing, though in some cases Calc leaves @key{RET} with its
12037 usual meaning (``insert a newline'') if it's a situation where you
12038 might want to insert new lines into the editing buffer. The traditional
12039 Emacs ``finish'' key sequence, @kbd{C-c C-c}, also works to finish
12040 editing and may be easier to type, depending on your keyboard.
12042 When you finish editing, the Calculator parses the lines of text in
12043 the @samp{*Calc Edit*} buffer as numbers or formulas, replaces the
12044 original stack elements in the original buffer with these new values,
12045 then kills the @samp{*Calc Edit*} buffer. The original Calculator buffer
12046 continues to exist during editing, but for best results you should be
12047 careful not to change it until you have finished the edit. You can
12048 also cancel the edit by pressing @kbd{M-# x}.
12050 The formula is normally reevaluated as it is put onto the stack.
12051 For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
12052 @kbd{M-# M-#} will push 5 on the stack. If you use @key{LFD} to
12053 finish, Calc will put the result on the stack without evaluating it.
12055 If you give a prefix argument to @kbd{M-# M-#} (or @kbd{C-c C-c}),
12056 Calc will not kill the @samp{*Calc Edit*} buffer. You can switch
12057 back to that buffer and continue editing if you wish. However, you
12058 should understand that if you initiated the edit with @kbd{`}, the
12059 @kbd{M-# M-#} operation will be programmed to replace the top of the
12060 stack with the new edited value, and it will do this even if you have
12061 rearranged the stack in the meanwhile. This is not so much of a problem
12062 with other editing commands, though, such as @kbd{s e}
12063 (@code{calc-edit-variable}; @pxref{Operations on Variables}).
12065 If the @code{calc-edit} command involves more than one stack entry,
12066 each line of the @samp{*Calc Edit*} buffer is interpreted as a
12067 separate formula. Otherwise, the entire buffer is interpreted as
12068 one formula, with line breaks ignored. (You can use @kbd{C-o} or
12069 @kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
12071 The @kbd{`} key also works during numeric or algebraic entry. The
12072 text entered so far is moved to the @code{*Calc Edit*} buffer for
12073 more extensive editing than is convenient in the minibuffer.
12075 @node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
12076 @section Trail Commands
12079 @cindex Trail buffer
12080 The commands for manipulating the Calc Trail buffer are two-key sequences
12081 beginning with the @kbd{t} prefix.
12084 @pindex calc-trail-display
12085 The @kbd{t d} (@code{calc-trail-display}) command turns display of the
12086 trail on and off. Normally the trail display is toggled on if it was off,
12087 off if it was on. With a numeric prefix of zero, this command always
12088 turns the trail off; with a prefix of one, it always turns the trail on.
12089 The other trail-manipulation commands described here automatically turn
12090 the trail on. Note that when the trail is off values are still recorded
12091 there; they are simply not displayed. To set Emacs to turn the trail
12092 off by default, type @kbd{t d} and then save the mode settings with
12093 @kbd{m m} (@code{calc-save-modes}).
12096 @pindex calc-trail-in
12098 @pindex calc-trail-out
12099 The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
12100 (@code{calc-trail-out}) commands switch the cursor into and out of the
12101 Calc Trail window. In practice they are rarely used, since the commands
12102 shown below are a more convenient way to move around in the
12103 trail, and they work ``by remote control'' when the cursor is still
12104 in the Calculator window.@refill
12106 @cindex Trail pointer
12107 There is a @dfn{trail pointer} which selects some entry of the trail at
12108 any given time. The trail pointer looks like a @samp{>} symbol right
12109 before the selected number. The following commands operate on the
12110 trail pointer in various ways.
12113 @pindex calc-trail-yank
12114 @cindex Retrieving previous results
12115 The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
12116 the trail and pushes it onto the Calculator stack. It allows you to
12117 re-use any previously computed value without retyping. With a numeric
12118 prefix argument @var{n}, it yanks the value @var{n} lines above the current
12122 @pindex calc-trail-scroll-left
12124 @pindex calc-trail-scroll-right
12125 The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
12126 (@code{calc-trail-scroll-right}) commands horizontally scroll the trail
12127 window left or right by one half of its width.@refill
12130 @pindex calc-trail-next
12132 @pindex calc-trail-previous
12134 @pindex calc-trail-forward
12136 @pindex calc-trail-backward
12137 The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
12138 (@code{calc-trail-previous)} commands move the trail pointer down or up
12139 one line. The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
12140 (@code{calc-trail-backward}) commands move the trail pointer down or up
12141 one screenful at a time. All of these commands accept numeric prefix
12142 arguments to move several lines or screenfuls at a time.@refill
12145 @pindex calc-trail-first
12147 @pindex calc-trail-last
12149 @pindex calc-trail-here
12150 The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
12151 (@code{calc-trail-last}) commands move the trail pointer to the first or
12152 last line of the trail. The @kbd{t h} (@code{calc-trail-here}) command
12153 moves the trail pointer to the cursor position; unlike the other trail
12154 commands, @kbd{t h} works only when Calc Trail is the selected window.@refill
12157 @pindex calc-trail-isearch-forward
12159 @pindex calc-trail-isearch-backward
12161 The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12162 (@code{calc-trail-isearch-backward}) commands perform an incremental
12163 search forward or backward through the trail. You can press @key{RET}
12164 to terminate the search; the trail pointer moves to the current line.
12165 If you cancel the search with @kbd{C-g}, the trail pointer stays where
12166 it was when the search began.@refill
12169 The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12170 (@code{calc-trail-isearch-backward}) com\-mands perform an incremental
12171 search forward or backward through the trail. You can press @key{RET}
12172 to terminate the search; the trail pointer moves to the current line.
12173 If you cancel the search with @kbd{C-g}, the trail pointer stays where
12174 it was when the search began.
12178 @pindex calc-trail-marker
12179 The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
12180 line of text of your own choosing into the trail. The text is inserted
12181 after the line containing the trail pointer; this usually means it is
12182 added to the end of the trail. Trail markers are useful mainly as the
12183 targets for later incremental searches in the trail.
12186 @pindex calc-trail-kill
12187 The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
12188 from the trail. The line is saved in the Emacs kill ring suitable for
12189 yanking into another buffer, but it is not easy to yank the text back
12190 into the trail buffer. With a numeric prefix argument, this command
12191 kills the @var{n} lines below or above the selected one.
12193 The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
12194 elsewhere; @pxref{Vector and Matrix Formats}.
12196 @node Keep Arguments, , Trail Commands, Stack and Trail
12197 @section Keep Arguments
12201 @pindex calc-keep-args
12202 The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
12203 the following command. It prevents that command from removing its
12204 arguments from the stack. For example, after @kbd{2 @key{RET} 3 +},
12205 the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
12206 the stack contains the arguments and the result: @samp{2 3 5}.
12208 This works for all commands that take arguments off the stack. As
12209 another example, @kbd{K a s} simplifies a formula, pushing the
12210 simplified version of the formula onto the stack after the original
12211 formula (rather than replacing the original formula).
12213 Note that you could get the same effect by typing @kbd{RET a s},
12214 copying the formula and then simplifying the copy. One difference
12215 is that for a very large formula the time taken to format the
12216 intermediate copy in @kbd{RET a s} could be noticeable; @kbd{K a s}
12217 would avoid this extra work.
12219 Even stack manipulation commands are affected. @key{TAB} works by
12220 popping two values and pushing them back in the opposite order,
12221 so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
12223 A few Calc commands provide other ways of doing the same thing.
12224 For example, @kbd{' sin($)} replaces the number on the stack with
12225 its sine using algebraic entry; to push the sine and keep the
12226 original argument you could use either @kbd{' sin($1)} or
12227 @kbd{K ' sin($)}. @xref{Algebraic Entry}. Also, the @kbd{s s}
12228 command is effectively the same as @kbd{K s t}. @xref{Storing Variables}.
12230 Keyboard macros may interact surprisingly with the @kbd{K} prefix.
12231 If you have defined a keyboard macro to be, say, @samp{Q +} to add
12232 one number to the square root of another, then typing @kbd{K X} will
12233 execute @kbd{K Q +}, probably not what you expected. The @kbd{K}
12234 prefix will apply to just the first command in the macro rather than
12237 If you execute a command and then decide you really wanted to keep
12238 the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
12239 This command pushes the last arguments that were popped by any command
12240 onto the stack. Note that the order of things on the stack will be
12241 different than with @kbd{K}: @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
12242 @samp{5 2 3} on the stack instead of @samp{2 3 5}. @xref{Undo}.
12244 @node Mode Settings, Arithmetic, Stack and Trail, Top
12245 @chapter Mode Settings
12248 This chapter describes commands that set modes in the Calculator.
12249 They do not affect the contents of the stack, although they may change
12250 the @emph{appearance} or @emph{interpretation} of the stack's contents.
12253 * General Mode Commands::
12255 * Inverse and Hyperbolic::
12256 * Calculation Modes::
12257 * Simplification Modes::
12265 @node General Mode Commands, Precision, Mode Settings, Mode Settings
12266 @section General Mode Commands
12270 @pindex calc-save-modes
12271 @cindex Continuous memory
12272 @cindex Saving mode settings
12273 @cindex Permanent mode settings
12274 @cindex @file{.emacs} file, mode settings
12275 You can save all of the current mode settings in your @file{.emacs} file
12276 with the @kbd{m m} (@code{calc-save-modes}) command. This will cause
12277 Emacs to reestablish these modes each time it starts up. The modes saved
12278 in the file include everything controlled by the @kbd{m} and @kbd{d}
12279 prefix keys, the current precision and binary word size, whether or not
12280 the trail is displayed, the current height of the Calc window, and more.
12281 The current interface (used when you type @kbd{M-# M-#}) is also saved.
12282 If there were already saved mode settings in the file, they are replaced.
12283 Otherwise, the new mode information is appended to the end of the file.
12286 @pindex calc-mode-record-mode
12287 The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
12288 record the new mode settings (as if by pressing @kbd{m m}) every
12289 time a mode setting changes. If Embedded Mode is enabled, other
12290 options are available; @pxref{Mode Settings in Embedded Mode}.
12293 @pindex calc-settings-file-name
12294 The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
12295 choose a different place than your @file{.emacs} file for @kbd{m m},
12296 @kbd{Z P}, and similar commands to save permanent information.
12297 You are prompted for a file name. All Calc modes are then reset to
12298 their default values, then settings from the file you named are loaded
12299 if this file exists, and this file becomes the one that Calc will
12300 use in the future for commands like @kbd{m m}. The default settings
12301 file name is @file{~/.emacs}. You can see the current file name by
12302 giving a blank response to the @kbd{m F} prompt. See also the
12303 discussion of the @code{calc-settings-file} variable; @pxref{Installation}.
12305 If the file name you give contains the string @samp{.emacs} anywhere
12306 inside it, @kbd{m F} will not automatically load the new file. This
12307 is because you are presumably switching to your @file{~/.emacs} file,
12308 which may contain other things you don't want to reread. You can give
12309 a numeric prefix argument of 1 to @kbd{m F} to force it to read the
12310 file no matter what its name. Conversely, an argument of @i{-1} tells
12311 @kbd{m F} @emph{not} to read the new file. An argument of 2 or @i{-2}
12312 tells @kbd{m F} not to reset the modes to their defaults beforehand,
12313 which is useful if you intend your new file to have a variant of the
12314 modes present in the file you were using before.
12317 @pindex calc-always-load-extensions
12318 The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
12319 in which the first use of Calc loads the entire program, including all
12320 extensions modules. Otherwise, the extensions modules will not be loaded
12321 until the various advanced Calc features are used. Since this mode only
12322 has effect when Calc is first loaded, @kbd{m x} is usually followed by
12323 @kbd{m m} to make the mode-setting permanent. To load all of Calc just
12324 once, rather than always in the future, you can press @kbd{M-# L}.
12327 @pindex calc-shift-prefix
12328 The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
12329 all of Calc's letter prefix keys may be typed shifted as well as unshifted.
12330 If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
12331 you might find it easier to turn this mode on so that you can type
12332 @kbd{A S} instead. When this mode is enabled, the commands that used to
12333 be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
12334 now be invoked by pressing the shifted letter twice: @kbd{A A}. Note
12335 that the @kbd{v} prefix key always works both shifted and unshifted, and
12336 the @kbd{z} and @kbd{Z} prefix keys are always distinct. Also, the @kbd{h}
12337 prefix is not affected by this mode. Press @kbd{m S} again to disable
12338 shifted-prefix mode.
12340 @node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
12345 @pindex calc-precision
12346 @cindex Precision of calculations
12347 The @kbd{p} (@code{calc-precision}) command controls the precision to
12348 which floating-point calculations are carried. The precision must be
12349 at least 3 digits and may be arbitrarily high, within the limits of
12350 memory and time. This affects only floats: Integer and rational
12351 calculations are always carried out with as many digits as necessary.
12353 The @kbd{p} key prompts for the current precision. If you wish you
12354 can instead give the precision as a numeric prefix argument.
12356 Many internal calculations are carried to one or two digits higher
12357 precision than normal. Results are rounded down afterward to the
12358 current precision. Unless a special display mode has been selected,
12359 floats are always displayed with their full stored precision, i.e.,
12360 what you see is what you get. Reducing the current precision does not
12361 round values already on the stack, but those values will be rounded
12362 down before being used in any calculation. The @kbd{c 0} through
12363 @kbd{c 9} commands (@pxref{Conversions}) can be used to round an
12364 existing value to a new precision.@refill
12366 @cindex Accuracy of calculations
12367 It is important to distinguish the concepts of @dfn{precision} and
12368 @dfn{accuracy}. In the normal usage of these words, the number
12369 123.4567 has a precision of 7 digits but an accuracy of 4 digits.
12370 The precision is the total number of digits not counting leading
12371 or trailing zeros (regardless of the position of the decimal point).
12372 The accuracy is simply the number of digits after the decimal point
12373 (again not counting trailing zeros). In Calc you control the precision,
12374 not the accuracy of computations. If you were to set the accuracy
12375 instead, then calculations like @samp{exp(100)} would generate many
12376 more digits than you would typically need, while @samp{exp(-100)} would
12377 probably round to zero! In Calc, both these computations give you
12378 exactly 12 (or the requested number of) significant digits.
12380 The only Calc features that deal with accuracy instead of precision
12381 are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
12382 and the rounding functions like @code{floor} and @code{round}
12383 (@pxref{Integer Truncation}). Also, @kbd{c 0} through @kbd{c 9}
12384 deal with both precision and accuracy depending on the magnitudes
12385 of the numbers involved.
12387 If you need to work with a particular fixed accuracy (say, dollars and
12388 cents with two digits after the decimal point), one solution is to work
12389 with integers and an ``implied'' decimal point. For example, $8.99
12390 divided by 6 would be entered @kbd{899 RET 6 /}, yielding 149.833
12391 (actually $1.49833 with our implied decimal point); pressing @kbd{R}
12392 would round this to 150 cents, i.e., $1.50.
12394 @xref{Floats}, for still more on floating-point precision and related
12397 @node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
12398 @section Inverse and Hyperbolic Flags
12402 @pindex calc-inverse
12403 There is no single-key equivalent to the @code{calc-arcsin} function.
12404 Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
12405 the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
12406 The @kbd{I} key actually toggles the Inverse Flag. When this flag
12407 is set, the word @samp{Inv} appears in the mode line.@refill
12410 @pindex calc-hyperbolic
12411 Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
12412 Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
12413 If both of these flags are set at once, the effect will be
12414 @code{calc-arcsinh}. (The Hyperbolic flag is also used by some
12415 non-trigonometric commands; for example @kbd{H L} computes a base-10,
12416 instead of base-@i{e}, logarithm.)@refill
12418 Command names like @code{calc-arcsin} are provided for completeness, and
12419 may be executed with @kbd{x} or @kbd{M-x}. Their effect is simply to
12420 toggle the Inverse and/or Hyperbolic flags and then execute the
12421 corresponding base command (@code{calc-sin} in this case).
12423 The Inverse and Hyperbolic flags apply only to the next Calculator
12424 command, after which they are automatically cleared. (They are also
12425 cleared if the next keystroke is not a Calc command.) Digits you
12426 type after @kbd{I} or @kbd{H} (or @kbd{K}) are treated as prefix
12427 arguments for the next command, not as numeric entries. The same
12428 is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means to
12429 subtract and keep arguments).
12431 The third Calc prefix flag, @kbd{K} (keep-arguments), is discussed
12432 elsewhere. @xref{Keep Arguments}.
12434 @node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
12435 @section Calculation Modes
12438 The commands in this section are two-key sequences beginning with
12439 the @kbd{m} prefix. (That's the letter @kbd{m}, not the @key{META} key.)
12440 The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
12441 (@pxref{Algebraic Entry}).
12450 * Automatic Recomputation::
12451 * Working Message::
12454 @node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
12455 @subsection Angular Modes
12458 @cindex Angular mode
12459 The Calculator supports three notations for angles: radians, degrees,
12460 and degrees-minutes-seconds. When a number is presented to a function
12461 like @code{sin} that requires an angle, the current angular mode is
12462 used to interpret the number as either radians or degrees. If an HMS
12463 form is presented to @code{sin}, it is always interpreted as
12464 degrees-minutes-seconds.
12466 Functions that compute angles produce a number in radians, a number in
12467 degrees, or an HMS form depending on the current angular mode. If the
12468 result is a complex number and the current mode is HMS, the number is
12469 instead expressed in degrees. (Complex-number calculations would
12470 normally be done in radians mode, though. Complex numbers are converted
12471 to degrees by calculating the complex result in radians and then
12472 multiplying by 180 over @c{$\pi$}
12476 @pindex calc-radians-mode
12478 @pindex calc-degrees-mode
12480 @pindex calc-hms-mode
12481 The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
12482 and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
12483 The current angular mode is displayed on the Emacs mode line.
12484 The default angular mode is degrees.@refill
12486 @node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
12487 @subsection Polar Mode
12491 The Calculator normally ``prefers'' rectangular complex numbers in the
12492 sense that rectangular form is used when the proper form can not be
12493 decided from the input. This might happen by multiplying a rectangular
12494 number by a polar one, by taking the square root of a negative real
12495 number, or by entering @kbd{( 2 @key{SPC} 3 )}.
12498 @pindex calc-polar-mode
12499 The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
12500 preference between rectangular and polar forms. In polar mode, all
12501 of the above example situations would produce polar complex numbers.
12503 @node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
12504 @subsection Fraction Mode
12507 @cindex Fraction mode
12508 @cindex Division of integers
12509 Division of two integers normally yields a floating-point number if the
12510 result cannot be expressed as an integer. In some cases you would
12511 rather get an exact fractional answer. One way to accomplish this is
12512 to multiply fractions instead: @kbd{6 @key{RET} 1:4 *} produces @cite{3:2}
12513 even though @kbd{6 @key{RET} 4 /} produces @cite{1.5}.
12516 @pindex calc-frac-mode
12517 To set the Calculator to produce fractional results for normal integer
12518 divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
12519 For example, @cite{8/4} produces @cite{2} in either mode,
12520 but @cite{6/4} produces @cite{3:2} in Fraction Mode, @cite{1.5} in
12523 At any time you can use @kbd{c f} (@code{calc-float}) to convert a
12524 fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
12525 float to a fraction. @xref{Conversions}.
12527 @node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
12528 @subsection Infinite Mode
12531 @cindex Infinite mode
12532 The Calculator normally treats results like @cite{1 / 0} as errors;
12533 formulas like this are left in unsimplified form. But Calc can be
12534 put into a mode where such calculations instead produce ``infinite''
12538 @pindex calc-infinite-mode
12539 The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
12540 on and off. When the mode is off, infinities do not arise except
12541 in calculations that already had infinities as inputs. (One exception
12542 is that infinite open intervals like @samp{[0 .. inf)} can be
12543 generated; however, intervals closed at infinity (@samp{[0 .. inf]})
12544 will not be generated when infinite mode is off.)
12546 With infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
12547 an undirected infinity. @xref{Infinities}, for a discussion of the
12548 difference between @code{inf} and @code{uinf}. Also, @cite{0 / 0}
12549 evaluates to @code{nan}, the ``indeterminate'' symbol. Various other
12550 functions can also return infinities in this mode; for example,
12551 @samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}. Once again,
12552 note that @samp{exp(inf) = inf} regardless of infinite mode because
12553 this calculation has infinity as an input.
12555 @cindex Positive infinite mode
12556 The @kbd{m i} command with a numeric prefix argument of zero,
12557 i.e., @kbd{C-u 0 m i}, turns on a ``positive infinite mode'' in
12558 which zero is treated as positive instead of being directionless.
12559 Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
12560 Note that zero never actually has a sign in Calc; there are no
12561 separate representations for @i{+0} and @i{-0}. Positive
12562 infinite mode merely changes the interpretation given to the
12563 single symbol, @samp{0}. One consequence of this is that, while
12564 you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
12565 is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
12567 @node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
12568 @subsection Symbolic Mode
12571 @cindex Symbolic mode
12572 @cindex Inexact results
12573 Calculations are normally performed numerically wherever possible.
12574 For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
12575 algebraic expression, produces a numeric answer if the argument is a
12576 number or a symbolic expression if the argument is an expression:
12577 @kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
12580 @pindex calc-symbolic-mode
12581 In @dfn{symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
12582 command, functions which would produce inexact, irrational results are
12583 left in symbolic form. Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
12587 @pindex calc-eval-num
12588 The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
12589 the expression at the top of the stack, by temporarily disabling
12590 @code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
12591 Given a numeric prefix argument, it also
12592 sets the floating-point precision to the specified value for the duration
12593 of the command.@refill
12595 To evaluate a formula numerically without expanding the variables it
12596 contains, you can use the key sequence @kbd{m s a v m s} (this uses
12597 @code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
12600 @node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
12601 @subsection Matrix and Scalar Modes
12604 @cindex Matrix mode
12605 @cindex Scalar mode
12606 Calc sometimes makes assumptions during algebraic manipulation that
12607 are awkward or incorrect when vectors and matrices are involved.
12608 Calc has two modes, @dfn{matrix mode} and @dfn{scalar mode}, which
12609 modify its behavior around vectors in useful ways.
12612 @pindex calc-matrix-mode
12613 Press @kbd{m v} (@code{calc-matrix-mode}) once to enter matrix mode.
12614 In this mode, all objects are assumed to be matrices unless provably
12615 otherwise. One major effect is that Calc will no longer consider
12616 multiplication to be commutative. (Recall that in matrix arithmetic,
12617 @samp{A*B} is not the same as @samp{B*A}.) This assumption affects
12618 rewrite rules and algebraic simplification. Another effect of this
12619 mode is that calculations that would normally produce constants like
12620 0 and 1 (e.g., @cite{a - a} and @cite{a / a}, respectively) will now
12621 produce function calls that represent ``generic'' zero or identity
12622 matrices: @samp{idn(0)}, @samp{idn(1)}. The @code{idn} function
12623 @samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
12624 identity matrix; if @var{n} is omitted, it doesn't know what
12625 dimension to use and so the @code{idn} call remains in symbolic
12626 form. However, if this generic identity matrix is later combined
12627 with a matrix whose size is known, it will be converted into
12628 a true identity matrix of the appropriate size. On the other hand,
12629 if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
12630 will assume it really was a scalar after all and produce, e.g., 3.
12632 Press @kbd{m v} a second time to get scalar mode. Here, objects are
12633 assumed @emph{not} to be vectors or matrices unless provably so.
12634 For example, normally adding a variable to a vector, as in
12635 @samp{[x, y, z] + a}, will leave the sum in symbolic form because
12636 as far as Calc knows, @samp{a} could represent either a number or
12637 another 3-vector. In scalar mode, @samp{a} is assumed to be a
12638 non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
12640 Press @kbd{m v} a third time to return to the normal mode of operation.
12642 If you press @kbd{m v} with a numeric prefix argument @var{n}, you
12643 get a special ``dimensioned matrix mode'' in which matrices of
12644 unknown size are assumed to be @var{n}x@var{n} square matrices.
12645 Then, the function call @samp{idn(1)} will expand into an actual
12646 matrix rather than representing a ``generic'' matrix.
12648 @cindex Declaring scalar variables
12649 Of course these modes are approximations to the true state of
12650 affairs, which is probably that some quantities will be matrices
12651 and others will be scalars. One solution is to ``declare''
12652 certain variables or functions to be scalar-valued.
12653 @xref{Declarations}, to see how to make declarations in Calc.
12655 There is nothing stopping you from declaring a variable to be
12656 scalar and then storing a matrix in it; however, if you do, the
12657 results you get from Calc may not be valid. Suppose you let Calc
12658 get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
12659 @samp{[1, 2, 3]} in @samp{a}. The result would not be the same as
12660 for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
12661 your earlier promise to Calc that @samp{a} would be scalar.
12663 Another way to mix scalars and matrices is to use selections
12664 (@pxref{Selecting Subformulas}). Use matrix mode when operating on
12665 your formula normally; then, to apply scalar mode to a certain part
12666 of the formula without affecting the rest just select that part,
12667 change into scalar mode and press @kbd{=} to resimplify the part
12668 under this mode, then change back to matrix mode before deselecting.
12670 @node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
12671 @subsection Automatic Recomputation
12674 The @dfn{evaluates-to} operator, @samp{=>}, has the special
12675 property that any @samp{=>} formulas on the stack are recomputed
12676 whenever variable values or mode settings that might affect them
12677 are changed. @xref{Evaluates-To Operator}.
12680 @pindex calc-auto-recompute
12681 The @kbd{m C} (@code{calc-auto-recompute}) command turns this
12682 automatic recomputation on and off. If you turn it off, Calc will
12683 not update @samp{=>} operators on the stack (nor those in the
12684 attached Embedded Mode buffer, if there is one). They will not
12685 be updated unless you explicitly do so by pressing @kbd{=} or until
12686 you press @kbd{m C} to turn recomputation back on. (While automatic
12687 recomputation is off, you can think of @kbd{m C m C} as a command
12688 to update all @samp{=>} operators while leaving recomputation off.)
12690 To update @samp{=>} operators in an Embedded buffer while
12691 automatic recomputation is off, use @w{@kbd{M-# u}}.
12692 @xref{Embedded Mode}.
12694 @node Working Message, , Automatic Recomputation, Calculation Modes
12695 @subsection Working Messages
12698 @cindex Performance
12699 @cindex Working messages
12700 Since the Calculator is written entirely in Emacs Lisp, which is not
12701 designed for heavy numerical work, many operations are quite slow.
12702 The Calculator normally displays the message @samp{Working...} in the
12703 echo area during any command that may be slow. In addition, iterative
12704 operations such as square roots and trigonometric functions display the
12705 intermediate result at each step. Both of these types of messages can
12706 be disabled if you find them distracting.
12709 @pindex calc-working
12710 Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
12711 disable all ``working'' messages. Use a numeric prefix of 1 to enable
12712 only the plain @samp{Working...} message. Use a numeric prefix of 2 to
12713 see intermediate results as well. With no numeric prefix this displays
12714 the current mode.@refill
12716 While it may seem that the ``working'' messages will slow Calc down
12717 considerably, experiments have shown that their impact is actually
12718 quite small. But if your terminal is slow you may find that it helps
12719 to turn the messages off.
12721 @node Simplification Modes, Declarations, Calculation Modes, Mode Settings
12722 @section Simplification Modes
12725 The current @dfn{simplification mode} controls how numbers and formulas
12726 are ``normalized'' when being taken from or pushed onto the stack.
12727 Some normalizations are unavoidable, such as rounding floating-point
12728 results to the current precision, and reducing fractions to simplest
12729 form. Others, such as simplifying a formula like @cite{a+a} (or @cite{2+3}),
12730 are done by default but can be turned off when necessary.
12732 When you press a key like @kbd{+} when @cite{2} and @cite{3} are on the
12733 stack, Calc pops these numbers, normalizes them, creates the formula
12734 @cite{2+3}, normalizes it, and pushes the result. Of course the standard
12735 rules for normalizing @cite{2+3} will produce the result @cite{5}.
12737 Simplification mode commands consist of the lower-case @kbd{m} prefix key
12738 followed by a shifted letter.
12741 @pindex calc-no-simplify-mode
12742 The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
12743 simplifications. These would leave a formula like @cite{2+3} alone. In
12744 fact, nothing except simple numbers are ever affected by normalization
12748 @pindex calc-num-simplify-mode
12749 The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
12750 of any formulas except those for which all arguments are constants. For
12751 example, @cite{1+2} is simplified to @cite{3}, and @cite{a+(2-2)} is
12752 simplified to @cite{a+0} but no further, since one argument of the sum
12753 is not a constant. Unfortunately, @cite{(a+2)-2} is @emph{not} simplified
12754 because the top-level @samp{-} operator's arguments are not both
12755 constant numbers (one of them is the formula @cite{a+2}).
12756 A constant is a number or other numeric object (such as a constant
12757 error form or modulo form), or a vector all of whose
12758 elements are constant.@refill
12761 @pindex calc-default-simplify-mode
12762 The @kbd{m D} (@code{calc-default-simplify-mode}) command restores the
12763 default simplifications for all formulas. This includes many easy and
12764 fast algebraic simplifications such as @cite{a+0} to @cite{a}, and
12765 @cite{a + 2 a} to @cite{3 a}, as well as evaluating functions like
12766 @cite{@t{deriv}(x^2, x)} to @cite{2 x}.
12769 @pindex calc-bin-simplify-mode
12770 The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the default
12771 simplifications to a result and then, if the result is an integer,
12772 uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
12773 to the current binary word size. @xref{Binary Functions}. Real numbers
12774 are rounded to the nearest integer and then clipped; other kinds of
12775 results (after the default simplifications) are left alone.
12778 @pindex calc-alg-simplify-mode
12779 The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does algebraic
12780 simplification; it applies all the default simplifications, and also
12781 the more powerful (and slower) simplifications made by @kbd{a s}
12782 (@code{calc-simplify}). @xref{Algebraic Simplifications}.
12785 @pindex calc-ext-simplify-mode
12786 The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended''
12787 algebraic simplification, as by the @kbd{a e} (@code{calc-simplify-extended})
12788 command. @xref{Unsafe Simplifications}.
12791 @pindex calc-units-simplify-mode
12792 The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
12793 simplification; it applies the command @kbd{u s}
12794 (@code{calc-simplify-units}), which in turn
12795 is a superset of @kbd{a s}. In this mode, variable names which
12796 are identifiable as unit names (like @samp{mm} for ``millimeters'')
12797 are simplified with their unit definitions in mind.@refill
12799 A common technique is to set the simplification mode down to the lowest
12800 amount of simplification you will allow to be applied automatically, then
12801 use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
12802 perform higher types of simplifications on demand. @xref{Algebraic
12803 Definitions}, for another sample use of no-simplification mode.@refill
12805 @node Declarations, Display Modes, Simplification Modes, Mode Settings
12806 @section Declarations
12809 A @dfn{declaration} is a statement you make that promises you will
12810 use a certain variable or function in a restricted way. This may
12811 give Calc the freedom to do things that it couldn't do if it had to
12812 take the fully general situation into account.
12815 * Declaration Basics::
12816 * Kinds of Declarations::
12817 * Functions for Declarations::
12820 @node Declaration Basics, Kinds of Declarations, Declarations, Declarations
12821 @subsection Declaration Basics
12825 @pindex calc-declare-variable
12826 The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
12827 way to make a declaration for a variable. This command prompts for
12828 the variable name, then prompts for the declaration. The default
12829 at the declaration prompt is the previous declaration, if any.
12830 You can edit this declaration, or press @kbd{C-k} to erase it and
12831 type a new declaration. (Or, erase it and press @key{RET} to clear
12832 the declaration, effectively ``undeclaring'' the variable.)
12834 A declaration is in general a vector of @dfn{type symbols} and
12835 @dfn{range} values. If there is only one type symbol or range value,
12836 you can write it directly rather than enclosing it in a vector.
12837 For example, @kbd{s d foo RET real RET} declares @code{foo} to
12838 be a real number, and @kbd{s d bar RET [int, const, [1..6]] RET}
12839 declares @code{bar} to be a constant integer between 1 and 6.
12840 (Actually, you can omit the outermost brackets and Calc will
12841 provide them for you: @kbd{s d bar RET int, const, [1..6] RET}.)
12843 @cindex @code{Decls} variable
12845 Declarations in Calc are kept in a special variable called @code{Decls}.
12846 This variable encodes the set of all outstanding declarations in
12847 the form of a matrix. Each row has two elements: A variable or
12848 vector of variables declared by that row, and the declaration
12849 specifier as described above. You can use the @kbd{s D} command to
12850 edit this variable if you wish to see all the declarations at once.
12851 @xref{Operations on Variables}, for a description of this command
12852 and the @kbd{s p} command that allows you to save your declarations
12853 permanently if you wish.
12855 Items being declared can also be function calls. The arguments in
12856 the call are ignored; the effect is to say that this function returns
12857 values of the declared type for any valid arguments. The @kbd{s d}
12858 command declares only variables, so if you wish to make a function
12859 declaration you will have to edit the @code{Decls} matrix yourself.
12861 For example, the declaration matrix
12867 [ f(1,2,3), [0 .. inf) ] ]
12872 declares that @code{foo} represents a real number, @code{j}, @code{k}
12873 and @code{n} represent integers, and the function @code{f} always
12874 returns a real number in the interval shown.
12877 If there is a declaration for the variable @code{All}, then that
12878 declaration applies to all variables that are not otherwise declared.
12879 It does not apply to function names. For example, using the row
12880 @samp{[All, real]} says that all your variables are real unless they
12881 are explicitly declared without @code{real} in some other row.
12882 The @kbd{s d} command declares @code{All} if you give a blank
12883 response to the variable-name prompt.
12885 @node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
12886 @subsection Kinds of Declarations
12889 The type-specifier part of a declaration (that is, the second prompt
12890 in the @kbd{s d} command) can be a type symbol, an interval, or a
12891 vector consisting of zero or more type symbols followed by zero or
12892 more intervals or numbers that represent the set of possible values
12897 [ [ a, [1, 2, 3, 4, 5] ]
12899 [ c, [int, 1 .. 5] ] ]
12903 Here @code{a} is declared to contain one of the five integers shown;
12904 @code{b} is any number in the interval from 1 to 5 (any real number
12905 since we haven't specified), and @code{c} is any integer in that
12906 interval. Thus the declarations for @code{a} and @code{c} are
12907 nearly equivalent (see below).
12909 The type-specifier can be the empty vector @samp{[]} to say that
12910 nothing is known about a given variable's value. This is the same
12911 as not declaring the variable at all except that it overrides any
12912 @code{All} declaration which would otherwise apply.
12914 The initial value of @code{Decls} is the empty vector @samp{[]}.
12915 If @code{Decls} has no stored value or if the value stored in it
12916 is not valid, it is ignored and there are no declarations as far
12917 as Calc is concerned. (The @kbd{s d} command will replace such a
12918 malformed value with a fresh empty matrix, @samp{[]}, before recording
12919 the new declaration.) Unrecognized type symbols are ignored.
12921 The following type symbols describe what sorts of numbers will be
12922 stored in a variable:
12928 Numerical integers. (Integers or integer-valued floats.)
12930 Fractions. (Rational numbers which are not integers.)
12932 Rational numbers. (Either integers or fractions.)
12934 Floating-point numbers.
12936 Real numbers. (Integers, fractions, or floats. Actually,
12937 intervals and error forms with real components also count as
12940 Positive real numbers. (Strictly greater than zero.)
12942 Nonnegative real numbers. (Greater than or equal to zero.)
12944 Numbers. (Real or complex.)
12947 Calc uses this information to determine when certain simplifications
12948 of formulas are safe. For example, @samp{(x^y)^z} cannot be
12949 simplified to @samp{x^(y z)} in general; for example,
12950 @samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @i{-3}.
12951 However, this simplification @emph{is} safe if @code{z} is known
12952 to be an integer, or if @code{x} is known to be a nonnegative
12953 real number. If you have given declarations that allow Calc to
12954 deduce either of these facts, Calc will perform this simplification
12957 Calc can apply a certain amount of logic when using declarations.
12958 For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
12959 has been declared @code{int}; Calc knows that an integer times an
12960 integer, plus an integer, must always be an integer. (In fact,
12961 Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
12962 it is able to determine that @samp{2n+1} must be an odd integer.)
12964 Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
12965 because Calc knows that the @code{abs} function always returns a
12966 nonnegative real. If you had a @code{myabs} function that also had
12967 this property, you could get Calc to recognize it by adding the row
12968 @samp{[myabs(), nonneg]} to the @code{Decls} matrix.
12970 One instance of this simplification is @samp{sqrt(x^2)} (since the
12971 @code{sqrt} function is effectively a one-half power). Normally
12972 Calc leaves this formula alone. After the command
12973 @kbd{s d x RET real RET}, however, it can simplify the formula to
12974 @samp{abs(x)}. And after @kbd{s d x RET nonneg RET}, Calc can
12975 simplify this formula all the way to @samp{x}.
12977 If there are any intervals or real numbers in the type specifier,
12978 they comprise the set of possible values that the variable or
12979 function being declared can have. In particular, the type symbol
12980 @code{real} is effectively the same as the range @samp{[-inf .. inf]}
12981 (note that infinity is included in the range of possible values);
12982 @code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
12983 the same as @samp{[0 .. inf]}. Saying @samp{[real, [-5 .. 5]]} is
12984 redundant because the fact that the variable is real can be
12985 deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
12986 @samp{[rat, [-5 .. 5]]} are useful combinations.
12988 Note that the vector of intervals or numbers is in the same format
12989 used by Calc's set-manipulation commands. @xref{Set Operations}.
12991 The type specifier @samp{[1, 2, 3]} is equivalent to
12992 @samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
12993 In other words, the range of possible values means only that
12994 the variable's value must be numerically equal to a number in
12995 that range, but not that it must be equal in type as well.
12996 Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
12997 and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
12999 If you use a conflicting combination of type specifiers, the
13000 results are unpredictable. An example is @samp{[pos, [0 .. 5]]},
13001 where the interval does not lie in the range described by the
13004 ``Real'' declarations mostly affect simplifications involving powers
13005 like the one described above. Another case where they are used
13006 is in the @kbd{a P} command which returns a list of all roots of a
13007 polynomial; if the variable has been declared real, only the real
13008 roots (if any) will be included in the list.
13010 ``Integer'' declarations are used for simplifications which are valid
13011 only when certain values are integers (such as @samp{(x^y)^z}
13014 Another command that makes use of declarations is @kbd{a s}, when
13015 simplifying equations and inequalities. It will cancel @code{x}
13016 from both sides of @samp{a x = b x} only if it is sure @code{x}
13017 is non-zero, say, because it has a @code{pos} declaration.
13018 To declare specifically that @code{x} is real and non-zero,
13019 use @samp{[[-inf .. 0), (0 .. inf]]}. (There is no way in the
13020 current notation to say that @code{x} is nonzero but not necessarily
13021 real.) The @kbd{a e} command does ``unsafe'' simplifications,
13022 including cancelling @samp{x} from the equation when @samp{x} is
13023 not known to be nonzero.
13025 Another set of type symbols distinguish between scalars and vectors.
13029 The value is not a vector.
13031 The value is a vector.
13033 The value is a matrix (a rectangular vector of vectors).
13036 These type symbols can be combined with the other type symbols
13037 described above; @samp{[int, matrix]} describes an object which
13038 is a matrix of integers.
13040 Scalar/vector declarations are used to determine whether certain
13041 algebraic operations are safe. For example, @samp{[a, b, c] + x}
13042 is normally not simplified to @samp{[a + x, b + x, c + x]}, but
13043 it will be if @code{x} has been declared @code{scalar}. On the
13044 other hand, multiplication is usually assumed to be commutative,
13045 but the terms in @samp{x y} will never be exchanged if both @code{x}
13046 and @code{y} are known to be vectors or matrices. (Calc currently
13047 never distinguishes between @code{vector} and @code{matrix}
13050 @xref{Matrix Mode}, for a discussion of ``matrix mode'' and
13051 ``scalar mode,'' which are similar to declaring @samp{[All, matrix]}
13052 or @samp{[All, scalar]} but much more convenient.
13054 One more type symbol that is recognized is used with the @kbd{H a d}
13055 command for taking total derivatives of a formula. @xref{Calculus}.
13059 The value is a constant with respect to other variables.
13062 Calc does not check the declarations for a variable when you store
13063 a value in it. However, storing @i{-3.5} in a variable that has
13064 been declared @code{pos}, @code{int}, or @code{matrix} may have
13065 unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @cite{3.5}
13066 if it substitutes the value first, or to @cite{-3.5} if @code{x}
13067 was declared @code{pos} and the formula @samp{sqrt(x^2)} is
13068 simplified to @samp{x} before the value is substituted. Before
13069 using a variable for a new purpose, it is best to use @kbd{s d}
13070 or @kbd{s D} to check to make sure you don't still have an old
13071 declaration for the variable that will conflict with its new meaning.
13073 @node Functions for Declarations, , Kinds of Declarations, Declarations
13074 @subsection Functions for Declarations
13077 Calc has a set of functions for accessing the current declarations
13078 in a convenient manner. These functions return 1 if the argument
13079 can be shown to have the specified property, or 0 if the argument
13080 can be shown @emph{not} to have that property; otherwise they are
13081 left unevaluated. These functions are suitable for use with rewrite
13082 rules (@pxref{Conditional Rewrite Rules}) or programming constructs
13083 (@pxref{Conditionals in Macros}). They can be entered only using
13084 algebraic notation. @xref{Logical Operations}, for functions
13085 that perform other tests not related to declarations.
13087 For example, @samp{dint(17)} returns 1 because 17 is an integer, as
13088 do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
13089 @code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
13090 Calc consults knowledge of its own built-in functions as well as your
13091 own declarations: @samp{dint(floor(x))} returns 1.
13099 The @code{dint} function checks if its argument is an integer.
13100 The @code{dnatnum} function checks if its argument is a natural
13101 number, i.e., a nonnegative integer. The @code{dnumint} function
13102 checks if its argument is numerically an integer, i.e., either an
13103 integer or an integer-valued float. Note that these and the other
13104 data type functions also accept vectors or matrices composed of
13105 suitable elements, and that real infinities @samp{inf} and @samp{-inf}
13106 are considered to be integers for the purposes of these functions.
13110 The @code{drat} function checks if its argument is rational, i.e.,
13111 an integer or fraction. Infinities count as rational, but intervals
13112 and error forms do not.
13116 The @code{dreal} function checks if its argument is real. This
13117 includes integers, fractions, floats, real error forms, and intervals.
13121 The @code{dimag} function checks if its argument is imaginary,
13122 i.e., is mathematically equal to a real number times @cite{i}.
13130 The @code{dpos} function checks for positive (but nonzero) reals.
13131 The @code{dneg} function checks for negative reals. The @code{dnonneg}
13132 function checks for nonnegative reals, i.e., reals greater than or
13133 equal to zero. Note that the @kbd{a s} command can simplify an
13134 expression like @cite{x > 0} to 1 or 0 using @code{dpos}, and that
13135 @kbd{a s} is effectively applied to all conditions in rewrite rules,
13136 so the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
13137 are rarely necessary.
13141 The @code{dnonzero} function checks that its argument is nonzero.
13142 This includes all nonzero real or complex numbers, all intervals that
13143 do not include zero, all nonzero modulo forms, vectors all of whose
13144 elements are nonzero, and variables or formulas whose values can be
13145 deduced to be nonzero. It does not include error forms, since they
13146 represent values which could be anything including zero. (This is
13147 also the set of objects considered ``true'' in conditional contexts.)
13153 The @code{deven} function returns 1 if its argument is known to be
13154 an even integer (or integer-valued float); it returns 0 if its argument
13155 is known not to be even (because it is known to be odd or a non-integer).
13156 The @kbd{a s} command uses this to simplify a test of the form
13157 @samp{x % 2 = 0}. There is also an analogous @code{dodd} function.
13161 The @code{drange} function returns a set (an interval or a vector
13162 of intervals and/or numbers; @pxref{Set Operations}) that describes
13163 the set of possible values of its argument. If the argument is
13164 a variable or a function with a declaration, the range is copied
13165 from the declaration. Otherwise, the possible signs of the
13166 expression are determined using a method similar to @code{dpos},
13167 etc., and a suitable set like @samp{[0 .. inf]} is returned. If
13168 the expression is not provably real, the @code{drange} function
13169 remains unevaluated.
13173 The @code{dscalar} function returns 1 if its argument is provably
13174 scalar, or 0 if its argument is provably non-scalar. It is left
13175 unevaluated if this cannot be determined. (If matrix mode or scalar
13176 mode are in effect, this function returns 1 or 0, respectively,
13177 if it has no other information.) When Calc interprets a condition
13178 (say, in a rewrite rule) it considers an unevaluated formula to be
13179 ``false.'' Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
13180 provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
13181 is provably non-scalar; both are ``false'' if there is insufficient
13182 information to tell.
13184 @node Display Modes, Language Modes, Declarations, Mode Settings
13185 @section Display Modes
13188 The commands in this section are two-key sequences beginning with the
13189 @kbd{d} prefix. The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
13190 (@code{calc-line-breaking}) commands are described elsewhere;
13191 @pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
13192 Display formats for vectors and matrices are also covered elsewhere;
13193 @pxref{Vector and Matrix Formats}.@refill
13195 One thing all display modes have in common is their treatment of the
13196 @kbd{H} prefix. This prefix causes any mode command that would normally
13197 refresh the stack to leave the stack display alone. The word ``Dirty''
13198 will appear in the mode line when Calc thinks the stack display may not
13199 reflect the latest mode settings.
13202 @pindex calc-refresh-top
13203 The @kbd{d RET} (@code{calc-refresh-top}) command reformats the
13204 top stack entry according to all the current modes. Positive prefix
13205 arguments reformat the top @var{n} entries; negative prefix arguments
13206 reformat the specified entry, and a prefix of zero is equivalent to
13207 @kbd{d SPC} (@code{calc-refresh}), which reformats the entire stack.
13208 For example, @kbd{H d s M-2 d RET} changes to scientific notation
13209 but reformats only the top two stack entries in the new mode.
13211 The @kbd{I} prefix has another effect on the display modes. The mode
13212 is set only temporarily; the top stack entry is reformatted according
13213 to that mode, then the original mode setting is restored. In other
13214 words, @kbd{I d s} is equivalent to @kbd{H d s d RET H d @var{(old mode)}}.
13218 * Grouping Digits::
13220 * Complex Formats::
13221 * Fraction Formats::
13224 * Truncating the Stack::
13229 @node Radix Modes, Grouping Digits, Display Modes, Display Modes
13230 @subsection Radix Modes
13233 @cindex Radix display
13234 @cindex Non-decimal numbers
13235 @cindex Decimal and non-decimal numbers
13236 Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
13237 notation. Calc can actually display in any radix from two (binary) to 36.
13238 When the radix is above 10, the letters @code{A} to @code{Z} are used as
13239 digits. When entering such a number, letter keys are interpreted as
13240 potential digits rather than terminating numeric entry mode.
13246 @cindex Hexadecimal integers
13247 @cindex Octal integers
13248 The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
13249 binary, octal, hexadecimal, and decimal as the current display radix,
13250 respectively. Numbers can always be entered in any radix, though the
13251 current radix is used as a default if you press @kbd{#} without any initial
13252 digits. A number entered without a @kbd{#} is @emph{always} interpreted
13257 To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
13258 an integer from 2 to 36. You can specify the radix as a numeric prefix
13259 argument; otherwise you will be prompted for it.
13262 @pindex calc-leading-zeros
13263 @cindex Leading zeros
13264 Integers normally are displayed with however many digits are necessary to
13265 represent the integer and no more. The @kbd{d z} (@code{calc-leading-zeros})
13266 command causes integers to be padded out with leading zeros according to the
13267 current binary word size. (@xref{Binary Functions}, for a discussion of
13268 word size.) If the absolute value of the word size is @cite{w}, all integers
13269 are displayed with at least enough digits to represent @c{$2^w-1$}
13270 @cite{(2^w)-1} in the
13271 current radix. (Larger integers will still be displayed in their entirety.)
13273 @node Grouping Digits, Float Formats, Radix Modes, Display Modes
13274 @subsection Grouping Digits
13278 @pindex calc-group-digits
13279 @cindex Grouping digits
13280 @cindex Digit grouping
13281 Long numbers can be hard to read if they have too many digits. For
13282 example, the factorial of 30 is 33 digits long! Press @kbd{d g}
13283 (@code{calc-group-digits}) to enable @dfn{grouping} mode, in which digits
13284 are displayed in clumps of 3 or 4 (depending on the current radix)
13285 separated by commas.
13287 The @kbd{d g} command toggles grouping on and off.
13288 With a numerix prefix of 0, this command displays the current state of
13289 the grouping flag; with an argument of minus one it disables grouping;
13290 with a positive argument @cite{N} it enables grouping on every @cite{N}
13291 digits. For floating-point numbers, grouping normally occurs only
13292 before the decimal point. A negative prefix argument @cite{-N} enables
13293 grouping every @cite{N} digits both before and after the decimal point.@refill
13296 @pindex calc-group-char
13297 The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
13298 character as the grouping separator. The default is the comma character.
13299 If you find it difficult to read vectors of large integers grouped with
13300 commas, you may wish to use spaces or some other character instead.
13301 This command takes the next character you type, whatever it is, and
13302 uses it as the digit separator. As a special case, @kbd{d , \} selects
13303 @samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
13305 Please note that grouped numbers will not generally be parsed correctly
13306 if re-read in textual form, say by the use of @kbd{M-# y} and @kbd{M-# g}.
13307 (@xref{Kill and Yank}, for details on these commands.) One exception is
13308 the @samp{\,} separator, which doesn't interfere with parsing because it
13309 is ignored by @TeX{} language mode.
13311 @node Float Formats, Complex Formats, Grouping Digits, Display Modes
13312 @subsection Float Formats
13315 Floating-point quantities are normally displayed in standard decimal
13316 form, with scientific notation used if the exponent is especially high
13317 or low. All significant digits are normally displayed. The commands
13318 in this section allow you to choose among several alternative display
13319 formats for floats.
13322 @pindex calc-normal-notation
13323 The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
13324 display format. All significant figures in a number are displayed.
13325 With a positive numeric prefix, numbers are rounded if necessary to
13326 that number of significant digits. With a negative numerix prefix,
13327 the specified number of significant digits less than the current
13328 precision is used. (Thus @kbd{C-u -2 d n} displays 10 digits if the
13329 current precision is 12.)
13332 @pindex calc-fix-notation
13333 The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
13334 notation. The numeric argument is the number of digits after the
13335 decimal point, zero or more. This format will relax into scientific
13336 notation if a nonzero number would otherwise have been rounded all the
13337 way to zero. Specifying a negative number of digits is the same as
13338 for a positive number, except that small nonzero numbers will be rounded
13339 to zero rather than switching to scientific notation.
13342 @pindex calc-sci-notation
13343 @cindex Scientific notation, display of
13344 The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
13345 notation. A positive argument sets the number of significant figures
13346 displayed, of which one will be before and the rest after the decimal
13347 point. A negative argument works the same as for @kbd{d n} format.
13348 The default is to display all significant digits.
13351 @pindex calc-eng-notation
13352 @cindex Engineering notation, display of
13353 The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
13354 notation. This is similar to scientific notation except that the
13355 exponent is rounded down to a multiple of three, with from one to three
13356 digits before the decimal point. An optional numeric prefix sets the
13357 number of significant digits to display, as for @kbd{d s}.
13359 It is important to distinguish between the current @emph{precision} and
13360 the current @emph{display format}. After the commands @kbd{C-u 10 p}
13361 and @kbd{C-u 6 d n} the Calculator computes all results to ten
13362 significant figures but displays only six. (In fact, intermediate
13363 calculations are often carried to one or two more significant figures,
13364 but values placed on the stack will be rounded down to ten figures.)
13365 Numbers are never actually rounded to the display precision for storage,
13366 except by commands like @kbd{C-k} and @kbd{M-# y} which operate on the
13367 actual displayed text in the Calculator buffer.
13370 @pindex calc-point-char
13371 The @kbd{d .} (@code{calc-point-char}) command selects the character used
13372 as a decimal point. Normally this is a period; users in some countries
13373 may wish to change this to a comma. Note that this is only a display
13374 style; on entry, periods must always be used to denote floating-point
13375 numbers, and commas to separate elements in a list.
13377 @node Complex Formats, Fraction Formats, Float Formats, Display Modes
13378 @subsection Complex Formats
13382 @pindex calc-complex-notation
13383 There are three supported notations for complex numbers in rectangular
13384 form. The default is as a pair of real numbers enclosed in parentheses
13385 and separated by a comma: @samp{(a,b)}. The @kbd{d c}
13386 (@code{calc-complex-notation}) command selects this style.@refill
13389 @pindex calc-i-notation
13391 @pindex calc-j-notation
13392 The other notations are @kbd{d i} (@code{calc-i-notation}), in which
13393 numbers are displayed in @samp{a+bi} form, and @kbd{d j}
13394 (@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
13395 in some disciplines.@refill
13397 @cindex @code{i} variable
13399 Complex numbers are normally entered in @samp{(a,b)} format.
13400 If you enter @samp{2+3i} as an algebraic formula, it will be stored as
13401 the formula @samp{2 + 3 * i}. However, if you use @kbd{=} to evaluate
13402 this formula and you have not changed the variable @samp{i}, the @samp{i}
13403 will be interpreted as @samp{(0,1)} and the formula will be simplified
13404 to @samp{(2,3)}. Other commands (like @code{calc-sin}) will @emph{not}
13405 interpret the formula @samp{2 + 3 * i} as a complex number.
13406 @xref{Variables}, under ``special constants.''@refill
13408 @node Fraction Formats, HMS Formats, Complex Formats, Display Modes
13409 @subsection Fraction Formats
13413 @pindex calc-over-notation
13414 Display of fractional numbers is controlled by the @kbd{d o}
13415 (@code{calc-over-notation}) command. By default, a number like
13416 eight thirds is displayed in the form @samp{8:3}. The @kbd{d o} command
13417 prompts for a one- or two-character format. If you give one character,
13418 that character is used as the fraction separator. Common separators are
13419 @samp{:} and @samp{/}. (During input of numbers, the @kbd{:} key must be
13420 used regardless of the display format; in particular, the @kbd{/} is used
13421 for RPN-style division, @emph{not} for entering fractions.)
13423 If you give two characters, fractions use ``integer-plus-fractional-part''
13424 notation. For example, the format @samp{+/} would display eight thirds
13425 as @samp{2+2/3}. If two colons are present in a number being entered,
13426 the number is interpreted in this form (so that the entries @kbd{2:2:3}
13427 and @kbd{8:3} are equivalent).
13429 It is also possible to follow the one- or two-character format with
13430 a number. For example: @samp{:10} or @samp{+/3}. In this case,
13431 Calc adjusts all fractions that are displayed to have the specified
13432 denominator, if possible. Otherwise it adjusts the denominator to
13433 be a multiple of the specified value. For example, in @samp{:6} mode
13434 the fraction @cite{1:6} will be unaffected, but @cite{2:3} will be
13435 displayed as @cite{4:6}, @cite{1:2} will be displayed as @cite{3:6},
13436 and @cite{1:8} will be displayed as @cite{3:24}. Integers are also
13437 affected by this mode: 3 is displayed as @cite{18:6}. Note that the
13438 format @samp{:1} writes fractions the same as @samp{:}, but it writes
13439 integers as @cite{n:1}.
13441 The fraction format does not affect the way fractions or integers are
13442 stored, only the way they appear on the screen. The fraction format
13443 never affects floats.
13445 @node HMS Formats, Date Formats, Fraction Formats, Display Modes
13446 @subsection HMS Formats
13450 @pindex calc-hms-notation
13451 The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
13452 HMS (hours-minutes-seconds) forms. It prompts for a string which
13453 consists basically of an ``hours'' marker, optional punctuation, a
13454 ``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
13455 Punctuation is zero or more spaces, commas, or semicolons. The hours
13456 marker is one or more non-punctuation characters. The minutes and
13457 seconds markers must be single non-punctuation characters.
13459 The default HMS format is @samp{@@ ' "}, producing HMS values of the form
13460 @samp{23@@ 30' 15.75"}. The format @samp{deg, ms} would display this same
13461 value as @samp{23deg, 30m15.75s}. During numeric entry, the @kbd{h} or @kbd{o}
13462 keys are recognized as synonyms for @kbd{@@} regardless of display format.
13463 The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
13464 @kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
13465 already been typed; otherwise, they have their usual meanings
13466 (@kbd{m-} prefix and @kbd{s-} prefix). Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
13467 @kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
13468 The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
13469 @kbd{o}) has already been pressed; otherwise it means to switch to algebraic
13472 @node Date Formats, Truncating the Stack, HMS Formats, Display Modes
13473 @subsection Date Formats
13477 @pindex calc-date-notation
13478 The @kbd{d d} (@code{calc-date-notation}) command controls the display
13479 of date forms (@pxref{Date Forms}). It prompts for a string which
13480 contains letters that represent the various parts of a date and time.
13481 To show which parts should be omitted when the form represents a pure
13482 date with no time, parts of the string can be enclosed in @samp{< >}
13483 marks. If you don't include @samp{< >} markers in the format, Calc
13484 guesses at which parts, if any, should be omitted when formatting
13487 The default format is: @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
13488 An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
13489 If you enter a blank format string, this default format is
13492 Calc uses @samp{< >} notation for nameless functions as well as for
13493 dates. @xref{Specifying Operators}. To avoid confusion with nameless
13494 functions, your date formats should avoid using the @samp{#} character.
13497 * Date Formatting Codes::
13498 * Free-Form Dates::
13499 * Standard Date Formats::
13502 @node Date Formatting Codes, Free-Form Dates, Date Formats, Date Formats
13503 @subsubsection Date Formatting Codes
13506 When displaying a date, the current date format is used. All
13507 characters except for letters and @samp{<} and @samp{>} are
13508 copied literally when dates are formatted. The portion between
13509 @samp{< >} markers is omitted for pure dates, or included for
13510 date/time forms. Letters are interpreted according to the table
13513 When dates are read in during algebraic entry, Calc first tries to
13514 match the input string to the current format either with or without
13515 the time part. The punctuation characters (including spaces) must
13516 match exactly; letter fields must correspond to suitable text in
13517 the input. If this doesn't work, Calc checks if the input is a
13518 simple number; if so, the number is interpreted as a number of days
13519 since Jan 1, 1 AD. Otherwise, Calc tries a much more relaxed and
13520 flexible algorithm which is described in the next section.
13522 Weekday names are ignored during reading.
13524 Two-digit year numbers are interpreted as lying in the range
13525 from 1941 to 2039. Years outside that range are always
13526 entered and displayed in full. Year numbers with a leading
13527 @samp{+} sign are always interpreted exactly, allowing the
13528 entry and display of the years 1 through 99 AD.
13530 Here is a complete list of the formatting codes for dates:
13534 Year: ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
13536 Year: ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
13538 Year: ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
13540 Year: ``1991'' for 1991, ``23'' for 23 AD.
13542 Year: ``1991'' for 1991, ``+23'' for 23 AD.
13544 Year: ``ad'' or blank.
13546 Year: ``AD'' or blank.
13548 Year: ``ad '' or blank. (Note trailing space.)
13550 Year: ``AD '' or blank.
13552 Year: ``a.d.'' or blank.
13554 Year: ``A.D.'' or blank.
13556 Year: ``bc'' or blank.
13558 Year: ``BC'' or blank.
13560 Year: `` bc'' or blank. (Note leading space.)
13562 Year: `` BC'' or blank.
13564 Year: ``b.c.'' or blank.
13566 Year: ``B.C.'' or blank.
13568 Month: ``8'' for August.
13570 Month: ``08'' for August.
13572 Month: `` 8'' for August.
13574 Month: ``AUG'' for August.
13576 Month: ``Aug'' for August.
13578 Month: ``aug'' for August.
13580 Month: ``AUGUST'' for August.
13582 Month: ``August'' for August.
13584 Day: ``7'' for 7th day of month.
13586 Day: ``07'' for 7th day of month.
13588 Day: `` 7'' for 7th day of month.
13590 Weekday: ``0'' for Sunday, ``6'' for Saturday.
13592 Weekday: ``SUN'' for Sunday.
13594 Weekday: ``Sun'' for Sunday.
13596 Weekday: ``sun'' for Sunday.
13598 Weekday: ``SUNDAY'' for Sunday.
13600 Weekday: ``Sunday'' for Sunday.
13602 Day of year: ``34'' for Feb. 3.
13604 Day of year: ``034'' for Feb. 3.
13606 Day of year: `` 34'' for Feb. 3.
13608 Hour: ``5'' for 5 AM; ``17'' for 5 PM.
13610 Hour: ``05'' for 5 AM; ``17'' for 5 PM.
13612 Hour: `` 5'' for 5 AM; ``17'' for 5 PM.
13614 Hour: ``5'' for 5 AM and 5 PM.
13616 Hour: ``05'' for 5 AM and 5 PM.
13618 Hour: `` 5'' for 5 AM and 5 PM.
13620 AM/PM: ``a'' or ``p''.
13622 AM/PM: ``A'' or ``P''.
13624 AM/PM: ``am'' or ``pm''.
13626 AM/PM: ``AM'' or ``PM''.
13628 AM/PM: ``a.m.'' or ``p.m.''.
13630 AM/PM: ``A.M.'' or ``P.M.''.
13632 Minutes: ``7'' for 7.
13634 Minutes: ``07'' for 7.
13636 Minutes: `` 7'' for 7.
13638 Seconds: ``7'' for 7; ``7.23'' for 7.23.
13640 Seconds: ``07'' for 7; ``07.23'' for 7.23.
13642 Seconds: `` 7'' for 7; `` 7.23'' for 7.23.
13644 Optional seconds: ``07'' for 7; blank for 0.
13646 Optional seconds: `` 7'' for 7; blank for 0.
13648 Numeric date/time: ``726842.25'' for 6:00am Wed Jan 9, 1991.
13650 Numeric date: ``726842'' for any time on Wed Jan 9, 1991.
13652 Julian date/time: ``2448265.75'' for 6:00am Wed Jan 9, 1991.
13654 Julian date: ``2448266'' for any time on Wed Jan 9, 1991.
13656 Unix time: ``663400800'' for 6:00am Wed Jan 9, 1991.
13658 Brackets suppression. An ``X'' at the front of the format
13659 causes the surrounding @w{@samp{< >}} delimiters to be omitted
13660 when formatting dates. Note that the brackets are still
13661 required for algebraic entry.
13664 If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
13665 colon is also omitted if the seconds part is zero.
13667 If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
13668 appear in the format, then negative year numbers are displayed
13669 without a minus sign. Note that ``aa'' and ``bb'' are mutually
13670 exclusive. Some typical usages would be @samp{YYYY AABB};
13671 @samp{AAAYYYYBBB}; @samp{YYYYBBB}.
13673 The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
13674 ``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
13675 reading unless several of these codes are strung together with no
13676 punctuation in between, in which case the input must have exactly as
13677 many digits as there are letters in the format.
13679 The ``j,'' ``J,'' and ``U'' formats do not make any time zone
13680 adjustment. They effectively use @samp{julian(x,0)} and
13681 @samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
13683 @node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
13684 @subsubsection Free-Form Dates
13687 When reading a date form during algebraic entry, Calc falls back
13688 on the algorithm described here if the input does not exactly
13689 match the current date format. This algorithm generally
13690 ``does the right thing'' and you don't have to worry about it,
13691 but it is described here in full detail for the curious.
13693 Calc does not distinguish between upper- and lower-case letters
13694 while interpreting dates.
13696 First, the time portion, if present, is located somewhere in the
13697 text and then removed. The remaining text is then interpreted as
13700 A time is of the form @samp{hh:mm:ss}, possibly with the seconds
13701 part omitted and possibly with an AM/PM indicator added to indicate
13702 12-hour time. If the AM/PM is present, the minutes may also be
13703 omitted. The AM/PM part may be any of the words @samp{am},
13704 @samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
13705 abbreviated to one letter, and the alternate forms @samp{a.m.},
13706 @samp{p.m.}, and @samp{mid} are also understood. Obviously
13707 @samp{noon} and @samp{midnight} are allowed only on 12:00:00.
13708 The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
13709 recognized with no number attached.
13711 If there is no AM/PM indicator, the time is interpreted in 24-hour
13714 To read the date portion, all words and numbers are isolated
13715 from the string; other characters are ignored. All words must
13716 be either month names or day-of-week names (the latter of which
13717 are ignored). Names can be written in full or as three-letter
13720 Large numbers, or numbers with @samp{+} or @samp{-} signs,
13721 are interpreted as years. If one of the other numbers is
13722 greater than 12, then that must be the day and the remaining
13723 number in the input is therefore the month. Otherwise, Calc
13724 assumes the month, day and year are in the same order that they
13725 appear in the current date format. If the year is omitted, the
13726 current year is taken from the system clock.
13728 If there are too many or too few numbers, or any unrecognizable
13729 words, then the input is rejected.
13731 If there are any large numbers (of five digits or more) other than
13732 the year, they are ignored on the assumption that they are something
13733 like Julian dates that were included along with the traditional
13734 date components when the date was formatted.
13736 One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
13737 may optionally be used; the latter two are equivalent to a
13738 minus sign on the year value.
13740 If you always enter a four-digit year, and use a name instead
13741 of a number for the month, there is no danger of ambiguity.
13743 @node Standard Date Formats, , Free-Form Dates, Date Formats
13744 @subsubsection Standard Date Formats
13747 There are actually ten standard date formats, numbered 0 through 9.
13748 Entering a blank line at the @kbd{d d} command's prompt gives
13749 you format number 1, Calc's usual format. You can enter any digit
13750 to select the other formats.
13752 To create your own standard date formats, give a numeric prefix
13753 argument from 0 to 9 to the @w{@kbd{d d}} command. The format you
13754 enter will be recorded as the new standard format of that
13755 number, as well as becoming the new current date format.
13756 You can save your formats permanently with the @w{@kbd{m m}}
13757 command (@pxref{Mode Settings}).
13761 @samp{N} (Numerical format)
13763 @samp{<H:mm:SSpp >Www Mmm D, YYYY} (American format)
13765 @samp{D Mmm YYYY<, h:mm:SS>} (European format)
13767 @samp{Www Mmm BD< hh:mm:ss> YYYY} (Unix written date format)
13769 @samp{M/D/Y< H:mm:SSpp>} (American slashed format)
13771 @samp{D.M.Y< h:mm:SS>} (European dotted format)
13773 @samp{M-D-Y< H:mm:SSpp>} (American dashed format)
13775 @samp{D-M-Y< h:mm:SS>} (European dashed format)
13777 @samp{j<, h:mm:ss>} (Julian day plus time)
13779 @samp{YYddd< hh:mm:ss>} (Year-day format)
13782 @node Truncating the Stack, Justification, Date Formats, Display Modes
13783 @subsection Truncating the Stack
13787 @pindex calc-truncate-stack
13788 @cindex Truncating the stack
13789 @cindex Narrowing the stack
13790 The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
13791 line that marks the top-of-stack up or down in the Calculator buffer.
13792 The number right above that line is considered to the be at the top of
13793 the stack. Any numbers below that line are ``hidden'' from all stack
13794 operations. This is similar to the Emacs ``narrowing'' feature, except
13795 that the values below the @samp{.} are @emph{visible}, just temporarily
13796 frozen. This feature allows you to keep several independent calculations
13797 running at once in different parts of the stack, or to apply a certain
13798 command to an element buried deep in the stack.@refill
13800 Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
13801 is on. Thus, this line and all those below it become hidden. To un-hide
13802 these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
13803 With a positive numeric prefix argument @cite{n}, @kbd{d t} hides the
13804 bottom @cite{n} values in the buffer. With a negative argument, it hides
13805 all but the top @cite{n} values. With an argument of zero, it hides zero
13806 values, i.e., moves the @samp{.} all the way down to the bottom.@refill
13809 @pindex calc-truncate-up
13811 @pindex calc-truncate-down
13812 The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
13813 (@code{calc-truncate-down}) commands move the @samp{.} up or down one
13814 line at a time (or several lines with a prefix argument).@refill
13816 @node Justification, Labels, Truncating the Stack, Display Modes
13817 @subsection Justification
13821 @pindex calc-left-justify
13823 @pindex calc-center-justify
13825 @pindex calc-right-justify
13826 Values on the stack are normally left-justified in the window. You can
13827 control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
13828 @kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
13829 (@code{calc-center-justify}). For example, in right-justification mode,
13830 stack entries are displayed flush-right against the right edge of the
13833 If you change the width of the Calculator window you may have to type
13834 @kbd{d SPC} (@code{calc-refresh}) to re-align right-justified or centered
13837 Right-justification is especially useful together with fixed-point
13838 notation (see @code{d f}; @code{calc-fix-notation}). With these modes
13839 together, the decimal points on numbers will always line up.
13841 With a numeric prefix argument, the justification commands give you
13842 a little extra control over the display. The argument specifies the
13843 horizontal ``origin'' of a display line. It is also possible to
13844 specify a maximum line width using the @kbd{d b} command (@pxref{Normal
13845 Language Modes}). For reference, the precise rules for formatting and
13846 breaking lines are given below. Notice that the interaction between
13847 origin and line width is slightly different in each justification
13850 In left-justified mode, the line is indented by a number of spaces
13851 given by the origin (default zero). If the result is longer than the
13852 maximum line width, if given, or too wide to fit in the Calc window
13853 otherwise, then it is broken into lines which will fit; each broken
13854 line is indented to the origin.
13856 In right-justified mode, lines are shifted right so that the rightmost
13857 character is just before the origin, or just before the current
13858 window width if no origin was specified. If the line is too long
13859 for this, then it is broken; the current line width is used, if
13860 specified, or else the origin is used as a width if that is
13861 specified, or else the line is broken to fit in the window.
13863 In centering mode, the origin is the column number of the center of
13864 each stack entry. If a line width is specified, lines will not be
13865 allowed to go past that width; Calc will either indent less or
13866 break the lines if necessary. If no origin is specified, half the
13867 line width or Calc window width is used.
13869 Note that, in each case, if line numbering is enabled the display
13870 is indented an additional four spaces to make room for the line
13871 number. The width of the line number is taken into account when
13872 positioning according to the current Calc window width, but not
13873 when positioning by explicit origins and widths. In the latter
13874 case, the display is formatted as specified, and then uniformly
13875 shifted over four spaces to fit the line numbers.
13877 @node Labels, , Justification, Display Modes
13882 @pindex calc-left-label
13883 The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
13884 then displays that string to the left of every stack entry. If the
13885 entries are left-justified (@pxref{Justification}), then they will
13886 appear immediately after the label (unless you specified an origin
13887 greater than the length of the label). If the entries are centered
13888 or right-justified, the label appears on the far left and does not
13889 affect the horizontal position of the stack entry.
13891 Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
13894 @pindex calc-right-label
13895 The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
13896 label on the righthand side. It does not affect positioning of
13897 the stack entries unless they are right-justified. Also, if both
13898 a line width and an origin are given in right-justified mode, the
13899 stack entry is justified to the origin and the righthand label is
13900 justified to the line width.
13902 One application of labels would be to add equation numbers to
13903 formulas you are manipulating in Calc and then copying into a
13904 document (possibly using Embedded Mode). The equations would
13905 typically be centered, and the equation numbers would be on the
13906 left or right as you prefer.
13908 @node Language Modes, Modes Variable, Display Modes, Mode Settings
13909 @section Language Modes
13912 The commands in this section change Calc to use a different notation for
13913 entry and display of formulas, corresponding to the conventions of some
13914 other common language such as Pascal or @TeX{}. Objects displayed on the
13915 stack or yanked from the Calculator to an editing buffer will be formatted
13916 in the current language; objects entered in algebraic entry or yanked from
13917 another buffer will be interpreted according to the current language.
13919 The current language has no effect on things written to or read from the
13920 trail buffer, nor does it affect numeric entry. Only algebraic entry is
13921 affected. You can make even algebraic entry ignore the current language
13922 and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
13924 For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
13925 program; elsewhere in the program you need the derivatives of this formula
13926 with respect to @samp{a[1]} and @samp{a[2]}. First, type @kbd{d C}
13927 to switch to C notation. Now use @code{C-u M-# g} to grab the formula
13928 into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
13929 to the first variable, and @kbd{M-# y} to yank the formula for the derivative
13930 back into your C program. Press @kbd{U} to undo the differentiation and
13931 repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
13933 Without being switched into C mode first, Calc would have misinterpreted
13934 the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
13935 @code{atan} was equivalent to Calc's built-in @code{arctan} function,
13936 and would have written the formula back with notations (like implicit
13937 multiplication) which would not have been legal for a C program.
13939 As another example, suppose you are maintaining a C program and a @TeX{}
13940 document, each of which needs a copy of the same formula. You can grab the
13941 formula from the program in C mode, switch to @TeX{} mode, and yank the
13942 formula into the document in @TeX{} math-mode format.
13944 Language modes are selected by typing the letter @kbd{d} followed by a
13945 shifted letter key.
13948 * Normal Language Modes::
13949 * C FORTRAN Pascal::
13950 * TeX Language Mode::
13951 * Eqn Language Mode::
13952 * Mathematica Language Mode::
13953 * Maple Language Mode::
13958 @node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
13959 @subsection Normal Language Modes
13963 @pindex calc-normal-language
13964 The @kbd{d N} (@code{calc-normal-language}) command selects the usual
13965 notation for Calc formulas, as described in the rest of this manual.
13966 Matrices are displayed in a multi-line tabular format, but all other
13967 objects are written in linear form, as they would be typed from the
13971 @pindex calc-flat-language
13972 @cindex Matrix display
13973 The @kbd{d O} (@code{calc-flat-language}) command selects a language
13974 identical with the normal one, except that matrices are written in
13975 one-line form along with everything else. In some applications this
13976 form may be more suitable for yanking data into other buffers.
13979 @pindex calc-line-breaking
13980 @cindex Line breaking
13981 @cindex Breaking up long lines
13982 Even in one-line mode, long formulas or vectors will still be split
13983 across multiple lines if they exceed the width of the Calculator window.
13984 The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
13985 feature on and off. (It works independently of the current language.)
13986 If you give a numeric prefix argument of five or greater to the @kbd{d b}
13987 command, that argument will specify the line width used when breaking
13991 @pindex calc-big-language
13992 The @kbd{d B} (@code{calc-big-language}) command selects a language
13993 which uses textual approximations to various mathematical notations,
13994 such as powers, quotients, and square roots:
14004 in place of @samp{sqrt((a+1)/b + c^2)}.
14006 Subscripts like @samp{a_i} are displayed as actual subscripts in ``big''
14007 mode. Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
14008 are displayed as @samp{a} with subscripts separated by commas:
14009 @samp{i, j}. They must still be entered in the usual underscore
14012 One slight ambiguity of Big notation is that
14021 can represent either the negative rational number @cite{-3:4}, or the
14022 actual expression @samp{-(3/4)}; but the latter formula would normally
14023 never be displayed because it would immediately be evaluated to
14024 @cite{-3:4} or @cite{-0.75}, so this ambiguity is not a problem in
14027 Non-decimal numbers are displayed with subscripts. Thus there is no
14028 way to tell the difference between @samp{16#C2} and @samp{C2_16},
14029 though generally you will know which interpretation is correct.
14030 Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
14033 In Big mode, stack entries often take up several lines. To aid
14034 readability, stack entries are separated by a blank line in this mode.
14035 You may find it useful to expand the Calc window's height using
14036 @kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
14037 one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
14039 Long lines are currently not rearranged to fit the window width in
14040 Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
14041 to scroll across a wide formula. For really big formulas, you may
14042 even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
14045 @pindex calc-unformatted-language
14046 The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
14047 the use of operator notation in formulas. In this mode, the formula
14048 shown above would be displayed:
14051 sqrt(add(div(add(a, 1), b), pow(c, 2)))
14054 These four modes differ only in display format, not in the format
14055 expected for algebraic entry. The standard Calc operators work in
14056 all four modes, and unformatted notation works in any language mode
14057 (except that Mathematica mode expects square brackets instead of
14060 @node C FORTRAN Pascal, TeX Language Mode, Normal Language Modes, Language Modes
14061 @subsection C, FORTRAN, and Pascal Modes
14065 @pindex calc-c-language
14067 The @kbd{d C} (@code{calc-c-language}) command selects the conventions
14068 of the C language for display and entry of formulas. This differs from
14069 the normal language mode in a variety of (mostly minor) ways. In
14070 particular, C language operators and operator precedences are used in
14071 place of Calc's usual ones. For example, @samp{a^b} means @samp{xor(a,b)}
14072 in C mode; a value raised to a power is written as a function call,
14075 In C mode, vectors and matrices use curly braces instead of brackets.
14076 Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
14077 rather than using the @samp{#} symbol. Array subscripting is
14078 translated into @code{subscr} calls, so that @samp{a[i]} in C
14079 mode is the same as @samp{a_i} in normal mode. Assignments
14080 turn into the @code{assign} function, which Calc normally displays
14081 using the @samp{:=} symbol.
14083 The variables @code{var-pi} and @code{var-e} would be displayed @samp{pi}
14084 and @samp{e} in normal mode, but in C mode they are displayed as
14085 @samp{M_PI} and @samp{M_E}, corresponding to the names of constants
14086 typically provided in the @file{<math.h>} header. Functions whose
14087 names are different in C are translated automatically for entry and
14088 display purposes. For example, entering @samp{asin(x)} will push the
14089 formula @samp{arcsin(x)} onto the stack; this formula will be displayed
14090 as @samp{asin(x)} as long as C mode is in effect.
14093 @pindex calc-pascal-language
14094 @cindex Pascal language
14095 The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
14096 conventions. Like C mode, Pascal mode interprets array brackets and uses
14097 a different table of operators. Hexadecimal numbers are entered and
14098 displayed with a preceding dollar sign. (Thus the regular meaning of
14099 @kbd{$2} during algebraic entry does not work in Pascal mode, though
14100 @kbd{$} (and @kbd{$$}, etc.) not followed by digits works the same as
14101 always.) No special provisions are made for other non-decimal numbers,
14102 vectors, and so on, since there is no universally accepted standard way
14103 of handling these in Pascal.
14106 @pindex calc-fortran-language
14107 @cindex FORTRAN language
14108 The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
14109 conventions. Various function names are transformed into FORTRAN
14110 equivalents. Vectors are written as @samp{/1, 2, 3/}, and may be
14111 entered this way or using square brackets. Since FORTRAN uses round
14112 parentheses for both function calls and array subscripts, Calc displays
14113 both in the same way; @samp{a(i)} is interpreted as a function call
14114 upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
14115 Also, if the variable @code{a} has been declared to have type
14116 @code{vector} or @code{matrix} then @samp{a(i)} will be parsed as a
14117 subscript. (@xref{Declarations}.) Usually it doesn't matter, though;
14118 if you enter the subscript expression @samp{a(i)} and Calc interprets
14119 it as a function call, you'll never know the difference unless you
14120 switch to another language mode or replace @code{a} with an actual
14121 vector (or unless @code{a} happens to be the name of a built-in
14124 Underscores are allowed in variable and function names in all of these
14125 language modes. The underscore here is equivalent to the @samp{#} in
14126 normal mode, or to hyphens in the underlying Emacs Lisp variable names.
14128 FORTRAN and Pascal modes normally do not adjust the case of letters in
14129 formulas. Most built-in Calc names use lower-case letters. If you use a
14130 positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
14131 modes will use upper-case letters exclusively for display, and will
14132 convert to lower-case on input. With a negative prefix, these modes
14133 convert to lower-case for display and input.
14135 @node TeX Language Mode, Eqn Language Mode, C FORTRAN Pascal, Language Modes
14136 @subsection @TeX{} Language Mode
14140 @pindex calc-tex-language
14141 @cindex TeX language
14142 The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
14143 of ``math mode'' in the @TeX{} typesetting language, by Donald Knuth.
14144 Formulas are entered
14145 and displayed in @TeX{} notation, as in @samp{\sin\left( a \over b \right)}.
14146 Math formulas are usually enclosed by @samp{$ $} signs in @TeX{}; these
14147 should be omitted when interfacing with Calc. To Calc, the @samp{$} sign
14148 has the same meaning it always does in algebraic formulas (a reference to
14149 an existing entry on the stack).@refill
14151 Complex numbers are displayed as in @samp{3 + 4i}. Fractions and
14152 quotients are written using @code{\over};
14153 binomial coefficients are written with @code{\choose}.
14154 Interval forms are written with @code{\ldots}, and
14155 error forms are written with @code{\pm}.
14156 Absolute values are written as in @samp{|x + 1|}, and the floor and
14157 ceiling functions are written with @code{\lfloor}, @code{\rfloor}, etc.
14158 The words @code{\left} and @code{\right} are ignored when reading
14159 formulas in @TeX{} mode. Both @code{inf} and @code{uinf} are written
14160 as @code{\infty}; when read, @code{\infty} always translates to
14163 Function calls are written the usual way, with the function name followed
14164 by the arguments in parentheses. However, functions for which @TeX{} has
14165 special names (like @code{\sin}) will use curly braces instead of
14166 parentheses for very simple arguments. During input, curly braces and
14167 parentheses work equally well for grouping, but when the document is
14168 formatted the curly braces will be invisible. Thus the printed result is
14170 @cite{sin 2x} but @c{$\sin(2 + x)$}
14173 Function and variable names not treated specially by @TeX{} are simply
14174 written out as-is, which will cause them to come out in italic letters
14175 in the printed document. If you invoke @kbd{d T} with a positive numeric
14176 prefix argument, names of more than one character will instead be written
14177 @samp{\hbox@{@var{name}@}}. The @samp{\hbox@{ @}} notation is ignored
14178 during reading. If you use a negative prefix argument, such function
14179 names are written @samp{\@var{name}}, and function names that begin
14180 with @code{\} during reading have the @code{\} removed. (Note that
14181 in this mode, long variable names are still written with @code{\hbox}.
14182 However, you can always make an actual variable name like @code{\bar}
14183 in any @TeX{} mode.)
14185 During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
14186 by @samp{[ ...@: ]}. The same also applies to @code{\pmatrix} and
14187 @code{\bmatrix}. The symbol @samp{&} is interpreted as a comma,
14188 and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
14189 During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
14190 format; you may need to edit this afterwards to change @code{\matrix}
14191 to @code{\pmatrix} or @code{\\} to @code{\cr}.
14193 Accents like @code{\tilde} and @code{\bar} translate into function
14194 calls internally (@samp{tilde(x)}, @samp{bar(x)}). The @code{\underline}
14195 sequence is treated as an accent. The @code{\vec} accent corresponds
14196 to the function name @code{Vec}, because @code{vec} is the name of
14197 a built-in Calc function. The following table shows the accents
14198 in Calc, @TeX{}, and @dfn{eqn} (described in the next section):
14202 @let@calcindexershow=@calcindexernoshow @c Suppress marginal notes
14203 @let@calcindexersh=@calcindexernoshow
14242 dotdot \ddot dotdot
14248 under \underline under
14252 The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
14253 @samp{@{@var{a} \to @var{b}@}}. @TeX{} defines @code{\to} as an
14254 alias for @code{\rightarrow}. However, if the @samp{=>} is the
14255 top-level expression being formatted, a slightly different notation
14256 is used: @samp{\evalto @var{a} \to @var{b}}. The @code{\evalto}
14257 word is ignored by Calc's input routines, and is undefined in @TeX{}.
14258 You will typically want to include one of the following definitions
14259 at the top of a @TeX{} file that uses @code{\evalto}:
14263 \def\evalto#1\to@{@}
14266 The first definition formats evaluates-to operators in the usual
14267 way. The second causes only the @var{b} part to appear in the
14268 printed document; the @var{a} part and the arrow are hidden.
14269 Another definition you may wish to use is @samp{\let\to=\Rightarrow}
14270 which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
14271 @xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
14273 The complete set of @TeX{} control sequences that are ignored during
14277 \hbox \mbox \text \left \right
14278 \, \> \: \; \! \quad \qquad \hfil \hfill
14279 \displaystyle \textstyle \dsize \tsize
14280 \scriptstyle \scriptscriptstyle \ssize \ssize
14281 \rm \bf \it \sl \roman \bold \italic \slanted
14282 \cal \mit \Cal \Bbb \frak \goth
14286 Note that, because these symbols are ignored, reading a @TeX{} formula
14287 into Calc and writing it back out may lose spacing and font information.
14289 Also, the ``discretionary multiplication sign'' @samp{\*} is read
14290 the same as @samp{*}.
14293 The @TeX{} version of this manual includes some printed examples at the
14294 end of this section.
14297 Here are some examples of how various Calc formulas are formatted in @TeX{}:
14302 \sin\left( {a^2 \over b_i} \right)
14306 $$ \sin\left( a^2 \over b_i \right) $$
14313 [(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
14314 [3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
14318 $$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
14325 [abs(a), abs(a / b), floor(a), ceil(a / b)]
14326 [|a|, \left| a \over b \right|,
14327 \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
14330 $$ [|a|, \left| a \over b \right|,
14331 \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
14338 [sin(a), sin(2 a), sin(2 + a), sin(a / b)]
14339 [\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
14340 \sin\left( @{a \over b@} \right)]
14343 \turnoffactive\let\rm\goodrm
14344 $$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
14350 First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
14351 @kbd{C-u - d T} (using the example definition
14352 @samp{\def\foo#1@{\tilde F(#1)@}}:
14356 [f(a), foo(bar), sin(pi)]
14357 [f(a), foo(bar), \sin{\pi}]
14358 [f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
14359 [f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
14363 $$ [f(a), foo(bar), \sin{\pi}] $$
14364 $$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
14365 $$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
14371 First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
14376 \evalto 2 + 3 \to 5
14387 First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
14391 [2 + 3 => 5, a / 2 => (b + c) / 2]
14392 [@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
14396 $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
14397 {\let\to\Rightarrow
14398 $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
14404 Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
14408 [ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
14409 \matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14410 \pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14414 $$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14415 $$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14421 @node Eqn Language Mode, Mathematica Language Mode, TeX Language Mode, Language Modes
14422 @subsection Eqn Language Mode
14426 @pindex calc-eqn-language
14427 @dfn{Eqn} is another popular formatter for math formulas. It is
14428 designed for use with the TROFF text formatter, and comes standard
14429 with many versions of Unix. The @kbd{d E} (@code{calc-eqn-language})
14430 command selects @dfn{eqn} notation.
14432 The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
14433 a significant part in the parsing of the language. For example,
14434 @samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
14435 @code{sqrt} operator. @dfn{Eqn} also understands more conventional
14436 grouping using curly braces: @samp{sqrt@{x+1@} + y}. Braces are
14437 required only when the argument contains spaces.
14439 In Calc's @dfn{eqn} mode, however, curly braces are required to
14440 delimit arguments of operators like @code{sqrt}. The first of the
14441 above examples would treat only the @samp{x} as the argument of
14442 @code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
14443 @samp{sin * x + 1}, because @code{sin} is not a special operator
14444 in the @dfn{eqn} language. If you always surround the argument
14445 with curly braces, Calc will never misunderstand.
14447 Calc also understands parentheses as grouping characters. Another
14448 peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
14449 words with spaces from any surrounding characters that aren't curly
14450 braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
14451 (The spaces around @code{sin} are important to make @dfn{eqn}
14452 recognize that @code{sin} should be typeset in a roman font, and
14453 the spaces around @code{x} and @code{y} are a good idea just in
14454 case the @dfn{eqn} document has defined special meanings for these
14457 Powers and subscripts are written with the @code{sub} and @code{sup}
14458 operators, respectively. Note that the caret symbol @samp{^} is
14459 treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
14460 symbol (these are used to introduce spaces of various widths into
14461 the typeset output of @dfn{eqn}).
14463 As in @TeX{} mode, Calc's formatter omits parentheses around the
14464 arguments of functions like @code{ln} and @code{sin} if they are
14465 ``simple-looking''; in this case Calc surrounds the argument with
14466 braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
14468 Font change codes (like @samp{roman @var{x}}) and positioning codes
14469 (like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
14470 @dfn{eqn} reader. Also ignored are the words @code{left}, @code{right},
14471 @code{mark}, and @code{lineup}. Quotation marks in @dfn{eqn} mode input
14472 are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
14473 @samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
14474 of quotes in @dfn{eqn}, but it is good enough for most uses.
14476 Accent codes (@samp{@var{x} dot}) are handled by treating them as
14477 function calls (@samp{dot(@var{x})}) internally. @xref{TeX Language
14478 Mode}, for a table of these accent functions. The @code{prime} accent
14479 is treated specially if it occurs on a variable or function name:
14480 @samp{f prime prime @w{( x prime )}} is stored internally as
14481 @samp{f'@w{'}(x')}. For example, taking the derivative of @samp{f(2 x)}
14482 with @kbd{a d x} will produce @samp{2 f'(2 x)}, which @dfn{eqn} mode
14483 will display as @samp{2 f prime ( 2 x )}.
14485 Assignments are written with the @samp{<-} (left-arrow) symbol,
14486 and @code{evalto} operators are written with @samp{->} or
14487 @samp{evalto ... ->} (@pxref{TeX Language Mode}, for a discussion
14488 of this). The regular Calc symbols @samp{:=} and @samp{=>} are also
14489 recognized for these operators during reading.
14491 Vectors in @dfn{eqn} mode use regular Calc square brackets, but
14492 matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
14493 The words @code{lcol} and @code{rcol} are recognized as synonyms
14494 for @code{ccol} during input, and are generated instead of @code{ccol}
14495 if the matrix justification mode so specifies.
14497 @node Mathematica Language Mode, Maple Language Mode, Eqn Language Mode, Language Modes
14498 @subsection Mathematica Language Mode
14502 @pindex calc-mathematica-language
14503 @cindex Mathematica language
14504 The @kbd{d M} (@code{calc-mathematica-language}) command selects the
14505 conventions of Mathematica, a powerful and popular mathematical tool
14506 from Wolfram Research, Inc. Notable differences in Mathematica mode
14507 are that the names of built-in functions are capitalized, and function
14508 calls use square brackets instead of parentheses. Thus the Calc
14509 formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
14512 Vectors and matrices use curly braces in Mathematica. Complex numbers
14513 are written @samp{3 + 4 I}. The standard special constants in Calc are
14514 written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
14515 @code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
14517 Non-decimal numbers are written, e.g., @samp{16^^7fff}. Floating-point
14518 numbers in scientific notation are written @samp{1.23*10.^3}.
14519 Subscripts use double square brackets: @samp{a[[i]]}.@refill
14521 @node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
14522 @subsection Maple Language Mode
14526 @pindex calc-maple-language
14527 @cindex Maple language
14528 The @kbd{d W} (@code{calc-maple-language}) command selects the
14529 conventions of Maple, another mathematical tool from the University
14532 Maple's language is much like C. Underscores are allowed in symbol
14533 names; square brackets are used for subscripts; explicit @samp{*}s for
14534 multiplications are required. Use either @samp{^} or @samp{**} to
14537 Maple uses square brackets for lists and curly braces for sets. Calc
14538 interprets both notations as vectors, and displays vectors with square
14539 brackets. This means Maple sets will be converted to lists when they
14540 pass through Calc. As a special case, matrices are written as calls
14541 to the function @code{matrix}, given a list of lists as the argument,
14542 and can be read in this form or with all-capitals @code{MATRIX}.
14544 The Maple interval notation @samp{2 .. 3} has no surrounding brackets;
14545 Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]}, and
14546 writes any kind of interval as @samp{2 .. 3}. This means you cannot
14547 see the difference between an open and a closed interval while in
14548 Maple display mode.
14550 Maple writes complex numbers as @samp{3 + 4*I}. Its special constants
14551 are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
14552 @code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
14553 Floating-point numbers are written @samp{1.23*10.^3}.
14555 Among things not currently handled by Calc's Maple mode are the
14556 various quote symbols, procedures and functional operators, and
14557 inert (@samp{&}) operators.
14559 @node Compositions, Syntax Tables, Maple Language Mode, Language Modes
14560 @subsection Compositions
14563 @cindex Compositions
14564 There are several @dfn{composition functions} which allow you to get
14565 displays in a variety of formats similar to those in Big language
14566 mode. Most of these functions do not evaluate to anything; they are
14567 placeholders which are left in symbolic form by Calc's evaluator but
14568 are recognized by Calc's display formatting routines.
14570 Two of these, @code{string} and @code{bstring}, are described elsewhere.
14571 @xref{Strings}. For example, @samp{string("ABC")} is displayed as
14572 @samp{ABC}. When viewed on the stack it will be indistinguishable from
14573 the variable @code{ABC}, but internally it will be stored as
14574 @samp{string([65, 66, 67])} and can still be manipulated this way; for
14575 example, the selection and vector commands @kbd{j 1 v v j u} would
14576 select the vector portion of this object and reverse the elements, then
14577 deselect to reveal a string whose characters had been reversed.
14579 The composition functions do the same thing in all language modes
14580 (although their components will of course be formatted in the current
14581 language mode). The one exception is Unformatted mode (@kbd{d U}),
14582 which does not give the composition functions any special treatment.
14583 The functions are discussed here because of their relationship to
14584 the language modes.
14587 * Composition Basics::
14588 * Horizontal Compositions::
14589 * Vertical Compositions::
14590 * Other Compositions::
14591 * Information about Compositions::
14592 * User-Defined Compositions::
14595 @node Composition Basics, Horizontal Compositions, Compositions, Compositions
14596 @subsubsection Composition Basics
14599 Compositions are generally formed by stacking formulas together
14600 horizontally or vertically in various ways. Those formulas are
14601 themselves compositions. @TeX{} users will find this analogous
14602 to @TeX{}'s ``boxes.'' Each multi-line composition has a
14603 @dfn{baseline}; horizontal compositions use the baselines to
14604 decide how formulas should be positioned relative to one another.
14605 For example, in the Big mode formula
14617 the second term of the sum is four lines tall and has line three as
14618 its baseline. Thus when the term is combined with 17, line three
14619 is placed on the same level as the baseline of 17.
14625 Another important composition concept is @dfn{precedence}. This is
14626 an integer that represents the binding strength of various operators.
14627 For example, @samp{*} has higher precedence (195) than @samp{+} (180),
14628 which means that @samp{(a * b) + c} will be formatted without the
14629 parentheses, but @samp{a * (b + c)} will keep the parentheses.
14631 The operator table used by normal and Big language modes has the
14632 following precedences:
14635 _ 1200 @r{(subscripts)}
14636 % 1100 @r{(as in n}%@r{)}
14637 - 1000 @r{(as in }-@r{n)}
14638 ! 1000 @r{(as in }!@r{n)}
14641 !! 210 @r{(as in n}!!@r{)}
14642 ! 210 @r{(as in n}!@r{)}
14644 * 195 @r{(or implicit multiplication)}
14646 + - 180 @r{(as in a}+@r{b)}
14648 < = 160 @r{(and other relations)}
14660 The general rule is that if an operator with precedence @cite{n}
14661 occurs as an argument to an operator with precedence @cite{m}, then
14662 the argument is enclosed in parentheses if @cite{n < m}. Top-level
14663 expressions and expressions which are function arguments, vector
14664 components, etc., are formatted with precedence zero (so that they
14665 normally never get additional parentheses).
14667 For binary left-associative operators like @samp{+}, the righthand
14668 argument is actually formatted with one-higher precedence than shown
14669 in the table. This makes sure @samp{(a + b) + c} omits the parentheses,
14670 but the unnatural form @samp{a + (b + c)} keeps its parentheses.
14671 Right-associative operators like @samp{^} format the lefthand argument
14672 with one-higher precedence.
14676 The @code{cprec} function formats an expression with an arbitrary
14677 precedence. For example, @samp{cprec(abc, 185)} will combine into
14678 sums and products as follows: @samp{7 + abc}, @samp{7 (abc)} (because
14679 this @code{cprec} form has higher precedence than addition, but lower
14680 precedence than multiplication).
14686 A final composition issue is @dfn{line breaking}. Calc uses two
14687 different strategies for ``flat'' and ``non-flat'' compositions.
14688 A non-flat composition is anything that appears on multiple lines
14689 (not counting line breaking). Examples would be matrices and Big
14690 mode powers and quotients. Non-flat compositions are displayed
14691 exactly as specified. If they come out wider than the current
14692 window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
14695 Flat compositions, on the other hand, will be broken across several
14696 lines if they are too wide to fit the window. Certain points in a
14697 composition are noted internally as @dfn{break points}. Calc's
14698 general strategy is to fill each line as much as possible, then to
14699 move down to the next line starting at the first break point that
14700 didn't fit. However, the line breaker understands the hierarchical
14701 structure of formulas. It will not break an ``inner'' formula if
14702 it can use an earlier break point from an ``outer'' formula instead.
14703 For example, a vector of sums might be formatted as:
14707 [ a + b + c, d + e + f,
14708 g + h + i, j + k + l, m ]
14713 If the @samp{m} can fit, then so, it seems, could the @samp{g}.
14714 But Calc prefers to break at the comma since the comma is part
14715 of a ``more outer'' formula. Calc would break at a plus sign
14716 only if it had to, say, if the very first sum in the vector had
14717 itself been too large to fit.
14719 Of the composition functions described below, only @code{choriz}
14720 generates break points. The @code{bstring} function (@pxref{Strings})
14721 also generates breakable items: A break point is added after every
14722 space (or group of spaces) except for spaces at the very beginning or
14725 Composition functions themselves count as levels in the formula
14726 hierarchy, so a @code{choriz} that is a component of a larger
14727 @code{choriz} will be less likely to be broken. As a special case,
14728 if a @code{bstring} occurs as a component of a @code{choriz} or
14729 @code{choriz}-like object (such as a vector or a list of arguments
14730 in a function call), then the break points in that @code{bstring}
14731 will be on the same level as the break points of the surrounding
14734 @node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
14735 @subsubsection Horizontal Compositions
14740 The @code{choriz} function takes a vector of objects and composes
14741 them horizontally. For example, @samp{choriz([17, a b/c, d])} formats
14742 as @w{@samp{17a b / cd}} in normal language mode, or as
14753 in Big language mode. This is actually one case of the general
14754 function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
14755 either or both of @var{sep} and @var{prec} may be omitted.
14756 @var{Prec} gives the @dfn{precedence} to use when formatting
14757 each of the components of @var{vec}. The default precedence is
14758 the precedence from the surrounding environment.
14760 @var{Sep} is a string (i.e., a vector of character codes as might
14761 be entered with @code{" "} notation) which should separate components
14762 of the composition. Also, if @var{sep} is given, the line breaker
14763 will allow lines to be broken after each occurrence of @var{sep}.
14764 If @var{sep} is omitted, the composition will not be breakable
14765 (unless any of its component compositions are breakable).
14767 For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
14768 formatted as @samp{2 a + b c + (d = e)}. To get the @code{choriz}
14769 to have precedence 180 ``outwards'' as well as ``inwards,''
14770 enclose it in a @code{cprec} form: @samp{2 cprec(choriz(...), 180)}
14771 formats as @samp{2 (a + b c + (d = e))}.
14773 The baseline of a horizontal composition is the same as the
14774 baselines of the component compositions, which are all aligned.
14776 @node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
14777 @subsubsection Vertical Compositions
14782 The @code{cvert} function makes a vertical composition. Each
14783 component of the vector is centered in a column. The baseline of
14784 the result is by default the top line of the resulting composition.
14785 For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
14786 formats in Big mode as
14799 There are several special composition functions that work only as
14800 components of a vertical composition. The @code{cbase} function
14801 controls the baseline of the vertical composition; the baseline
14802 will be the same as the baseline of whatever component is enclosed
14803 in @code{cbase}. Thus @samp{f(cvert([a, cbase(bb), ccc]),
14804 cvert([a^2 + 1, cbase(b^2)]))} displays as
14820 There are also @code{ctbase} and @code{cbbase} functions which
14821 make the baseline of the vertical composition equal to the top
14822 or bottom line (rather than the baseline) of that component.
14823 Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
14824 cvert([cbbase(a / b)])} gives
14836 There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
14837 function in a given vertical composition. These functions can also
14838 be written with no arguments: @samp{ctbase()} is a zero-height object
14839 which means the baseline is the top line of the following item, and
14840 @samp{cbbase()} means the baseline is the bottom line of the preceding
14845 The @code{crule} function builds a ``rule,'' or horizontal line,
14846 across a vertical composition. By itself @samp{crule()} uses @samp{-}
14847 characters to build the rule. You can specify any other character,
14848 e.g., @samp{crule("=")}. The argument must be a character code or
14849 vector of exactly one character code. It is repeated to match the
14850 width of the widest item in the stack. For example, a quotient
14851 with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
14866 Finally, the functions @code{clvert} and @code{crvert} act exactly
14867 like @code{cvert} except that the items are left- or right-justified
14868 in the stack. Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
14879 Like @code{choriz}, the vertical compositions accept a second argument
14880 which gives the precedence to use when formatting the components.
14881 Vertical compositions do not support separator strings.
14883 @node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
14884 @subsubsection Other Compositions
14889 The @code{csup} function builds a superscripted expression. For
14890 example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
14891 language mode. This is essentially a horizontal composition of
14892 @samp{a} and @samp{b}, where @samp{b} is shifted up so that its
14893 bottom line is one above the baseline.
14897 Likewise, the @code{csub} function builds a subscripted expression.
14898 This shifts @samp{b} down so that its top line is one below the
14899 bottom line of @samp{a} (note that this is not quite analogous to
14900 @code{csup}). Other arrangements can be obtained by using
14901 @code{choriz} and @code{cvert} directly.
14905 The @code{cflat} function formats its argument in ``flat'' mode,
14906 as obtained by @samp{d O}, if the current language mode is normal
14907 or Big. It has no effect in other language modes. For example,
14908 @samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
14909 to improve its readability.
14913 The @code{cspace} function creates horizontal space. For example,
14914 @samp{cspace(4)} is effectively the same as @samp{string(" ")}.
14915 A second string (i.e., vector of characters) argument is repeated
14916 instead of the space character. For example, @samp{cspace(4, "ab")}
14917 looks like @samp{abababab}. If the second argument is not a string,
14918 it is formatted in the normal way and then several copies of that
14919 are composed together: @samp{cspace(4, a^2)} yields