\input texinfo @c -*-texinfo-*- @comment %**start of header (This is for running Texinfo on a region.) @c smallbook @setfilename ../info/calc @c [title] @settitle GNU Emacs Calc 2.1 Manual @setchapternewpage odd @comment %**end of header (This is for running Texinfo on a region.) @c The following macros are used for conditional output for single lines. @c @texline foo @c `foo' will appear only in TeX output @c @infoline foo @c `foo' will appear only in non-TeX output @c @expr{expr} will typeset an expression; @c $x$ in TeX, @samp{x} otherwise. @iftex @macro texline @end macro @alias infoline=comment @alias expr=math @alias tfn=code @alias mathit=expr @macro cpi{} @math{@pi{}} @end macro @macro cpiover{den} @math{@pi/\den\} @end macro @end iftex @ifnottex @alias texline=comment @macro infoline{stuff} \stuff\ @end macro @alias expr=samp @alias tfn=t @alias mathit=i @macro cpi{} @expr{pi} @end macro @macro cpiover{den} @expr{pi/\den\} @end macro @end ifnottex @tex % Suggested by Karl Berry \gdef\!{\mskip-\thinmuskip} @end tex @c Fix some other things specifically for this manual. @iftex @finalout @mathcode`@:=`@: @c Make Calc fractions come out right in math mode @tex \gdef\coloneq{\mathrel{\mathord:\mathord=}} \gdef\beforedisplay{\vskip-10pt} \gdef\afterdisplay{\vskip-5pt} \gdef\beforedisplayh{\vskip-25pt} \gdef\afterdisplayh{\vskip-10pt} @end tex @newdimen@kyvpos @kyvpos=0pt @newdimen@kyhpos @kyhpos=0pt @newcount@calcclubpenalty @calcclubpenalty=1000 @ignore @newcount@calcpageno @newtoks@calcoldeverypar @calcoldeverypar=@everypar @everypar={@calceverypar@the@calcoldeverypar} @ifx@turnoffactive@undefinedzzz@def@turnoffactive{}@fi @ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi @catcode`@\=0 \catcode`\@=11 \r@ggedbottomtrue \catcode`\@=0 @catcode`@\=@active @end ignore @end iftex @copying This file documents Calc, the GNU Emacs calculator. Copyright @copyright{} 1990, 1991, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. @quotation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with the Invariant Sections being just ``GNU GENERAL PUBLIC LICENSE'', with the Front-Cover texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled ``GNU Free Documentation License.'' (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.'' @end quotation @end copying @dircategory Emacs @direntry * Calc: (calc). Advanced desk calculator and mathematical tool. @end direntry @titlepage @sp 6 @center @titlefont{Calc Manual} @sp 4 @center GNU Emacs Calc Version 2.1 @c [volume] @sp 5 @center Dave Gillespie @center daveg@@synaptics.com @page @vskip 0pt plus 1filll Copyright @copyright{} 1990, 1991, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. @insertcopying @end titlepage @c [begin] @ifinfo @node Top, Getting Started, (dir), (dir) @chapter The GNU Emacs Calculator @noindent @dfn{Calc} is an advanced desk calculator and mathematical tool that runs as part of the GNU Emacs environment. This manual is divided into three major parts: ``Getting Started,'' the ``Calc Tutorial,'' and the ``Calc Reference.'' The Tutorial introduces all the major aspects of Calculator use in an easy, hands-on way. The remainder of the manual is a complete reference to the features of the Calculator. For help in the Emacs Info system (which you are using to read this file), type @kbd{?}. (You can also type @kbd{h} to run through a longer Info tutorial.) @end ifinfo @menu * Getting Started:: General description and overview. * Interactive Tutorial:: * Tutorial:: A step-by-step introduction for beginners. * Introduction:: Introduction to the Calc reference manual. * Data Types:: Types of objects manipulated by Calc. * Stack and Trail:: Manipulating the stack and trail buffers. * Mode Settings:: Adjusting display format and other modes. * Arithmetic:: Basic arithmetic functions. * Scientific Functions:: Transcendentals and other scientific functions. * Matrix Functions:: Operations on vectors and matrices. * Algebra:: Manipulating expressions algebraically. * Units:: Operations on numbers with units. * Store and Recall:: Storing and recalling variables. * Graphics:: Commands for making graphs of data. * Kill and Yank:: Moving data into and out of Calc. * Keypad Mode:: Operating Calc from a keypad. * Embedded Mode:: Working with formulas embedded in a file. * Programming:: Calc as a programmable calculator. * Copying:: How you can copy and share Calc. * GNU Free Documentation License:: The license for this documentation. * Customizing Calc:: Customizing Calc. * Reporting Bugs:: How to report bugs and make suggestions. * Summary:: Summary of Calc commands and functions. * Key Index:: The standard Calc key sequences. * Command Index:: The interactive Calc commands. * Function Index:: Functions (in algebraic formulas). * Concept Index:: General concepts. * Variable Index:: Variables used by Calc (both user and internal). * Lisp Function Index:: Internal Lisp math functions. @end menu @node Getting Started, Interactive Tutorial, Top, Top @chapter Getting Started @noindent This chapter provides a general overview of Calc, the GNU Emacs Calculator: What it is, how to start it and how to exit from it, and what are the various ways that it can be used. @menu * What is Calc:: * About This Manual:: * Notations Used in This Manual:: * Demonstration of Calc:: * Using Calc:: * History and Acknowledgements:: @end menu @node What is Calc, About This Manual, Getting Started, Getting Started @section What is Calc? @noindent @dfn{Calc} is an advanced calculator and mathematical tool that runs as part of the GNU Emacs environment. Very roughly based on the HP-28/48 series of calculators, its many features include: @itemize @bullet @item Choice of algebraic or RPN (stack-based) entry of calculations. @item Arbitrary precision integers and floating-point numbers. @item Arithmetic on rational numbers, complex numbers (rectangular and polar), error forms with standard deviations, open and closed intervals, vectors and matrices, dates and times, infinities, sets, quantities with units, and algebraic formulas. @item Mathematical operations such as logarithms and trigonometric functions. @item Programmer's features (bitwise operations, non-decimal numbers). @item Financial functions such as future value and internal rate of return. @item Number theoretical features such as prime factorization and arithmetic modulo @var{m} for any @var{m}. @item Algebraic manipulation features, including symbolic calculus. @item Moving data to and from regular editing buffers. @item Embedded mode for manipulating Calc formulas and data directly inside any editing buffer. @item Graphics using GNUPLOT, a versatile (and free) plotting program. @item Easy programming using keyboard macros, algebraic formulas, algebraic rewrite rules, or extended Emacs Lisp. @end itemize Calc tries to include a little something for everyone; as a result it is large and might be intimidating to the first-time user. If you plan to use Calc only as a traditional desk calculator, all you really need to read is the ``Getting Started'' chapter of this manual and possibly the first few sections of the tutorial. As you become more comfortable with the program you can learn its additional features. Calc does not have the scope and depth of a fully-functional symbolic math package, but Calc has the advantages of convenience, portability, and freedom. @node About This Manual, Notations Used in This Manual, What is Calc, Getting Started @section About This Manual @noindent This document serves as a complete description of the GNU Emacs Calculator. It works both as an introduction for novices, and as a reference for experienced users. While it helps to have some experience with GNU Emacs in order to get the most out of Calc, this manual ought to be readable even if you don't know or use Emacs regularly. @ifinfo The manual is divided into three major parts:@: the ``Getting Started'' chapter you are reading now, the Calc tutorial (chapter 2), and the Calc reference manual (the remaining chapters and appendices). @end ifinfo @iftex The manual is divided into three major parts:@: the ``Getting Started'' chapter you are reading now, the Calc tutorial (chapter 2), and the Calc reference manual (the remaining chapters and appendices). @c [when-split] @c This manual has been printed in two volumes, the @dfn{Tutorial} and the @c @dfn{Reference}. Both volumes include a copy of the ``Getting Started'' @c chapter. @end iftex If you are in a hurry to use Calc, there is a brief ``demonstration'' below which illustrates the major features of Calc in just a couple of pages. If you don't have time to go through the full tutorial, this will show you everything you need to know to begin. @xref{Demonstration of Calc}. The tutorial chapter walks you through the various parts of Calc with lots of hands-on examples and explanations. If you are new to Calc and you have some time, try going through at least the beginning of the tutorial. The tutorial includes about 70 exercises with answers. These exercises give you some guided practice with Calc, as well as pointing out some interesting and unusual ways to use its features. The reference section discusses Calc in complete depth. You can read the reference from start to finish if you want to learn every aspect of Calc. Or, you can look in the table of contents or the Concept Index to find the parts of the manual that discuss the things you need to know. @cindex Marginal notes Every Calc keyboard command is listed in the Calc Summary, and also in the Key Index. Algebraic functions, @kbd{M-x} commands, and variables also have their own indices. @texline Each @infoline In the printed manual, each paragraph that is referenced in the Key or Function Index is marked in the margin with its index entry. @c [fix-ref Help Commands] You can access this manual on-line at any time within Calc by pressing the @kbd{h i} key sequence. Outside of the Calc window, you can press @kbd{C-x * i} to read the manual on-line. Also, you can jump directly to the Tutorial by pressing @kbd{h t} or @kbd{C-x * t}, or to the Summary by pressing @kbd{h s} or @kbd{C-x * s}. Within Calc, you can also go to the part of the manual describing any Calc key, function, or variable using @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v}, respectively. @xref{Help Commands}. The Calc manual can be printed, but because the manual is so large, you should only make a printed copy if you really need it. To print the manual, you will need the @TeX{} typesetting program (this is a free program by Donald Knuth at Stanford University) as well as the @file{texindex} program and @file{texinfo.tex} file, both of which can be obtained from the FSF as part of the @code{texinfo} package. To print the Calc manual in one huge tome, you will need the source code to this manual, @file{calc.texi}, available as part of the Emacs source. Once you have this file, type @kbd{texi2dvi calc.texi}. Alternatively, change to the @file{man} subdirectory of the Emacs source distribution, and type @kbd{make calc.dvi}. (Don't worry if you get some ``overfull box'' warnings while @TeX{} runs.) The result will be a device-independent output file called @file{calc.dvi}, which you must print in whatever way is right for your system. On many systems, the command is @example lpr -d calc.dvi @end example @noindent or @example dvips calc.dvi @end example @c Printed copies of this manual are also available from the Free Software @c Foundation. @node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started @section Notations Used in This Manual @noindent This section describes the various notations that are used throughout the Calc manual. In keystroke sequences, uppercase letters mean you must hold down the shift key while typing the letter. Keys pressed with Control held down are shown as @kbd{C-x}. Keys pressed with Meta held down are shown as @kbd{M-x}. Other notations are @key{RET} for the Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key, @key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key. The @key{DEL} key is called Backspace on some keyboards, it is whatever key you would use to correct a simple typing error when regularly using Emacs. (If you don't have the @key{LFD} or @key{TAB} keys on your keyboard, the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively. If you don't have a Meta key, look for Alt or Extend Char. You can also press @key{ESC} or @kbd{C-[} first to get the same effect, so that @kbd{M-x}, @kbd{@key{ESC} x}, and @kbd{C-[ x} are all equivalent.) Sometimes the @key{RET} key is not shown when it is ``obvious'' that you must press @key{RET} to proceed. For example, the @key{RET} is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}. Commands are generally shown like this: @kbd{p} (@code{calc-precision}) or @kbd{C-x * k} (@code{calc-keypad}). This means that the command is normally used by pressing the @kbd{p} key or @kbd{C-x * k} key sequence, but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}. Commands that correspond to functions in algebraic notation are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that the corresponding function in an algebraic-style formula would be @samp{cos(@var{x})}. A few commands don't have key equivalents: @code{calc-sincos} [@code{sincos}]. @node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started @section A Demonstration of Calc @noindent @cindex Demonstration of Calc This section will show some typical small problems being solved with Calc. The focus is more on demonstration than explanation, but everything you see here will be covered more thoroughly in the Tutorial. To begin, start Emacs if necessary (usually the command @code{emacs} does this), and type @kbd{C-x * c} to start the Calculator. (You can also use @kbd{M-x calc} if this doesn't work. @xref{Starting Calc}, for various ways of starting the Calculator.) Be sure to type all the sample input exactly, especially noting the difference between lower-case and upper-case letters. Remember, @key{RET}, @key{TAB}, @key{DEL}, and @key{SPC} are the Return, Tab, Delete, and Space keys. @strong{RPN calculation.} In RPN, you type the input number(s) first, then the command to operate on the numbers. @noindent Type @kbd{2 @key{RET} 3 + Q} to compute @texline @math{\sqrt{2+3} = 2.2360679775}. @infoline the square root of 2+3, which is 2.2360679775. @noindent Type @kbd{P 2 ^} to compute @texline @math{\pi^2 = 9.86960440109}. @infoline the value of `pi' squared, 9.86960440109. @noindent Type @key{TAB} to exchange the order of these two results. @noindent Type @kbd{- I H S} to subtract these results and compute the Inverse Hyperbolic sine of the difference, 2.72996136574. @noindent Type @key{DEL} to erase this result. @strong{Algebraic calculation.} You can also enter calculations using conventional ``algebraic'' notation. To enter an algebraic formula, use the apostrophe key. @noindent Type @kbd{' sqrt(2+3) @key{RET}} to compute @texline @math{\sqrt{2+3}}. @infoline the square root of 2+3. @noindent Type @kbd{' pi^2 @key{RET}} to enter @texline @math{\pi^2}. @infoline `pi' squared. To evaluate this symbolic formula as a number, type @kbd{=}. @noindent Type @kbd{' arcsinh($ - $$) @key{RET}} to subtract the second-most-recent result from the most-recent and compute the Inverse Hyperbolic sine. @strong{Keypad mode.} If you are using the X window system, press @w{@kbd{C-x * k}} to get Keypad mode. (If you don't use X, skip to the next section.) @noindent Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT} ``buttons'' using your left mouse button. @noindent Click on @key{PI}, @key{2}, and @tfn{y^x}. @noindent Click on @key{INV}, then @key{ENTER} to swap the two results. @noindent Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}. @noindent Click on @key{<-} to erase the result, then click @key{OFF} to turn the Keypad Calculator off. @strong{Grabbing data.} Type @kbd{C-x * x} if necessary to exit Calc. Now select the following numbers as an Emacs region: ``Mark'' the front of the list by typing @kbd{C-@key{SPC}} or @kbd{C-@@} there, then move to the other end of the list. (Either get this list from the on-line copy of this manual, accessed by @w{@kbd{C-x * i}}, or just type these numbers into a scratch file.) Now type @kbd{C-x * g} to ``grab'' these numbers into Calc. @example @group 1.23 1.97 1.6 2 1.19 1.08 @end group @end example @noindent The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.'' Type @w{@kbd{V R +}} to compute the sum of these numbers. @noindent Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute the product of the numbers. @noindent You can also grab data as a rectangular matrix. Place the cursor on the upper-leftmost @samp{1} and set the mark, then move to just after the lower-right @samp{8} and press @kbd{C-x * r}. @noindent Type @kbd{v t} to transpose this @texline @math{3\times2} @infoline 3x2 matrix into a @texline @math{2\times3} @infoline 2x3 matrix. Type @w{@kbd{v u}} to unpack the rows into two separate vectors. Now type @w{@kbd{V R + @key{TAB} V R +}} to compute the sums of the two original columns. (There is also a special grab-and-sum-columns command, @kbd{C-x * :}.) @strong{Units conversion.} Units are entered algebraically. Type @w{@kbd{' 43 mi/hr @key{RET}}} to enter the quantity 43 miles-per-hour. Type @w{@kbd{u c km/hr @key{RET}}}. Type @w{@kbd{u c m/s @key{RET}}}. @strong{Date arithmetic.} Type @kbd{t N} to get the current date and time. Type @kbd{90 +} to find the date 90 days from now. Type @kbd{' <25 dec 87> @key{RET}} to enter a date, then @kbd{- 7 /} to see how many weeks have passed since then. @strong{Algebra.} Algebraic entries can also include formulas or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] @key{RET}} to enter a pair of equations involving three variables. (Note the leading apostrophe in this example; also, note that the space between @samp{x y} is required.) Type @w{@kbd{a S x,y @key{RET}}} to solve these equations for the variables @expr{x} and @expr{y}. @noindent Type @kbd{d B} to view the solutions in more readable notation. Type @w{@kbd{d C}} to view them in C language notation, @kbd{d T} to view them in the notation for the @TeX{} typesetting system, and @kbd{d L} to view them in the notation for the La@TeX{} typesetting system. Type @kbd{d N} to return to normal notation. @noindent Type @kbd{7.5}, then @kbd{s l a @key{RET}} to let @expr{a = 7.5} in these formulas. (That's a letter @kbd{l}, not a numeral @kbd{1}.) @iftex @strong{Help functions.} You can read about any command in the on-line manual. Type @kbd{C-x * c} to return to Calc after each of these commands: @kbd{h k t N} to read about the @kbd{t N} command, @kbd{h f sqrt @key{RET}} to read about the @code{sqrt} function, and @kbd{h s} to read the Calc summary. @end iftex @ifinfo @strong{Help functions.} You can read about any command in the on-line manual. Remember to type the letter @kbd{l}, then @kbd{C-x * c}, to return here after each of these commands: @w{@kbd{h k t N}} to read about the @w{@kbd{t N}} command, @kbd{h f sqrt @key{RET}} to read about the @code{sqrt} function, and @kbd{h s} to read the Calc summary. @end ifinfo Press @key{DEL} repeatedly to remove any leftover results from the stack. To exit from Calc, press @kbd{q} or @kbd{C-x * c} again. @node Using Calc, History and Acknowledgements, Demonstration of Calc, Getting Started @section Using Calc @noindent Calc has several user interfaces that are specialized for different kinds of tasks. As well as Calc's standard interface, there are Quick mode, Keypad mode, and Embedded mode. @menu * Starting Calc:: * The Standard Interface:: * Quick Mode Overview:: * Keypad Mode Overview:: * Standalone Operation:: * Embedded Mode Overview:: * Other C-x * Commands:: @end menu @node Starting Calc, The Standard Interface, Using Calc, Using Calc @subsection Starting Calc @noindent On most systems, you can type @kbd{C-x *} to start the Calculator. The key sequence @kbd{C-x *} is bound to the command @code{calc-dispatch}, which can be rebound if convenient (@pxref{Customizing Calc}). When you press @kbd{C-x *}, Emacs waits for you to press a second key to complete the command. In this case, you will follow @kbd{C-x *} with a letter (upper- or lower-case, it doesn't matter for @kbd{C-x *}) that says which Calc interface you want to use. To get Calc's standard interface, type @kbd{C-x * c}. To get Keypad mode, type @kbd{C-x * k}. Type @kbd{C-x * ?} to get a brief list of the available options, and type a second @kbd{?} to get a complete list. To ease typing, @kbd{C-x * *} also works to start Calc. It starts the same interface (either @kbd{C-x * c} or @w{@kbd{C-x * k}}) that you last used, selecting the @kbd{C-x * c} interface by default. If @kbd{C-x *} doesn't work for you, you can always type explicit commands like @kbd{M-x calc} (for the standard user interface) or @w{@kbd{M-x calc-keypad}} (for Keypad mode). First type @kbd{M-x} (that's Meta with the letter @kbd{x}), then, at the prompt, type the full command (like @kbd{calc-keypad}) and press Return. The same commands (like @kbd{C-x * c} or @kbd{C-x * *}) that start the Calculator also turn it off if it is already on. @node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc @subsection The Standard Calc Interface @noindent @cindex Standard user interface Calc's standard interface acts like a traditional RPN calculator, operated by the normal Emacs keyboard. When you type @kbd{C-x * c} to start the Calculator, the Emacs screen splits into two windows with the file you were editing on top and Calc on the bottom. @smallexample @group ... --**-Emacs: myfile (Fundamental)----All---------------------- --- Emacs Calculator Mode --- |Emacs Calculator Trail 2: 17.3 | 17.3 1: -5 | 3 . | 2 | 4 | * 8 | ->-5 | --%%-Calc: 12 Deg (Calculator)----All----- --%%-Emacs: *Calc Trail* @end group @end smallexample In this figure, the mode-line for @file{myfile} has moved up and the ``Calculator'' window has appeared below it. As you can see, Calc actually makes two windows side-by-side. The lefthand one is called the @dfn{stack window} and the righthand one is called the @dfn{trail window.} The stack holds the numbers involved in the calculation you are currently performing. The trail holds a complete record of all calculations you have done. In a desk calculator with a printer, the trail corresponds to the paper tape that records what you do. In this case, the trail shows that four numbers (17.3, 3, 2, and 4) were first entered into the Calculator, then the 2 and 4 were multiplied to get 8, then the 3 and 8 were subtracted to get @mathit{-5}. (The @samp{>} symbol shows that this was the most recent calculation.) The net result is the two numbers 17.3 and @mathit{-5} sitting on the stack. Most Calculator commands deal explicitly with the stack only, but there is a set of commands that allow you to search back through the trail and retrieve any previous result. Calc commands use the digits, letters, and punctuation keys. Shifted (i.e., upper-case) letters are different from lowercase letters. Some letters are @dfn{prefix} keys that begin two-letter commands. For example, @kbd{e} means ``enter exponent'' and shifted @kbd{E} means @expr{e^x}. With the @kbd{d} (``display modes'') prefix the letter ``e'' takes on very different meanings: @kbd{d e} means ``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.'' There is nothing stopping you from switching out of the Calc window and back into your editing window, say by using the Emacs @w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is inside a regular window, Emacs acts just like normal. When the cursor is in the Calc stack or trail windows, keys are interpreted as Calc commands. When you quit by pressing @kbd{C-x * c} a second time, the Calculator windows go away but the actual Stack and Trail are not gone, just hidden. When you press @kbd{C-x * c} once again you will get the same stack and trail contents you had when you last used the Calculator. The Calculator does not remember its state between Emacs sessions. Thus if you quit Emacs and start it again, @kbd{C-x * c} will give you a fresh stack and trail. There is a command (@kbd{m m}) that lets you save your favorite mode settings between sessions, though. One of the things it saves is which user interface (standard or Keypad) you last used; otherwise, a freshly started Emacs will always treat @kbd{C-x * *} the same as @kbd{C-x * c}. The @kbd{q} key is another equivalent way to turn the Calculator off. If you type @kbd{C-x * b} first and then @kbd{C-x * c}, you get a full-screen version of Calc (@code{full-calc}) in which the stack and trail windows are still side-by-side but are now as tall as the whole Emacs screen. When you press @kbd{q} or @kbd{C-x * c} again to quit, the file you were editing before reappears. The @kbd{C-x * b} key switches back and forth between ``big'' full-screen mode and the normal partial-screen mode. Finally, @kbd{C-x * o} (@code{calc-other-window}) is like @kbd{C-x * c} except that the Calc window is not selected. The buffer you were editing before remains selected instead. @kbd{C-x * o} is a handy way to switch out of Calc momentarily to edit your file; type @kbd{C-x * c} to switch back into Calc when you are done. @node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc @subsection Quick Mode (Overview) @noindent @dfn{Quick mode} is a quick way to use Calc when you don't need the full complexity of the stack and trail. To use it, type @kbd{C-x * q} (@code{quick-calc}) in any regular editing buffer. Quick mode is very simple: It prompts you to type any formula in standard algebraic notation (like @samp{4 - 2/3}) and then displays the result at the bottom of the Emacs screen (@mathit{3.33333333333} in this case). You are then back in the same editing buffer you were in before, ready to continue editing or to type @kbd{C-x * q} again to do another quick calculation. The result of the calculation will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command at this point will yank the result into your editing buffer. Calc mode settings affect Quick mode, too, though you will have to go into regular Calc (with @kbd{C-x * c}) to change the mode settings. @c [fix-ref Quick Calculator mode] @xref{Quick Calculator}, for further information. @node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc @subsection Keypad Mode (Overview) @noindent @dfn{Keypad mode} is a mouse-based interface to the Calculator. It is designed for use with terminals that support a mouse. If you don't have a mouse, you will have to operate Keypad mode with your arrow keys (which is probably more trouble than it's worth). Type @kbd{C-x * k} to turn Keypad mode on or off. Once again you get two new windows, this time on the righthand side of the screen instead of at the bottom. The upper window is the familiar Calc Stack; the lower window is a picture of a typical calculator keypad. @tex \dimen0=\pagetotal% \advance \dimen0 by 24\baselineskip% \ifdim \dimen0>\pagegoal \vfill\eject \fi% \medskip @end tex @smallexample @group |--- Emacs Calculator Mode --- |2: 17.3 |1: -5 | . |--%%-Calc: 12 Deg (Calcul |----+-----Calc 2.1------+----1 |FLR |CEIL|RND |TRNC|CLN2|FLT | |----+----+----+----+----+----| | LN |EXP | |ABS |IDIV|MOD | |----+----+----+----+----+----| |SIN |COS |TAN |SQRT|y^x |1/x | |----+----+----+----+----+----| | ENTER |+/- |EEX |UNDO| <- | |-----+---+-+--+--+-+---++----| | INV | 7 | 8 | 9 | / | |-----+-----+-----+-----+-----| | HYP | 4 | 5 | 6 | * | |-----+-----+-----+-----+-----| |EXEC | 1 | 2 | 3 | - | |-----+-----+-----+-----+-----| | OFF | 0 | . | PI | + | |-----+-----+-----+-----+-----+ @end group @end smallexample Keypad mode is much easier for beginners to learn, because there is no need to memorize lots of obscure key sequences. But not all commands in regular Calc are available on the Keypad. You can always switch the cursor into the Calc stack window to use standard Calc commands if you need. Serious Calc users, though, often find they prefer the standard interface over Keypad mode. To operate the Calculator, just click on the ``buttons'' of the keypad using your left mouse button. To enter the two numbers shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to add them together you would then click @kbd{+} (to get 12.3 on the stack). If you click the right mouse button, the top three rows of the keypad change to show other sets of commands, such as advanced math functions, vector operations, and operations on binary numbers. Because Keypad mode doesn't use the regular keyboard, Calc leaves the cursor in your original editing buffer. You can type in this buffer in the usual way while also clicking on the Calculator keypad. One advantage of Keypad mode is that you don't need an explicit command to switch between editing and calculating. If you press @kbd{C-x * b} first, you get a full-screen Keypad mode (@code{full-calc-keypad}) with three windows: The keypad in the lower left, the stack in the lower right, and the trail on top. @c [fix-ref Keypad Mode] @xref{Keypad Mode}, for further information. @node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc @subsection Standalone Operation @noindent @cindex Standalone Operation If you are not in Emacs at the moment but you wish to use Calc, you must start Emacs first. If all you want is to run Calc, you can give the commands: @example emacs -f full-calc @end example @noindent or @example emacs -f full-calc-keypad @end example @noindent which run a full-screen Calculator (as if by @kbd{C-x * b C-x * c}) or a full-screen X-based Calculator (as if by @kbd{C-x * b C-x * k}). In standalone operation, quitting the Calculator (by pressing @kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs itself. @node Embedded Mode Overview, Other C-x * Commands, Standalone Operation, Using Calc @subsection Embedded Mode (Overview) @noindent @dfn{Embedded mode} is a way to use Calc directly from inside an editing buffer. Suppose you have a formula written as part of a document like this: @smallexample @group The derivative of ln(ln(x)) is @end group @end smallexample @noindent and you wish to have Calc compute and format the derivative for you and store this derivative in the buffer automatically. To do this with Embedded mode, first copy the formula down to where you want the result to be: @smallexample @group The derivative of ln(ln(x)) is ln(ln(x)) @end group @end smallexample Now, move the cursor onto this new formula and press @kbd{C-x * e}. Calc will read the formula (using the surrounding blank lines to tell how much text to read), then push this formula (invisibly) onto the Calc stack. The cursor will stay on the formula in the editing buffer, but the buffer's mode line will change to look like the Calc mode line (with mode indicators like @samp{12 Deg} and so on). Even though you are still in your editing buffer, the keyboard now acts like the Calc keyboard, and any new result you get is copied from the stack back into the buffer. To take the derivative, you would type @kbd{a d x @key{RET}}. @smallexample @group The derivative of ln(ln(x)) is 1 / ln(x) x @end group @end smallexample To make this look nicer, you might want to press @kbd{d =} to center the formula, and even @kbd{d B} to use Big display mode. @smallexample @group The derivative of ln(ln(x)) is % [calc-mode: justify: center] % [calc-mode: language: big] 1 ------- ln(x) x @end group @end smallexample Calc has added annotations to the file to help it remember the modes that were used for this formula. They are formatted like comments in the @TeX{} typesetting language, just in case you are using @TeX{} or La@TeX{}. (In this example @TeX{} is not being used, so you might want to move these comments up to the top of the file or otherwise put them out of the way.) As an extra flourish, we can add an equation number using a righthand label: Type @kbd{d @} (1) @key{RET}}. @smallexample @group % [calc-mode: justify: center] % [calc-mode: language: big] % [calc-mode: right-label: " (1)"] 1 ------- (1) ln(x) x @end group @end smallexample To leave Embedded mode, type @kbd{C-x * e} again. The mode line and keyboard will revert to the way they were before. The related command @kbd{C-x * w} operates on a single word, which generally means a single number, inside text. It uses any non-numeric characters rather than blank lines to delimit the formula it reads. Here's an example of its use: @smallexample A slope of one-third corresponds to an angle of 1 degrees. @end smallexample Place the cursor on the @samp{1}, then type @kbd{C-x * w} to enable Embedded mode on that number. Now type @kbd{3 /} (to get one-third), and @kbd{I T} (the Inverse Tangent converts a slope into an angle), then @w{@kbd{C-x * w}} again to exit Embedded mode. @smallexample A slope of one-third corresponds to an angle of 18.4349488229 degrees. @end smallexample @c [fix-ref Embedded Mode] @xref{Embedded Mode}, for full details. @node Other C-x * Commands, , Embedded Mode Overview, Using Calc @subsection Other @kbd{C-x *} Commands @noindent Two more Calc-related commands are @kbd{C-x * g} and @kbd{C-x * r}, which ``grab'' data from a selected region of a buffer into the Calculator. The region is defined in the usual Emacs way, by a ``mark'' placed at one end of the region, and the Emacs cursor or ``point'' placed at the other. The @kbd{C-x * g} command reads the region in the usual left-to-right, top-to-bottom order. The result is packaged into a Calc vector of numbers and placed on the stack. Calc (in its standard user interface) is then started. Type @kbd{v u} if you want to unpack this vector into separate numbers on the stack. Also, @kbd{C-u C-x * g} interprets the region as a single number or formula. The @kbd{C-x * r} command reads a rectangle, with the point and mark defining opposite corners of the rectangle. The result is a matrix of numbers on the Calculator stack. Complementary to these is @kbd{C-x * y}, which ``yanks'' the value at the top of the Calc stack back into an editing buffer. If you type @w{@kbd{C-x * y}} while in such a buffer, the value is yanked at the current position. If you type @kbd{C-x * y} while in the Calc buffer, Calc makes an educated guess as to which editing buffer you want to use. The Calc window does not have to be visible in order to use this command, as long as there is something on the Calc stack. Here, for reference, is the complete list of @kbd{C-x *} commands. The shift, control, and meta keys are ignored for the keystroke following @kbd{C-x *}. @noindent Commands for turning Calc on and off: @table @kbd @item * Turn Calc on or off, employing the same user interface as last time. @item =, +, -, /, \, &, # Alternatives for @kbd{*}. @item C Turn Calc on or off using its standard bottom-of-the-screen interface. If Calc is already turned on but the cursor is not in the Calc window, move the cursor into the window. @item O Same as @kbd{C}, but don't select the new Calc window. If Calc is already turned on and the cursor is in the Calc window, move it out of that window. @item B Control whether @kbd{C-x * c} and @kbd{C-x * k} use the full screen. @item Q Use Quick mode for a single short calculation. @item K Turn Calc Keypad mode on or off. @item E Turn Calc Embedded mode on or off at the current formula. @item J Turn Calc Embedded mode on or off, select the interesting part. @item W Turn Calc Embedded mode on or off at the current word (number). @item Z Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command. @item X Quit Calc; turn off standard, Keypad, or Embedded mode if on. (This is like @kbd{q} or @key{OFF} inside of Calc.) @end table @iftex @sp 2 @end iftex @noindent Commands for moving data into and out of the Calculator: @table @kbd @item G Grab the region into the Calculator as a vector. @item R Grab the rectangular region into the Calculator as a matrix. @item : Grab the rectangular region and compute the sums of its columns. @item _ Grab the rectangular region and compute the sums of its rows. @item Y Yank a value from the Calculator into the current editing buffer. @end table @iftex @sp 2 @end iftex @noindent Commands for use with Embedded mode: @table @kbd @item A ``Activate'' the current buffer. Locate all formulas that contain @samp{:=} or @samp{=>} symbols and record their locations so that they can be updated automatically as variables are changed. @item D Duplicate the current formula immediately below and select the duplicate. @item F Insert a new formula at the current point. @item N Move the cursor to the next active formula in the buffer. @item P Move the cursor to the previous active formula in the buffer. @item U Update (i.e., as if by the @kbd{=} key) the formula at the current point. @item ` Edit (as if by @code{calc-edit}) the formula at the current point. @end table @iftex @sp 2 @end iftex @noindent Miscellaneous commands: @table @kbd @item I Run the Emacs Info system to read the Calc manual. (This is the same as @kbd{h i} inside of Calc.) @item T Run the Emacs Info system to read the Calc Tutorial. @item S Run the Emacs Info system to read the Calc Summary. @item L Load Calc entirely into memory. (Normally the various parts are loaded only as they are needed.) @item M Read a region of written keystroke names (like @kbd{C-n a b c @key{RET}}) and record them as the current keyboard macro. @item 0 (This is the ``zero'' digit key.) Reset the Calculator to its initial state: Empty stack, and initial mode settings. @end table @node History and Acknowledgements, , Using Calc, Getting Started @section History and Acknowledgements @noindent Calc was originally started as a two-week project to occupy a lull in the author's schedule. Basically, a friend asked if I remembered the value of @texline @math{2^{32}}. @infoline @expr{2^32}. I didn't offhand, but I said, ``that's easy, just call up an @code{xcalc}.'' @code{Xcalc} duly reported that the answer to our question was @samp{4.294967e+09}---with no way to see the full ten digits even though we knew they were there in the program's memory! I was so annoyed, I vowed to write a calculator of my own, once and for all. I chose Emacs Lisp, a) because I had always been curious about it and b) because, being only a text editor extension language after all, Emacs Lisp would surely reach its limits long before the project got too far out of hand. To make a long story short, Emacs Lisp turned out to be a distressingly solid implementation of Lisp, and the humble task of calculating turned out to be more open-ended than one might have expected. Emacs Lisp didn't have built-in floating point math (now it does), so this had to be simulated in software. In fact, Emacs integers will only comfortably fit six decimal digits or so---not enough for a decent calculator. So I had to write my own high-precision integer code as well, and once I had this I figured that arbitrary-size integers were just as easy as large integers. Arbitrary floating-point precision was the logical next step. Also, since the large integer arithmetic was there anyway it seemed only fair to give the user direct access to it, which in turn made it practical to support fractions as well as floats. All these features inspired me to look around for other data types that might be worth having. Around this time, my friend Rick Koshi showed me his nifty new HP-28 calculator. It allowed the user to manipulate formulas as well as numerical quantities, and it could also operate on matrices. I decided that these would be good for Calc to have, too. And once things had gone this far, I figured I might as well take a look at serious algebra systems for further ideas. Since these systems did far more than I could ever hope to implement, I decided to focus on rewrite rules and other programming features so that users could implement what they needed for themselves. Rick complained that matrices were hard to read, so I put in code to format them in a 2D style. Once these routines were in place, Big mode was obligatory. Gee, what other language modes would be useful? Scott Hemphill and Allen Knutson, two friends with a strong mathematical bent, contributed ideas and algorithms for a number of Calc features including modulo forms, primality testing, and float-to-fraction conversion. Units were added at the eager insistence of Mass Sivilotti. Later, Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable expert assistance with the units table. As far as I can remember, the idea of using algebraic formulas and variables to represent units dates back to an ancient article in Byte magazine about muMath, an early algebra system for microcomputers. Many people have contributed to Calc by reporting bugs and suggesting features, large and small. A few deserve special mention: Tim Peters, who helped develop the ideas that led to the selection commands, rewrite rules, and many other algebra features; @texline Fran\c{c}ois @infoline Francois Pinard, who contributed an early prototype of the Calc Summary appendix as well as providing valuable suggestions in many other areas of Calc; Carl Witty, whose eagle eyes discovered many typographical and factual errors in the Calc manual; Tim Kay, who drove the development of Embedded mode; Ove Ewerlid, who made many suggestions relating to the algebra commands and contributed some code for polynomial operations; Randal Schwartz, who suggested the @code{calc-eval} function; Robert J. Chassell, who suggested the Calc Tutorial and exercises; and Juha Sarlin, who first worked out how to split Calc into quickly-loading parts. Bob Weiner helped immensely with the Lucid Emacs port. @cindex Bibliography @cindex Knuth, Art of Computer Programming @cindex Numerical Recipes @c Should these be expanded into more complete references? Among the books used in the development of Calc were Knuth's @emph{Art of Computer Programming} (especially volume II, @emph{Seminumerical Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky, and Vetterling; Bevington's @emph{Data Reduction and Error Analysis for the Physical Sciences}; @emph{Concrete Mathematics} by Graham, Knuth, and Patashnik; Steele's @emph{Common Lisp, the Language}; the @emph{CRC Standard Math Tables} (William H. Beyer, ed.); and Abramowitz and Stegun's venerable @emph{Handbook of Mathematical Functions}. Also, of course, Calc could not have been written without the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil Lewis and Dan LaLiberte. Final thanks go to Richard Stallman, without whose fine implementations of the Emacs editor, language, and environment, Calc would have been finished in two weeks. @c [tutorial] @ifinfo @c This node is accessed by the `C-x * t' command. @node Interactive Tutorial, Tutorial, Getting Started, Top @chapter Tutorial @noindent Some brief instructions on using the Emacs Info system for this tutorial: Press the space bar and Delete keys to go forward and backward in a section by screenfuls (or use the regular Emacs scrolling commands for this). Press @kbd{n} or @kbd{p} to go to the Next or Previous section. If the section has a @dfn{menu}, press a digit key like @kbd{1} or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to go back up from a sub-section to the menu it is part of. Exercises in the tutorial all have cross-references to the appropriate page of the ``answers'' section. Press @kbd{f}, then the exercise number, to see the answer to an exercise. After you have followed a cross-reference, you can press the letter @kbd{l} to return to where you were before. You can press @kbd{?} at any time for a brief summary of Info commands. Press @kbd{1} now to enter the first section of the Tutorial. @menu * Tutorial:: @end menu @end ifinfo @node Tutorial, Introduction, Interactive Tutorial, Top @chapter Tutorial @noindent This chapter explains how to use Calc and its many features, in a step-by-step, tutorial way. You are encouraged to run Calc and work along with the examples as you read (@pxref{Starting Calc}). If you are already familiar with advanced calculators, you may wish @c [not-split] to skip on to the rest of this manual. @c [when-split] @c to skip on to volume II of this manual, the @dfn{Calc Reference}. @c [fix-ref Embedded Mode] This tutorial describes the standard user interface of Calc only. The Quick mode and Keypad mode interfaces are fairly self-explanatory. @xref{Embedded Mode}, for a description of the Embedded mode interface. @ifinfo The easiest way to read this tutorial on-line is to have two windows on your Emacs screen, one with Calc and one with the Info system. (If you have a printed copy of the manual you can use that instead.) Press @kbd{C-x * c} to turn Calc on or to switch into the Calc window, and press @kbd{C-x * i} to start the Info system or to switch into its window. Or, you may prefer to use the tutorial in printed form. @end ifinfo @iftex The easiest way to read this tutorial on-line is to have two windows on your Emacs screen, one with Calc and one with the Info system. (If you have a printed copy of the manual you can use that instead.) Press @kbd{C-x * c} to turn Calc on or to switch into the Calc window, and press @kbd{C-x * i} to start the Info system or to switch into its window. @end iftex This tutorial is designed to be done in sequence. But the rest of this manual does not assume you have gone through the tutorial. The tutorial does not cover everything in the Calculator, but it touches on most general areas. @ifinfo You may wish to print out a copy of the Calc Summary and keep notes on it as you learn Calc. @xref{About This Manual}, to see how to make a printed summary. @xref{Summary}. @end ifinfo @iftex The Calc Summary at the end of the reference manual includes some blank space for your own use. You may wish to keep notes there as you learn Calc. @end iftex @menu * Basic Tutorial:: * Arithmetic Tutorial:: * Vector/Matrix Tutorial:: * Types Tutorial:: * Algebra Tutorial:: * Programming Tutorial:: * Answers to Exercises:: @end menu @node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial @section Basic Tutorial @noindent In this section, we learn how RPN and algebraic-style calculations work, how to undo and redo an operation done by mistake, and how to control various modes of the Calculator. @menu * RPN Tutorial:: Basic operations with the stack. * Algebraic Tutorial:: Algebraic entry; variables. * Undo Tutorial:: If you make a mistake: Undo and the trail. * Modes Tutorial:: Common mode-setting commands. @end menu @node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial @subsection RPN Calculations and the Stack @cindex RPN notation @ifinfo @noindent Calc normally uses RPN notation. You may be familiar with the RPN system from Hewlett-Packard calculators, FORTH, or PostScript. (Reverse Polish Notation, RPN, is named after the Polish mathematician Jan Lukasiewicz.) @end ifinfo @tex \noindent Calc normally uses RPN notation. You may be familiar with the RPN system from Hewlett-Packard calculators, FORTH, or PostScript. (Reverse Polish Notation, RPN, is named after the Polish mathematician Jan \L ukasiewicz.) @end tex The central component of an RPN calculator is the @dfn{stack}. A calculator stack is like a stack of dishes. New dishes (numbers) are added at the top of the stack, and numbers are normally only removed from the top of the stack. @cindex Operators @cindex Operands In an operation like @expr{2+3}, the 2 and 3 are called the @dfn{operands} and the @expr{+} is the @dfn{operator}. In an RPN calculator you always enter the operands first, then the operator. Each time you type a number, Calc adds or @dfn{pushes} it onto the top of the Stack. When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate number of operands from the stack and pushes back the result. Thus we could add the numbers 2 and 3 in an RPN calculator by typing: @kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to the @key{ENTER} key on traditional RPN calculators.) Try this now if you wish; type @kbd{C-x * c} to switch into the Calc window (you can type @kbd{C-x * c} again or @kbd{C-x * o} to switch back to the Tutorial window). The first four keystrokes ``push'' the numbers 2 and 3 onto the stack. The @kbd{+} key ``pops'' the top two numbers from the stack, adds them, and pushes the result (5) back onto the stack. Here's how the stack will look at various points throughout the calculation: @smallexample @group . 1: 2 2: 2 1: 5 . . 1: 3 . . C-x * c 2 @key{RET} 3 @key{RET} + @key{DEL} @end group @end smallexample The @samp{.} symbol is a marker that represents the top of the stack. Note that the ``top'' of the stack is really shown at the bottom of the Stack window. This may seem backwards, but it turns out to be less distracting in regular use. @cindex Stack levels @cindex Levels of stack The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level numbers}. Old RPN calculators always had four stack levels called @expr{x}, @expr{y}, @expr{z}, and @expr{t}. Calc's stack can grow as large as you like, so it uses numbers instead of letters. Some stack-manipulation commands accept a numeric argument that says which stack level to work on. Normal commands like @kbd{+} always work on the top few levels of the stack. @c [fix-ref Truncating the Stack] The Stack buffer is just an Emacs buffer, and you can move around in it using the regular Emacs motion commands. But no matter where the cursor is, even if you have scrolled the @samp{.} marker out of view, most Calc commands always move the cursor back down to level 1 before doing anything. It is possible to move the @samp{.} marker upwards through the stack, temporarily ``hiding'' some numbers from commands like @kbd{+}. This is called @dfn{stack truncation} and we will not cover it in this tutorial; @pxref{Truncating the Stack}, if you are interested. You don't really need the second @key{RET} in @kbd{2 @key{RET} 3 @key{RET} +}. That's because if you type any operator name or other non-numeric key when you are entering a number, the Calculator automatically enters that number and then does the requested command. Thus @kbd{2 @key{RET} 3 +} will work just as well. Examples in this tutorial will often omit @key{RET} even when the stack displays shown would only happen if you did press @key{RET}: @smallexample @group 1: 2 2: 2 1: 5 . 1: 3 . . 2 @key{RET} 3 + @end group @end smallexample @noindent Here, after pressing @kbd{3} the stack would really show @samp{1: 2} with @samp{Calc:@: 3} in the minibuffer. In these situations, you can press the optional @key{RET} to see the stack as the figure shows. (@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises at various points. Try them if you wish. Answers to all the exercises are located at the end of the Tutorial chapter. Each exercise will include a cross-reference to its particular answer. If you are reading with the Emacs Info system, press @kbd{f} and the exercise number to go to the answer, then the letter @kbd{l} to return to where you were.) @noindent Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for multiplication.) Figure it out by hand, then try it with Calc to see if you're right. @xref{RPN Answer 1, 1}. (@bullet{}) (@bullet{}) @strong{Exercise 2.} Compute @texline @math{(2\times4) + (7\times9.4) + {5\over4}} @infoline @expr{2*4 + 7*9.5 + 5/4} using the stack. @xref{RPN Answer 2, 2}. (@bullet{}) The @key{DEL} key is called Backspace on some keyboards. It is whatever key you would use to correct a simple typing error when regularly using Emacs. The @key{DEL} key pops and throws away the top value on the stack. (You can still get that value back from the Trail if you should need it later on.) There are many places in this tutorial where we assume you have used @key{DEL} to erase the results of the previous example at the beginning of a new example. In the few places where it is really important to use @key{DEL} to clear away old results, the text will remind you to do so. (It won't hurt to let things accumulate on the stack, except that whenever you give a display-mode-changing command Calc will have to spend a long time reformatting such a large stack.) Since the @kbd{-} key is also an operator (it subtracts the top two stack elements), how does one enter a negative number? Calc uses the @kbd{_} (underscore) key to act like the minus sign in a number. So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine. You can also press @kbd{n}, which means ``change sign.'' It changes the number at the top of the stack (or the number being entered) from positive to negative or vice-versa: @kbd{5 n @key{RET}}. @cindex Duplicating a stack entry If you press @key{RET} when you're not entering a number, the effect is to duplicate the top number on the stack. Consider this calculation: @smallexample @group 1: 3 2: 3 1: 9 2: 9 1: 81 . 1: 3 . 1: 9 . . . 3 @key{RET} @key{RET} * @key{RET} * @end group @end smallexample @noindent (Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^}, to raise 3 to the fourth power.) The space-bar key (denoted @key{SPC} here) performs the same function as @key{RET}; you could replace all three occurrences of @key{RET} in the above example with @key{SPC} and the effect would be the same. @cindex Exchanging stack entries Another stack manipulation key is @key{TAB}. This exchanges the top two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +} to get 5, and then you realize what you really wanted to compute was @expr{20 / (2+3)}. @smallexample @group 1: 5 2: 5 2: 20 1: 4 . 1: 20 1: 5 . . . 2 @key{RET} 3 + 20 @key{TAB} / @end group @end smallexample @noindent Planning ahead, the calculation would have gone like this: @smallexample @group 1: 20 2: 20 3: 20 2: 20 1: 4 . 1: 2 2: 2 1: 5 . . 1: 3 . . 20 @key{RET} 2 @key{RET} 3 + / @end group @end smallexample A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type @key{TAB}). It rotates the top three elements of the stack upward, bringing the object in level 3 to the top. @smallexample @group 1: 10 2: 10 3: 10 3: 20 3: 30 . 1: 20 2: 20 2: 30 2: 10 . 1: 30 1: 10 1: 20 . . . 10 @key{RET} 20 @key{RET} 30 @key{RET} M-@key{TAB} M-@key{TAB} @end group @end smallexample (@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are on the stack. Figure out how to add one to the number in level 2 without affecting the rest of the stack. Also figure out how to add one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{}) Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two arguments from the stack and push a result. Operations like @kbd{n} and @kbd{Q} (square root) pop a single number and push the result. You can think of them as simply operating on the top element of the stack. @smallexample @group 1: 3 1: 9 2: 9 1: 25 1: 5 . . 1: 16 . . . 3 @key{RET} @key{RET} * 4 @key{RET} @key{RET} * + Q @end group @end smallexample @noindent (Note that capital @kbd{Q} means to hold down the Shift key while typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.) @cindex Pythagorean Theorem Here we've used the Pythagorean Theorem to determine the hypotenuse of a right triangle. Calc actually has a built-in command for that called @kbd{f h}, but let's suppose we can't remember the necessary keystrokes. We can still enter it by its full name using @kbd{M-x} notation: @smallexample @group 1: 3 2: 3 1: 5 . 1: 4 . . 3 @key{RET} 4 @key{RET} M-x calc-hypot @end group @end smallexample All Calculator commands begin with the word @samp{calc-}. Since it gets tiring to type this, Calc provides an @kbd{x} key which is just like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-} prefix for you: @smallexample @group 1: 3 2: 3 1: 5 . 1: 4 . . 3 @key{RET} 4 @key{RET} x hypot @end group @end smallexample What happens if you take the square root of a negative number? @smallexample @group 1: 4 1: -4 1: (0, 2) . . . 4 @key{RET} n Q @end group @end smallexample @noindent The notation @expr{(a, b)} represents a complex number. Complex numbers are more traditionally written @expr{a + b i}; Calc can display in this format, too, but for now we'll stick to the @expr{(a, b)} notation. If you don't know how complex numbers work, you can safely ignore this feature. Complex numbers only arise from operations that would be errors in a calculator that didn't have complex numbers. (For example, taking the square root or logarithm of a negative number produces a complex result.) Complex numbers are entered in the notation shown. The @kbd{(} and @kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.'' @smallexample @group 1: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3) . 1: 2 . 3 . . . ( 2 , 3 ) @end group @end smallexample You can perform calculations while entering parts of incomplete objects. However, an incomplete object cannot actually participate in a calculation: @smallexample @group 1: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ... . 1: 2 2: 2 5 5 . 1: 3 . . . (error) ( 2 @key{RET} 3 + + @end group @end smallexample @noindent Adding 5 to an incomplete object makes no sense, so the last command produces an error message and leaves the stack the same. Incomplete objects can't participate in arithmetic, but they can be moved around by the regular stack commands. @smallexample @group 2: 2 3: 2 3: 3 1: ( ... 1: (2, 3) 1: 3 2: 3 2: ( ... 2 . . 1: ( ... 1: 2 3 . . . 2 @key{RET} 3 @key{RET} ( M-@key{TAB} M-@key{TAB} ) @end group @end smallexample @noindent Note that the @kbd{,} (comma) key did not have to be used here. When you press @kbd{)} all the stack entries between the incomplete entry and the top are collected, so there's never really a reason to use the comma. It's up to you. (@bullet{}) @strong{Exercise 4.} To enter the complex number @expr{(2, 3)}, your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened? (Joe thought of a clever way to correct his mistake in only two keystrokes, but it didn't quite work. Try it to find out why.) @xref{RPN Answer 4, 4}. (@bullet{}) Vectors are entered the same way as complex numbers, but with square brackets in place of parentheses. We'll meet vectors again later in the tutorial. Any Emacs command can be given a @dfn{numeric prefix argument} by typing a series of @key{META}-digits beforehand. If @key{META} is awkward for you, you can instead type @kbd{C-u} followed by the necessary digits. Numeric prefix arguments can be negative, as in @kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric prefix arguments in a variety of ways. For example, a numeric prefix on the @kbd{+} operator adds any number of stack entries at once: @smallexample @group 1: 10 2: 10 3: 10 3: 10 1: 60 . 1: 20 2: 20 2: 20 . . 1: 30 1: 30 . . 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u 3 + @end group @end smallexample For stack manipulation commands like @key{RET}, a positive numeric prefix argument operates on the top @var{n} stack entries at once. A negative argument operates on the entry in level @var{n} only. An argument of zero operates on the entire stack. In this example, we copy the second-to-top element of the stack: @smallexample @group 1: 10 2: 10 3: 10 3: 10 4: 10 . 1: 20 2: 20 2: 20 3: 20 . 1: 30 1: 30 2: 30 . . 1: 20 . 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u -2 @key{RET} @end group @end smallexample @cindex Clearing the stack @cindex Emptying the stack Another common idiom is @kbd{M-0 @key{DEL}}, which clears the stack. (The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the entire stack.) @node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial @subsection Algebraic-Style Calculations @noindent If you are not used to RPN notation, you may prefer to operate the Calculator in Algebraic mode, which is closer to the way non-RPN calculators work. In Algebraic mode, you enter formulas in traditional @expr{2+3} notation. @strong{Warning:} Note that @samp{/} has lower precedence than @samp{*}, so that @samp{a/b*c} is interpreted as @samp{a/(b*c)}. See below for details. You don't really need any special ``mode'' to enter algebraic formulas. You can enter a formula at any time by pressing the apostrophe (@kbd{'}) key. Answer the prompt with the desired formula, then press @key{RET}. The formula is evaluated and the result is pushed onto the RPN stack. If you don't want to think in RPN at all, you can enter your whole computation as a formula, read the result from the stack, then press @key{DEL} to delete it from the stack. Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}. The result should be the number 9. Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*}, @samp{/}, and @samp{^}. You can use parentheses to make the order of evaluation clear. In the absence of parentheses, @samp{^} is evaluated first, then @samp{*}, then @samp{/}, then finally @samp{+} and @samp{-}. For example, the expression @example 2 + 3*4*5 / 6*7^8 - 9 @end example @noindent is equivalent to @example 2 + ((3*4*5) / (6*(7^8)) - 9 @end example @noindent or, in large mathematical notation, @ifinfo @example @group 3 * 4 * 5 2 + --------- - 9 8 6 * 7 @end group @end example @end ifinfo @tex \turnoffactive \beforedisplay $$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$ \afterdisplay @end tex @noindent The result of this expression will be the number @mathit{-6.99999826533}. Calc's order of evaluation is the same as for most computer languages, except that @samp{*} binds more strongly than @samp{/}, as the above example shows. As in normal mathematical notation, the @samp{*} symbol can often be omitted: @samp{2 a} is the same as @samp{2*a}. Operators at the same level are evaluated from left to right, except that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is equivalent to @samp{(2-3)-4} or @mathit{-5}, whereas @samp{2^3^4} is equivalent to @samp{2^(3^4)} (a very large integer; try it!). If you tire of typing the apostrophe all the time, there is Algebraic mode, where Calc automatically senses when you are about to type an algebraic expression. To enter this mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator should appear in the Calc window's mode line.) Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}. In Algebraic mode, when you press any key that would normally begin entering a number (such as a digit, a decimal point, or the @kbd{_} key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins an algebraic entry. Functions which do not have operator symbols like @samp{+} and @samp{*} must be entered in formulas using function-call notation. For example, the function name corresponding to the square-root key @kbd{Q} is @code{sqrt}. To compute a square root in a formula, you would use the notation @samp{sqrt(@var{x})}. Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should be @expr{0.16227766017}. Note that if the formula begins with a function name, you need to use the apostrophe even if you are in Algebraic mode. If you type @kbd{arcsin} out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite command, and the @kbd{csin} will be taken as the name of the rewrite rule to use! Some people prefer to enter complex numbers and vectors in algebraic form because they find RPN entry with incomplete objects to be too distracting, even though they otherwise use Calc as an RPN calculator. Still in Algebraic mode, type: @smallexample @group 1: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1) . 1: (1, -2) . 1: 1 . . . (2,3) @key{RET} (1,-2) @key{RET} * 1 @key{RET} + @end group @end smallexample Algebraic mode allows us to enter complex numbers without pressing an apostrophe first, but it also means we need to press @key{RET} after every entry, even for a simple number like @expr{1}. (You can type @kbd{C-u m a} to enable a special Incomplete Algebraic mode in which the @kbd{(} and @kbd{[} keys use algebraic entry even though regular numeric keys still use RPN numeric entry. There is also Total Algebraic mode, started by typing @kbd{m t}, in which all normal keys begin algebraic entry. You must then use the @key{META} key to type Calc commands: @kbd{M-m t} to get back out of Total Algebraic mode, @kbd{M-q} to quit, etc.) If you're still in Algebraic mode, press @kbd{m a} again to turn it off. Actual non-RPN calculators use a mixture of algebraic and RPN styles. In general, operators of two numbers (like @kbd{+} and @kbd{*}) use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q}) use RPN form. Also, a non-RPN calculator allows you to see the intermediate results of a calculation as you go along. You can accomplish this in Calc by performing your calculation as a series of algebraic entries, using the @kbd{$} sign to tie them together. In an algebraic formula, @kbd{$} represents the number on the top of the stack. Here, we perform the calculation @texline @math{\sqrt{2\times4+1}}, @infoline @expr{sqrt(2*4+1)}, which on a traditional calculator would be done by pressing @kbd{2 * 4 + 1 =} and then the square-root key. @smallexample @group 1: 8 1: 9 1: 3 . . . ' 2*4 @key{RET} $+1 @key{RET} Q @end group @end smallexample @noindent Notice that we didn't need to press an apostrophe for the @kbd{$+1}, because the dollar sign always begins an algebraic entry. (@bullet{}) @strong{Exercise 1.} How could you get the same effect as pressing @kbd{Q} but using an algebraic entry instead? How about if the @kbd{Q} key on your keyboard were broken? @xref{Algebraic Answer 1, 1}. (@bullet{}) The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack entries. For example, @kbd{' $$+$ @key{RET}} is just like typing @kbd{+}. Algebraic formulas can include @dfn{variables}. To store in a variable, press @kbd{s s}, then type the variable name, then press @key{RET}. (There are actually two flavors of store command: @kbd{s s} stores a number in a variable but also leaves the number on the stack, while @w{@kbd{s t}} removes a number from the stack and stores it in the variable.) A variable name should consist of one or more letters or digits, beginning with a letter. @smallexample @group 1: 17 . 1: a + a^2 1: 306 . . . 17 s t a @key{RET} ' a+a^2 @key{RET} = @end group @end smallexample @noindent The @kbd{=} key @dfn{evaluates} a formula by replacing all its variables by the values that were stored in them. For RPN calculations, you can recall a variable's value on the stack either by entering its name as a formula and pressing @kbd{=}, or by using the @kbd{s r} command. @smallexample @group 1: 17 2: 17 3: 17 2: 17 1: 306 . 1: 17 2: 17 1: 289 . . 1: 2 . . s r a @key{RET} ' a @key{RET} = 2 ^ + @end group @end smallexample If you press a single digit for a variable name (as in @kbd{s t 3}, you get one of ten @dfn{quick variables} @code{q0} through @code{q9}. They are ``quick'' simply because you don't have to type the letter @code{q} or the @key{RET} after their names. In fact, you can type simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for @kbd{t 3} and @w{@kbd{r 3}}. Any variables in an algebraic formula for which you have not stored values are left alone, even when you evaluate the formula. @smallexample @group 1: 2 a + 2 b 1: 34 + 2 b . . ' 2a+2b @key{RET} = @end group @end smallexample Calls to function names which are undefined in Calc are also left alone, as are calls for which the value is undefined. @smallexample @group 1: 2 + log10(0) + log10(x) + log10(5, 6) + foo(3) . ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) @key{RET} @end group @end smallexample @noindent In this example, the first call to @code{log10} works, but the other calls are not evaluated. In the second call, the logarithm is undefined for that value of the argument; in the third, the argument is symbolic, and in the fourth, there are too many arguments. In the fifth case, there is no function called @code{foo}. You will see a ``Wrong number of arguments'' message referring to @samp{log10(5,6)}. Press the @kbd{w} (``why'') key to see any other messages that may have arisen from the last calculation. In this case you will get ``logarithm of zero,'' then ``number expected: @code{x}''. Calc automatically displays the first message only if the message is sufficiently important; for example, Calc considers ``wrong number of arguments'' and ``logarithm of zero'' to be important enough to report automatically, while a message like ``number expected: @code{x}'' will only show up if you explicitly press the @kbd{w} key. (@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y}, stored 5 in @code{x}, pressed @kbd{=}, and got the expected result, @samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)}, expecting @samp{10 (1+y)}, but it didn't work. Why not? @xref{Algebraic Answer 2, 2}. (@bullet{}) (@bullet{}) @strong{Exercise 3.} What result would you expect @kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}? @xref{Algebraic Answer 3, 3}. (@bullet{}) One interesting way to work with variables is to use the @dfn{evaluates-to} (@samp{=>}) operator. It works like this: Enter a formula algebraically in the usual way, but follow the formula with an @samp{=>} symbol. (There is also an @kbd{s =} command which builds an @samp{=>} formula using the stack.) On the stack, you will see two copies of the formula with an @samp{=>} between them. The lefthand formula is exactly like you typed it; the righthand formula has been evaluated as if by typing @kbd{=}. @smallexample @group 2: 2 + 3 => 5 2: 2 + 3 => 5 1: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b . . ' 2+3 => @key{RET} ' 2a+2b @key{RET} s = 10 s t a @key{RET} @end group @end smallexample @noindent Notice that the instant we stored a new value in @code{a}, all @samp{=>} operators already on the stack that referred to @expr{a} were updated to use the new value. With @samp{=>}, you can push a set of formulas on the stack, then change the variables experimentally to see the effects on the formulas' values. You can also ``unstore'' a variable when you are through with it: @smallexample @group 2: 2 + 5 => 5 1: 2 a + 2 b => 2 a + 2 b . s u a @key{RET} @end group @end smallexample We will encounter formulas involving variables and functions again when we discuss the algebra and calculus features of the Calculator. @node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial @subsection Undo and Redo @noindent If you make a mistake, you can usually correct it by pressing shift-@kbd{U}, the ``undo'' command. First, clear the stack (@kbd{M-0 @key{DEL}}) and exit and restart Calc (@kbd{C-x * * C-x * *}) to make sure things start off with a clean slate. Now: @smallexample @group 1: 2 2: 2 1: 8 2: 2 1: 6 . 1: 3 . 1: 3 . . . 2 @key{RET} 3 ^ U * @end group @end smallexample You can undo any number of times. Calc keeps a complete record of all you have done since you last opened the Calc window. After the above example, you could type: @smallexample @group 1: 6 2: 2 1: 2 . . . 1: 3 . . (error) U U U U @end group @end smallexample You can also type @kbd{D} to ``redo'' a command that you have undone mistakenly. @smallexample @group . 1: 2 2: 2 1: 6 1: 6 . 1: 3 . . . (error) D D D D @end group @end smallexample @noindent It was not possible to redo past the @expr{6}, since that was placed there by something other than an undo command. @cindex Time travel You can think of undo and redo as a sort of ``time machine.'' Press @kbd{U} to go backward in time, @kbd{D} to go forward. If you go backward and do something (like @kbd{*}) then, as any science fiction reader knows, you have changed your future and you cannot go forward again. Thus, the inability to redo past the @expr{6} even though there was an earlier undo command. You can always recall an earlier result using the Trail. We've ignored the trail so far, but it has been faithfully recording everything we did since we loaded the Calculator. If the Trail is not displayed, press @kbd{t d} now to turn it on. Let's try grabbing an earlier result. The @expr{8} we computed was undone by a @kbd{U} command, and was lost even to Redo when we pressed @kbd{*}, but it's still there in the trail. There should be a little @samp{>} arrow (the @dfn{trail pointer}) resting on the last trail entry. If there isn't, press @kbd{t ]} to reset the trail pointer. Now, press @w{@kbd{t p}} to move the arrow onto the line containing @expr{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the stack. If you press @kbd{t ]} again, you will see that even our Yank command went into the trail. Let's go further back in time. Earlier in the tutorial we computed a huge integer using the formula @samp{2^3^4}. We don't remember what it was, but the first digits were ``241''. Press @kbd{t r} (which stands for trail-search-reverse), then type @kbd{241}. The trail cursor will jump back to the next previous occurrence of the string ``241'' in the trail. This is just a regular Emacs incremental search; you can now press @kbd{C-s} or @kbd{C-r} to continue the search forwards or backwards as you like. To finish the search, press @key{RET}. This halts the incremental search and leaves the trail pointer at the thing we found. Now we can type @kbd{t y} to yank that number onto the stack. If we hadn't remembered the ``241'', we could simply have searched for @kbd{2^3^4}, then pressed @kbd{@key{RET} t n} to halt and then move to the next item. You may have noticed that all the trail-related commands begin with the letter @kbd{t}. (The store-and-recall commands, on the other hand, all began with @kbd{s}.) Calc has so many commands that there aren't enough keys for all of them, so various commands are grouped into two-letter sequences where the first letter is called the @dfn{prefix} key. If you type a prefix key by accident, you can press @kbd{C-g} to cancel it. (In fact, you can press @kbd{C-g} to cancel almost anything in Emacs.) To get help on a prefix key, press that key followed by @kbd{?}. Some prefixes have several lines of help, so you need to press @kbd{?} repeatedly to see them all. You can also type @kbd{h h} to see all the help at once. Try pressing @kbd{t ?} now. You will see a line of the form, @smallexample trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t- @end smallexample @noindent The word ``trail'' indicates that the @kbd{t} prefix key contains trail-related commands. Each entry on the line shows one command, with a single capital letter showing which letter you press to get that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and @kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?} again to see more @kbd{t}-prefix commands. Notice that the commands are roughly divided (by semicolons) into related groups. When you are in the help display for a prefix key, the prefix is still active. If you press another key, like @kbd{y} for example, it will be interpreted as a @kbd{t y} command. If all you wanted was to look at the help messages, press @kbd{C-g} afterwards to cancel the prefix. One more way to correct an error is by editing the stack entries. The actual Stack buffer is marked read-only and must not be edited directly, but you can press @kbd{`} (the backquote or accent grave) to edit a stack entry. Try entering @samp{3.141439} now. If this is supposed to represent @cpi{}, it's got several errors. Press @kbd{`} to edit this number. Now use the normal Emacs cursor motion and editing keys to change the second 4 to a 5, and to transpose the 3 and the 9. When you press @key{RET}, the number on the stack will be replaced by your new number. This works for formulas, vectors, and all other types of values you can put on the stack. The @kbd{`} key also works during entry of a number or algebraic formula. @node Modes Tutorial, , Undo Tutorial, Basic Tutorial @subsection Mode-Setting Commands @noindent Calc has many types of @dfn{modes} that affect the way it interprets your commands or the way it displays data. We have already seen one mode, namely Algebraic mode. There are many others, too; we'll try some of the most common ones here. Perhaps the most fundamental mode in Calc is the current @dfn{precision}. Notice the @samp{12} on the Calc window's mode line: @smallexample --%%-Calc: 12 Deg (Calculator)----All------ @end smallexample @noindent Most of the symbols there are Emacs things you don't need to worry about, but the @samp{12} and the @samp{Deg} are mode indicators. The @samp{12} means that calculations should always be carried to 12 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /}, we get @expr{0.142857142857} with exactly 12 digits, not counting leading and trailing zeros. You can set the precision to anything you like by pressing @kbd{p}, then entering a suitable number. Try pressing @kbd{p 30 @key{RET}}, then doing @kbd{1 @key{RET} 7 /} again: @smallexample @group 1: 0.142857142857 2: 0.142857142857142857142857142857 . @end group @end smallexample Although the precision can be set arbitrarily high, Calc always has to have @emph{some} value for the current precision. After all, the true value @expr{1/7} is an infinitely repeating decimal; Calc has to stop somewhere. Of course, calculations are slower the more digits you request. Press @w{@kbd{p 12}} now to set the precision back down to the default. Calculations always use the current precision. For example, even though we have a 30-digit value for @expr{1/7} on the stack, if we use it in a calculation in 12-digit mode it will be rounded down to 12 digits before it is used. Try it; press @key{RET} to duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET} key didn't round the number, because it doesn't do any calculation. But the instant we pressed @kbd{+}, the number was rounded down. @smallexample @group 1: 0.142857142857 2: 0.142857142857142857142857142857 3: 1.14285714286 . @end group @end smallexample @noindent In fact, since we added a digit on the left, we had to lose one digit on the right from even the 12-digit value of @expr{1/7}. How did we get more than 12 digits when we computed @samp{2^3^4}? The answer is that Calc makes a distinction between @dfn{integers} and @dfn{floating-point} numbers, or @dfn{floats}. An integer is a number that does not contain a decimal point. There is no such thing as an ``infinitely repeating fraction integer,'' so Calc doesn't have to limit itself. If you asked for @samp{2^10000} (don't try this!), you would have to wait a long time but you would eventually get an exact answer. If you ask for @samp{2.^10000}, you will quickly get an answer which is correct only to 12 places. The decimal point tells Calc that it should use floating-point arithmetic to get the answer, not exact integer arithmetic. You can use the @kbd{F} (@code{calc-floor}) command to convert a floating-point value to an integer, and @kbd{c f} (@code{calc-float}) to convert an integer to floating-point form. Let's try entering that last calculation: @smallexample @group 1: 2. 2: 2. 1: 1.99506311689e3010 . 1: 10000 . . 2.0 @key{RET} 10000 @key{RET} ^ @end group @end smallexample @noindent @cindex Scientific notation, entry of Notice the letter @samp{e} in there. It represents ``times ten to the power of,'' and is used by Calc automatically whenever writing the number out fully would introduce more extra zeros than you probably want to see. You can enter numbers in this notation, too. @smallexample @group 1: 2. 2: 2. 1: 1.99506311678e3010 . 1: 10000. . . 2.0 @key{RET} 1e4 @key{RET} ^ @end group @end smallexample @cindex Round-off errors @noindent Hey, the answer is different! Look closely at the middle columns of the two examples. In the first, the stack contained the exact integer @expr{10000}, but in the second it contained a floating-point value with a decimal point. When you raise a number to an integer power, Calc uses repeated squaring and multiplication to get the answer. When you use a floating-point power, Calc uses logarithms and exponentials. As you can see, a slight error crept in during one of these methods. Which one should we trust? Let's raise the precision a bit and find out: @smallexample @group . 1: 2. 2: 2. 1: 1.995063116880828e3010 . 1: 10000. . . p 16 @key{RET} 2. @key{RET} 1e4 ^ p 12 @key{RET} @end group @end smallexample @noindent @cindex Guard digits Presumably, it doesn't matter whether we do this higher-precision calculation using an integer or floating-point power, since we have added enough ``guard digits'' to trust the first 12 digits no matter what. And the verdict is@dots{} Integer powers were more accurate; in fact, the result was only off by one unit in the last place. @cindex Guard digits Calc does many of its internal calculations to a slightly higher precision, but it doesn't always bump the precision up enough. In each case, Calc added about two digits of precision during its calculation and then rounded back down to 12 digits afterward. In one case, it was enough; in the other, it wasn't. If you really need @var{x} digits of precision, it never hurts to do the calculation with a few extra guard digits. What if we want guard digits but don't want to look at them? We can set the @dfn{float format}. Calc supports four major formats for floating-point numbers, called @dfn{normal}, @dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f}, @kbd{d s}, and @kbd{d e}, respectively. In each case, you can supply a numeric prefix argument which says how many digits should be displayed. As an example, let's put a few numbers onto the stack and try some different display modes. First, use @kbd{M-0 @key{DEL}} to clear the stack, then enter the four numbers shown here: @smallexample @group 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345 3: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000 2: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450 1: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345 . . . . . d n M-3 d n d s M-3 d s M-3 d f @end group @end smallexample @noindent Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down to three significant digits, but then when we typed @kbd{d s} all five significant figures reappeared. The float format does not affect how numbers are stored, it only affects how they are displayed. Only the current precision governs the actual rounding of numbers in the Calculator's memory. Engineering notation, not shown here, is like scientific notation except the exponent (the power-of-ten part) is always adjusted to be a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result there will be one, two, or three digits before the decimal point. Whenever you change a display-related mode, Calc redraws everything in the stack. This may be slow if there are many things on the stack, so Calc allows you to type shift-@kbd{H} before any mode command to prevent it from updating the stack. Anything Calc displays after the mode-changing command will appear in the new format. @smallexample @group 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345 3: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345. 2: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45 1: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345 . . . . . H d s @key{DEL} U @key{TAB} d @key{SPC} d n @end group @end smallexample @noindent Here the @kbd{H d s} command changes to scientific notation but without updating the screen. Deleting the top stack entry and undoing it back causes it to show up in the new format; swapping the top two stack entries reformats both entries. The @kbd{d @key{SPC}} command refreshes the whole stack. The @kbd{d n} command changes back to the normal float format; since it doesn't have an @kbd{H} prefix, it also updates all the stack entries to be in @kbd{d n} format. Notice that the integer @expr{12345} was not affected by any of the float formats. Integers are integers, and are always displayed exactly. @cindex Large numbers, readability Large integers have their own problems. Let's look back at the result of @kbd{2^3^4}. @example 2417851639229258349412352 @end example @noindent Quick---how many digits does this have? Try typing @kbd{d g}: @example 2,417,851,639,229,258,349,412,352 @end example @noindent Now how many digits does this have? It's much easier to tell! We can actually group digits into clumps of any size. Some people prefer @kbd{M-5 d g}: @example 24178,51639,22925,83494,12352 @end example Let's see what happens to floating-point numbers when they are grouped. First, type @kbd{p 25 @key{RET}} to make sure we have enough precision to get ourselves into trouble. Now, type @kbd{1e13 /}: @example 24,17851,63922.9258349412352 @end example @noindent The integer part is grouped but the fractional part isn't. Now try @kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five): @example 24,17851,63922.92583,49412,352 @end example If you find it hard to tell the decimal point from the commas, try changing the grouping character to a space with @kbd{d , @key{SPC}}: @example 24 17851 63922.92583 49412 352 @end example Type @kbd{d , ,} to restore the normal grouping character, then @kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to restore the default precision. Press @kbd{U} enough times to get the original big integer back. (Notice that @kbd{U} does not undo each mode-setting command; if you want to undo a mode-setting command, you have to do it yourself.) Now, type @kbd{d r 16 @key{RET}}: @example 16#200000000000000000000 @end example @noindent The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form. Suddenly it looks pretty simple; this should be no surprise, since we got this number by computing a power of two, and 16 is a power of 2. In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary form: @example 2#1000000000000000000000000000000000000000000000000000000 @dots{} @end example @noindent We don't have enough space here to show all the zeros! They won't fit on a typical screen, either, so you will have to use horizontal scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the stack window left and right by half its width. Another way to view something large is to press @kbd{`} (back-quote) to edit the top of stack in a separate window. (Press @kbd{C-c C-c} when you are done.) You can enter non-decimal numbers using the @kbd{#} symbol, too. Let's see what the hexadecimal number @samp{5FE} looks like in binary. Type @kbd{16#5FE} (the letters can be typed in upper or lower case; they will always appear in upper case). It will also help to turn grouping on with @kbd{d g}: @example 2#101,1111,1110 @end example Notice that @kbd{d g} groups by fours by default if the display radix is binary or hexadecimal, but by threes if it is decimal, octal, or any other radix. Now let's see that number in decimal; type @kbd{d r 10}: @example 1,534 @end example Numbers are not @emph{stored} with any particular radix attached. They're just numbers; they can be entered in any radix, and are always displayed in whatever radix you've chosen with @kbd{d r}. The current radix applies to integers, fractions, and floats. @cindex Roundoff errors, in non-decimal numbers (@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got @samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied that by three, he got @samp{3#0.222222...} instead of the expected @samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief, saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got @samp{3#0.10000001} (some zeros omitted). What's going on here? @xref{Modes Answer 1, 1}. (@bullet{}) @cindex Scientific notation, in non-decimal numbers (@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal modes in the natural way (the exponent is a power of the radix instead of a power of ten, although the exponent itself is always written in decimal). Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number @samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}. What is wrong with this picture? What could we write instead that would work better? @xref{Modes Answer 2, 2}. (@bullet{}) The @kbd{m} prefix key has another set of modes, relating to the way Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix modes generally affect the way things look, @kbd{m}-prefix modes affect the way they are actually computed. The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice the @samp{Deg} indicator in the mode line. This means that if you use a command that interprets a number as an angle, it will assume the angle is measured in degrees. For example, @smallexample @group 1: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5 . . . . 45 S 2 ^ c 1 @end group @end smallexample @noindent The shift-@kbd{S} command computes the sine of an angle. The sine of 45 degrees is @texline @math{\sqrt{2}/2}; @infoline @expr{sqrt(2)/2}; squaring this yields @expr{2/4 = 0.5}. However, there has been a slight roundoff error because the representation of @texline @math{\sqrt{2}/2} @infoline @expr{sqrt(2)/2} wasn't exact. The @kbd{c 1} command is a handy way to clean up numbers in this case; it temporarily reduces the precision by one digit while it re-rounds the number on the top of the stack. @cindex Roundoff errors, examples (@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine of 45 degrees as shown above, then, hoping to avoid an inexact result, he increased the precision to 16 digits before squaring. What happened? @xref{Modes Answer 3, 3}. (@bullet{}) To do this calculation in radians, we would type @kbd{m r} first. (The indicator changes to @samp{Rad}.) 45 degrees corresponds to @cpiover{4} radians. To get @cpi{}, press the @kbd{P} key. (Once again, this is a shifted capital @kbd{P}. Remember, unshifted @kbd{p} sets the precision.) @smallexample @group 1: 3.14159265359 1: 0.785398163398 1: 0.707106781187 . . . P 4 / m r S @end group @end smallexample Likewise, inverse trigonometric functions generate results in either radians or degrees, depending on the current angular mode. @smallexample @group 1: 0.707106781187 1: 0.785398163398 1: 45. . . . .5 Q m r I S m d U I S @end group @end smallexample @noindent Here we compute the Inverse Sine of @texline @math{\sqrt{0.5}}, @infoline @expr{sqrt(0.5)}, first in radians, then in degrees. Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees and vice-versa. @smallexample @group 1: 45 1: 0.785398163397 1: 45. . . . 45 c r c d @end group @end smallexample Another interesting mode is @dfn{Fraction mode}. Normally, dividing two integers produces a floating-point result if the quotient can't be expressed as an exact integer. Fraction mode causes integer division to produce a fraction, i.e., a rational number, instead. @smallexample @group 2: 12 1: 1.33333333333 1: 4:3 1: 9 . . . 12 @key{RET} 9 / m f U / m f @end group @end smallexample @noindent In the first case, we get an approximate floating-point result. In the second case, we get an exact fractional result (four-thirds). You can enter a fraction at any time using @kbd{:} notation. (Calc uses @kbd{:} instead of @kbd{/} as the fraction separator because @kbd{/} is already used to divide the top two stack elements.) Calculations involving fractions will always produce exact fractional results; Fraction mode only says what to do when dividing two integers. @cindex Fractions vs. floats @cindex Floats vs. fractions (@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact, why would you ever use floating-point numbers instead? @xref{Modes Answer 4, 4}. (@bullet{}) Typing @kbd{m f} doesn't change any existing values in the stack. In the above example, we had to Undo the division and do it over again when we changed to Fraction mode. But if you use the evaluates-to operator you can get commands like @kbd{m f} to recompute for you. @smallexample @group 1: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3 . . . ' 12/9 => @key{RET} p 4 @key{RET} m f @end group @end smallexample @noindent In this example, the righthand side of the @samp{=>} operator on the stack is recomputed when we change the precision, then again when we change to Fraction mode. All @samp{=>} expressions on the stack are recomputed every time you change any mode that might affect their values. @node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial @section Arithmetic Tutorial @noindent In this section, we explore the arithmetic and scientific functions available in the Calculator. The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^}. Each normally takes two numbers from the top of the stack and pushes back a result. The @kbd{n} and @kbd{&} keys perform change-sign and reciprocal operations, respectively. @smallexample @group 1: 5 1: 0.2 1: 5. 1: -5. 1: 5. . . . . . 5 & & n n @end group @end smallexample @cindex Binary operators You can apply a ``binary operator'' like @kbd{+} across any number of stack entries by giving it a numeric prefix. You can also apply it pairwise to several stack elements along with the top one if you use a negative prefix. @smallexample @group 3: 2 1: 9 3: 2 4: 2 3: 12 2: 3 . 2: 3 3: 3 2: 13 1: 4 1: 4 2: 4 1: 14 . . 1: 10 . . 2 @key{RET} 3 @key{RET} 4 M-3 + U 10 M-- M-3 + @end group @end smallexample @cindex Unary operators You can apply a ``unary operator'' like @kbd{&} to the top @var{n} stack entries with a numeric prefix, too. @smallexample @group 3: 2 3: 0.5 3: 0.5 2: 3 2: 0.333333333333 2: 3. 1: 4 1: 0.25 1: 4. . . . 2 @key{RET} 3 @key{RET} 4 M-3 & M-2 & @end group @end smallexample Notice that the results here are left in floating-point form. We can convert them back to integers by pressing @kbd{F}, the ``floor'' function. This function rounds down to the next lower integer. There is also @kbd{R}, which rounds to the nearest integer. @smallexample @group 7: 2. 7: 2 7: 2 6: 2.4 6: 2 6: 2 5: 2.5 5: 2 5: 3 4: 2.6 4: 2 4: 3 3: -2. 3: -2 3: -2 2: -2.4 2: -3 2: -2 1: -2.6 1: -3 1: -3 . . . M-7 F U M-7 R @end group @end smallexample Since dividing-and-flooring (i.e., ``integer quotient'') is such a common operation, Calc provides a special command for that purpose, the backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which computes the remainder that would arise from a @kbd{\} operation, i.e., the ``modulo'' of two numbers. For example, @smallexample @group 2: 1234 1: 12 2: 1234 1: 34 1: 100 . 1: 100 . . . 1234 @key{RET} 100 \ U % @end group @end smallexample These commands actually work for any real numbers, not just integers. @smallexample @group 2: 3.1415 1: 3 2: 3.1415 1: 0.1415 1: 1 . 1: 1 . . . 3.1415 @key{RET} 1 \ U % @end group @end smallexample (@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a frill, since you could always do the same thing with @kbd{/ F}. Think of a situation where this is not true---@kbd{/ F} would be inadequate. Now think of a way you could get around the problem if Calc didn't provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{}) We've already seen the @kbd{Q} (square root) and @kbd{S} (sine) commands. Other commands along those lines are @kbd{C} (cosine), @kbd{T} (tangent), @kbd{E} (@expr{e^x}) and @kbd{L} (natural logarithm). These can be modified by the @kbd{I} (inverse) and @kbd{H} (hyperbolic) prefix keys. Let's compute the sine and cosine of an angle, and verify the identity @texline @math{\sin^2x + \cos^2x = 1}. @infoline @expr{sin(x)^2 + cos(x)^2 = 1}. We'll arbitrarily pick @mathit{-64} degrees as a good value for @expr{x}. With the angular mode set to degrees (type @w{@kbd{m d}}), do: @smallexample @group 2: -64 2: -64 2: -0.89879 2: -0.89879 1: 1. 1: -64 1: -0.89879 1: -64 1: 0.43837 . . . . . 64 n @key{RET} @key{RET} S @key{TAB} C f h @end group @end smallexample @noindent (For brevity, we're showing only five digits of the results here. You can of course do these calculations to any precision you like.) Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum of squares, command. Another identity is @texline @math{\displaystyle\tan x = {\sin x \over \cos x}}. @infoline @expr{tan(x) = sin(x) / cos(x)}. @smallexample @group 2: -0.89879 1: -2.0503 1: -64. 1: 0.43837 . . . U / I T @end group @end smallexample A physical interpretation of this calculation is that if you move @expr{0.89879} units downward and @expr{0.43837} units to the right, your direction of motion is @mathit{-64} degrees from horizontal. Suppose we move in the opposite direction, up and to the left: @smallexample @group 2: -0.89879 2: 0.89879 1: -2.0503 1: -64. 1: 0.43837 1: -0.43837 . . . . U U M-2 n / I T @end group @end smallexample @noindent How can the angle be the same? The answer is that the @kbd{/} operation loses information about the signs of its inputs. Because the quotient is negative, we know exactly one of the inputs was negative, but we can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which computes the inverse tangent of the quotient of a pair of numbers. Since you feed it the two original numbers, it has enough information to give you a full 360-degree answer. @smallexample @group 2: 0.89879 1: 116. 3: 116. 2: 116. 1: 180. 1: -0.43837 . 2: -0.89879 1: -64. . . 1: 0.43837 . . U U f T M-@key{RET} M-2 n f T - @end group @end smallexample @noindent The resulting angles differ by 180 degrees; in other words, they point in opposite directions, just as we would expect. The @key{META}-@key{RET} we used in the third step is the ``last-arguments'' command. It is sort of like Undo, except that it restores the arguments of the last command to the stack without removing the command's result. It is useful in situations like this one, where we need to do several operations on the same inputs. We could have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate the top two stack elements right after the @kbd{U U}, then a pair of @kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates. A similar identity is supposed to hold for hyperbolic sines and cosines, except that it is the @emph{difference} @texline @math{\cosh^2x - \sinh^2x} @infoline @expr{cosh(x)^2 - sinh(x)^2} that always equals one. Let's try to verify this identity. @smallexample @group 2: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54 1: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54 . . . . . 64 n @key{RET} @key{RET} H C 2 ^ @key{TAB} H S 2 ^ @end group @end smallexample @noindent @cindex Roundoff errors, examples Something's obviously wrong, because when we subtract these numbers the answer will clearly be zero! But if you think about it, if these numbers @emph{did} differ by one, it would be in the 55th decimal place. The difference we seek has been lost entirely to roundoff error. We could verify this hypothesis by doing the actual calculation with, say, 60 decimal places of precision. This will be slow, but not enormously so. Try it if you wish; sure enough, the answer is 0.99999, reasonably close to 1. Of course, a more reasonable way to verify the identity is to use a more reasonable value for @expr{x}! @cindex Common logarithm Some Calculator commands use the Hyperbolic prefix for other purposes. The logarithm and exponential functions, for example, work to the base @expr{e} normally but use base-10 instead if you use the Hyperbolic prefix. @smallexample @group 1: 1000 1: 6.9077 1: 1000 1: 3 . . . . 1000 L U H L @end group @end smallexample @noindent First, we mistakenly compute a natural logarithm. Then we undo and compute a common logarithm instead. The @kbd{B} key computes a general base-@var{b} logarithm for any value of @var{b}. @smallexample @group 2: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077 1: 10 . . 1: 2.71828 . . . 1000 @key{RET} 10 B H E H P B @end group @end smallexample @noindent Here we first use @kbd{B} to compute the base-10 logarithm, then use the ``hyperbolic'' exponential as a cheap hack to recover the number 1000, then use @kbd{B} again to compute the natural logarithm. Note that @kbd{P} with the hyperbolic prefix pushes the constant @expr{e} onto the stack. You may have noticed that both times we took the base-10 logarithm of 1000, we got an exact integer result. Calc always tries to give an exact rational result for calculations involving rational numbers where possible. But when we used @kbd{H E}, the result was a floating-point number for no apparent reason. In fact, if we had computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an exact integer 1000. But the @kbd{H E} command is rigged to generate a floating-point result all of the time so that @kbd{1000 H E} will not waste time computing a thousand-digit integer when all you probably wanted was @samp{1e1000}. (@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to the @kbd{B} command for which Calc could find an exact rational result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{}) The Calculator also has a set of functions relating to combinatorics and statistics. You may be familiar with the @dfn{factorial} function, which computes the product of all the integers up to a given number. @smallexample @group 1: 100 1: 93326215443... 1: 100. 1: 9.3326e157 . . . . 100 ! U c f ! @end group @end smallexample @noindent Recall, the @kbd{c f} command converts the integer or fraction at the top of the stack to floating-point format. If you take the factorial of a floating-point number, you get a floating-point result accurate to the current precision. But if you give @kbd{!} an exact integer, you get an exact integer result (158 digits long in this case). If you take the factorial of a non-integer, Calc uses a generalized factorial function defined in terms of Euler's Gamma function @texline @math{\Gamma(n)} @infoline @expr{gamma(n)} (which is itself available as the @kbd{f g} command). @smallexample @group 3: 4. 3: 24. 1: 5.5 1: 52.342777847 2: 4.5 2: 52.3427777847 . . 1: 5. 1: 120. . . M-3 ! M-0 @key{DEL} 5.5 f g @end group @end smallexample @noindent Here we verify the identity @texline @math{n! = \Gamma(n+1)}. @infoline @expr{@var{n}!@: = gamma(@var{n}+1)}. The binomial coefficient @var{n}-choose-@var{m} @texline or @math{\displaystyle {n \choose m}} is defined by @texline @math{\displaystyle {n! \over m! \, (n-m)!}} @infoline @expr{n!@: / m!@: (n-m)!} for all reals @expr{n} and @expr{m}. The intermediate results in this formula can become quite large even if the final result is small; the @kbd{k c} command computes a binomial coefficient in a way that avoids large intermediate values. The @kbd{k} prefix key defines several common functions out of combinatorics and number theory. Here we compute the binomial coefficient 30-choose-20, then determine its prime factorization. @smallexample @group 2: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29] 1: 20 . . . 30 @key{RET} 20 k c k f @end group @end smallexample @noindent You can verify these prime factors by using @kbd{v u} to ``unpack'' this vector into 8 separate stack entries, then @kbd{M-8 *} to multiply them back together. The result is the original number, 30045015. @cindex Hash tables Suppose a program you are writing needs a hash table with at least 10000 entries. It's best to use a prime number as the actual size of a hash table. Calc can compute the next prime number after 10000: @smallexample @group 1: 10000 1: 10007 1: 9973 . . . 10000 k n I k n @end group @end smallexample @noindent Just for kicks we've also computed the next prime @emph{less} than 10000. @c [fix-ref Financial Functions] @xref{Financial Functions}, for a description of the Calculator commands that deal with business and financial calculations (functions like @code{pv}, @code{rate}, and @code{sln}). @c [fix-ref Binary Number Functions] @xref{Binary Functions}, to read about the commands for operating on binary numbers (like @code{and}, @code{xor}, and @code{lsh}). @node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial @section Vector/Matrix Tutorial @noindent A @dfn{vector} is a list of numbers or other Calc data objects. Calc provides a large set of commands that operate on vectors. Some are familiar operations from vector analysis. Others simply treat a vector as a list of objects. @menu * Vector Analysis Tutorial:: * Matrix Tutorial:: * List Tutorial:: @end menu @node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial @subsection Vector Analysis @noindent If you add two vectors, the result is a vector of the sums of the elements, taken pairwise. @smallexample @group 1: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3] . 1: [7, 6, 0] . . [1,2,3] s 1 [7 6 0] s 2 + @end group @end smallexample @noindent Note that we can separate the vector elements with either commas or spaces. This is true whether we are using incomplete vectors or algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these vectors so we can easily reuse them later. If you multiply two vectors, the result is the sum of the products of the elements taken pairwise. This is called the @dfn{dot product} of the vectors. @smallexample @group 2: [1, 2, 3] 1: 19 1: [7, 6, 0] . . r 1 r 2 * @end group @end smallexample @cindex Dot product The dot product of two vectors is equal to the product of their lengths times the cosine of the angle between them. (Here the vector is interpreted as a line from the origin @expr{(0,0,0)} to the specified point in three-dimensional space.) The @kbd{A} (absolute value) command can be used to compute the length of a vector. @smallexample @group 3: 19 3: 19 1: 0.550782 1: 56.579 2: [1, 2, 3] 2: 3.741657 . . 1: [7, 6, 0] 1: 9.219544 . . M-@key{RET} M-2 A * / I C @end group @end smallexample @noindent First we recall the arguments to the dot product command, then we compute the absolute values of the top two stack entries to obtain the lengths of the vectors, then we divide the dot product by the product of the lengths to get the cosine of the angle. The inverse cosine finds that the angle between the vectors is about 56 degrees. @cindex Cross product @cindex Perpendicular vectors The @dfn{cross product} of two vectors is a vector whose length is the product of the lengths of the inputs times the sine of the angle between them, and whose direction is perpendicular to both input vectors. Unlike the dot product, the cross product is defined only for three-dimensional vectors. Let's double-check our computation of the angle using the cross product. @smallexample @group 2: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579 1: [7, 6, 0] 2: [1, 2, 3] . . . 1: [7, 6, 0] . r 1 r 2 V C s 3 M-@key{RET} M-2 A * / A I S @end group @end smallexample @noindent First we recall the original vectors and compute their cross product, which we also store for later reference. Now we divide the vector by the product of the lengths of the original vectors. The length of this vector should be the sine of the angle; sure enough, it is! @c [fix-ref General Mode Commands] Vector-related commands generally begin with the @kbd{v} prefix key. Some are uppercase letters and some are lowercase. To make it easier to type these commands, the shift-@kbd{V} prefix key acts the same as the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all prefix keys have this property.) If we take the dot product of two perpendicular vectors we expect to get zero, since the cosine of 90 degrees is zero. Let's check that the cross product is indeed perpendicular to both inputs: @smallexample @group 2: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0 1: [-18, 21, -8] . 1: [-18, 21, -8] . . . r 1 r 3 * @key{DEL} r 2 r 3 * @end group @end smallexample @cindex Normalizing a vector @cindex Unit vectors (@bullet{}) @strong{Exercise 1.} Given a vector on the top of the stack, what keystrokes would you use to @dfn{normalize} the vector, i.e., to reduce its length to one without changing its direction? @xref{Vector Answer 1, 1}. (@bullet{}) (@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be at any of several positions along a ruler. You have a list of those positions in the form of a vector, and another list of the probabilities for the particle to be at the corresponding positions. Find the average position of the particle. @xref{Vector Answer 2, 2}. (@bullet{}) @node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial @subsection Matrices @noindent A @dfn{matrix} is just a vector of vectors, all the same length. This means you can enter a matrix using nested brackets. You can also use the semicolon character to enter a matrix. We'll show both methods here: @smallexample @group 1: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] . . [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] @key{RET} @end group @end smallexample @noindent We'll be using this matrix again, so type @kbd{s 4} to save it now. Note that semicolons work with incomplete vectors, but they work better in algebraic entry. That's why we use the apostrophe in the second example. When two matrices are multiplied, the lefthand matrix must have the same number of columns as the righthand matrix has rows. Row @expr{i}, column @expr{j} of the result is effectively the dot product of row @expr{i} of the left matrix by column @expr{j} of the right matrix. If we try to duplicate this matrix and multiply it by itself, the dimensions are wrong and the multiplication cannot take place: @smallexample @group 1: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] . @key{RET} * @end group @end smallexample @noindent Though rather hard to read, this is a formula which shows the product of two matrices. The @samp{*} function, having invalid arguments, has been left in symbolic form. We can multiply the matrices if we @dfn{transpose} one of them first. @smallexample @group 2: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ] [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ] 1: [ [ 1, 4 ] . [ 27, 36, 45 ] ] [ 2, 5 ] . [ 3, 6 ] ] . U v t * U @key{TAB} * @end group @end smallexample Matrix multiplication is not commutative; indeed, switching the order of the operands can even change the dimensions of the result matrix, as happened here! If you multiply a plain vector by a matrix, it is treated as a single row or column depending on which side of the matrix it is on. The result is a plain vector which should also be interpreted as a row or column as appropriate. @smallexample @group 2: [ [ 1, 2, 3 ] 1: [14, 32] [ 4, 5, 6 ] ] . 1: [1, 2, 3] . r 4 r 1 * @end group @end smallexample Multiplying in the other order wouldn't work because the number of rows in the matrix is different from the number of elements in the vector. (@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows of the above @texline @math{2\times3} @infoline 2x3 matrix to get @expr{[6, 15]}. Now use @samp{*} to sum along the columns to get @expr{[5, 7, 9]}. @xref{Matrix Answer 1, 1}. (@bullet{}) @cindex Identity matrix An @dfn{identity matrix} is a square matrix with ones along the diagonal and zeros elsewhere. It has the property that multiplication by an identity matrix, on the left or on the right, always produces the original matrix. @smallexample @group 1: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] . 1: [ [ 1, 0, 0 ] . [ 0, 1, 0 ] [ 0, 0, 1 ] ] . r 4 v i 3 @key{RET} * @end group @end smallexample If a matrix is square, it is often possible to find its @dfn{inverse}, that is, a matrix which, when multiplied by the original matrix, yields an identity matrix. The @kbd{&} (reciprocal) key also computes the inverse of a matrix. @smallexample @group 1: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ] [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ] [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ] . . r 4 r 2 | s 5 & @end group @end smallexample @noindent The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and matrices together. Here we have used it to add a new row onto our matrix to make it square. We can multiply these two matrices in either order to get an identity. @smallexample @group 1: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ] [ 0., 1., 0. ] [ 0., 1., 0. ] [ 0., 0., 1. ] ] [ 0., 0., 1. ] ] . . M-@key{RET} * U @key{TAB} * @end group @end smallexample @cindex Systems of linear equations @cindex Linear equations, systems of Matrix inverses are related to systems of linear equations in algebra. Suppose we had the following set of equations: @ifinfo @group @example a + 2b + 3c = 6 4a + 5b + 6c = 2 7a + 6b = 3 @end example @end group @end ifinfo @tex \turnoffactive \beforedisplayh $$ \openup1\jot \tabskip=0pt plus1fil \halign to\displaywidth{\tabskip=0pt $\hfil#$&$\hfil{}#{}$& $\hfil#$&$\hfil{}#{}$& $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr a&+&2b&+&3c&=6 \cr 4a&+&5b&+&6c&=2 \cr 7a&+&6b& & &=3 \cr} $$ \afterdisplayh @end tex @noindent This can be cast into the matrix equation, @ifinfo @group @example [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ] [ 4, 5, 6 ] * [ b ] = [ 2 ] [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ] @end example @end group @end ifinfo @tex \turnoffactive \beforedisplay $$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 } \times \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 } $$ \afterdisplay @end tex We can solve this system of equations by multiplying both sides by the inverse of the matrix. Calc can do this all in one step: @smallexample @group 2: [6, 2, 3] 1: [-12.6, 15.2, -3.93333] 1: [ [ 1, 2, 3 ] . [ 4, 5, 6 ] [ 7, 6, 0 ] ] . [6,2,3] r 5 / @end group @end smallexample @noindent The result is the @expr{[a, b, c]} vector that solves the equations. (Dividing by a square matrix is equivalent to multiplying by its inverse.) Let's verify this solution: @smallexample @group 2: [ [ 1, 2, 3 ] 1: [6., 2., 3.] [ 4, 5, 6 ] . [ 7, 6, 0 ] ] 1: [-12.6, 15.2, -3.93333] . r 5 @key{TAB} * @end group @end smallexample @noindent Note that we had to be careful about the order in which we multiplied the matrix and vector. If we multiplied in the other order, Calc would assume the vector was a row vector in order to make the dimensions come out right, and the answer would be incorrect. If you don't feel safe letting Calc take either interpretation of your vectors, use explicit @texline @math{N\times1} @infoline Nx1 or @texline @math{1\times N} @infoline 1xN matrices instead. In this case, you would enter the original column vector as @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}. (@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make vectors and matrices that include variables. Solve the following system of equations to get expressions for @expr{x} and @expr{y} in terms of @expr{a} and @expr{b}. @ifinfo @group @example x + a y = 6 x + b y = 10 @end example @end group @end ifinfo @tex \turnoffactive \beforedisplay $$ \eqalign{ x &+ a y = 6 \cr x &+ b y = 10} $$ \afterdisplay @end tex @noindent @xref{Matrix Answer 2, 2}. (@bullet{}) @cindex Least-squares for over-determined systems @cindex Over-determined systems of equations (@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined'' if it has more equations than variables. It is often the case that there are no values for the variables that will satisfy all the equations at once, but it is still useful to find a set of values which ``nearly'' satisfy all the equations. In terms of matrix equations, you can't solve @expr{A X = B} directly because the matrix @expr{A} is not square for an over-determined system. Matrix inversion works only for square matrices. One common trick is to multiply both sides on the left by the transpose of @expr{A}: @ifinfo @samp{trn(A)*A*X = trn(A)*B}. @end ifinfo @tex \turnoffactive $A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}. @end tex Now @texline @math{A^T A} @infoline @expr{trn(A)*A} is a square matrix so a solution is possible. It turns out that the @expr{X} vector you compute in this way will be a ``least-squares'' solution, which can be regarded as the ``closest'' solution to the set of equations. Use Calc to solve the following over-determined system: @ifinfo @group @example a + 2b + 3c = 6 4a + 5b + 6c = 2 7a + 6b = 3 2a + 4b + 6c = 11 @end example @end group @end ifinfo @tex \turnoffactive \beforedisplayh $$ \openup1\jot \tabskip=0pt plus1fil \halign to\displaywidth{\tabskip=0pt $\hfil#$&$\hfil{}#{}$& $\hfil#$&$\hfil{}#{}$& $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr a&+&2b&+&3c&=6 \cr 4a&+&5b&+&6c&=2 \cr 7a&+&6b& & &=3 \cr 2a&+&4b&+&6c&=11 \cr} $$ \afterdisplayh @end tex @noindent @xref{Matrix Answer 3, 3}. (@bullet{}) @node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial @subsection Vectors as Lists @noindent @cindex Lists Although Calc has a number of features for manipulating vectors and matrices as mathematical objects, you can also treat vectors as simple lists of values. For example, we saw that the @kbd{k f} command returns a vector which is a list of the prime factors of a number. You can pack and unpack stack entries into vectors: @smallexample @group 3: 10 1: [10, 20, 30] 3: 10 2: 20 . 2: 20 1: 30 1: 30 . . M-3 v p v u @end group @end smallexample You can also build vectors out of consecutive integers, or out of many copies of a given value: @smallexample @group 1: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4] . 1: 17 1: [17, 17, 17, 17] . . v x 4 @key{RET} 17 v b 4 @key{RET} @end group @end smallexample You can apply an operator to every element of a vector using the @dfn{map} command. @smallexample @group 1: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68] . . . V M * 2 V M ^ V M Q @end group @end smallexample @noindent In the first step, we multiply the vector of integers by the vector of 17's elementwise. In the second step, we raise each element to the power two. (The general rule is that both operands must be vectors of the same length, or else one must be a vector and the other a plain number.) In the final step, we take the square root of each element. (@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two from @texline @math{2^{-4}} @infoline @expr{2^-4} to @expr{2^4}. @xref{List Answer 1, 1}. (@bullet{}) You can also @dfn{reduce} a binary operator across a vector. For example, reducing @samp{*} computes the product of all the elements in the vector: @smallexample @group 1: 123123 1: [3, 7, 11, 13, 41] 1: 123123 . . . 123123 k f V R * @end group @end smallexample @noindent In this example, we decompose 123123 into its prime factors, then multiply those factors together