The GNU Emacs Calculator

Calc is an advanced desk calculator and mathematical tool written by Dave Gillespie that runs as part of the GNU Emacs environment.

This manual, also written (mostly) by Dave Gillespie, 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.

This file documents Calc, the GNU Emacs calculator, included with GNU Emacs 27.1.

Copyright © 1990–1991, 2001–2020 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 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 the freedom to copy and modify this GNU manual.”

1 Getting Started

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.

1.1 What is Calc?

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:

Choice of algebraic or RPN (stack-based) entry of calculations.

Arbitrary precision integers and floating-point numbers.

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.

Mathematical operations such as logarithms and trigonometric functions.

Programmer’s features (bitwise operations, non-decimal numbers).

Financial functions such as future value and internal rate of return.

Number theoretical features such as prime factorization and arithmetic modulo m for any m .

for any . Algebraic manipulation features, including symbolic calculus.

Moving data to and from regular editing buffers.

Embedded mode for manipulating Calc formulas and data directly inside any editing buffer.

Graphics using GNUPLOT, a versatile (and free) plotting program.

Easy programming using keyboard macros, algebraic formulas, algebraic rewrite rules, or extended Emacs Lisp.

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.

1.2 About This Manual

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.

This manual is divided into three major parts: the “Getting Started” chapter you are reading now, the Calc tutorial, and the Calc reference manual.

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. See 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.

Every Calc keyboard command is listed in the Calc Summary, and also in the Key Index. Algebraic functions, M-x commands, and variables also have their own indices.

You can access this manual on-line at any time within Calc by pressing the h i key sequence. Outside of the Calc window, you can press C-x * i to read the manual on-line. From within Calc the command h t will jump directly to the Tutorial; from outside of Calc the command C-x * t will jump to the Tutorial and start Calc if necessary. Pressing h s or C-x * s will take you directly to the Calc Summary. Within Calc, you can also go to the part of the manual describing any Calc key, function, or variable using h k , h f , or h v , respectively. See 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 texindex program and texinfo.tex file, both of which can be obtained from the FSF as part of the texinfo package. To print the Calc manual in one huge tome, you will need the Emacs source, which contains the source code to this manual, calc.texi . Change to the doc/misc subdirectory of the Emacs source distribution, which contains source code for this manual, and type make calc.pdf . (Don’t worry if you get some “overfull box” warnings while TeX runs.) The result will be this entire manual as a pdf file.

1.3 Notations Used in This Manual

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 C-x . Keys pressed with Meta held down are shown as M-x . Other notations are RET for the Return key, SPC for the space bar, TAB for the Tab key, DEL for the Delete key, and LFD for the Line-Feed key. The 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 LFD or TAB keys on your keyboard, the C-j and 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 ESC or C-[ first to get the same effect, so that M-x , ESC x , and C-[ x are all equivalent.)

Sometimes the RET key is not shown when it is “obvious” that you must press RET to proceed. For example, the RET is usually omitted in key sequences like M-x calc-keypad RET .

Commands are generally shown like this: p ( calc-precision ) or C-x * k ( calc-keypad ). This means that the command is normally used by pressing the p key or C-x * k key sequence, but it also has the full-name equivalent shown, e.g., M-x calc-precision .

Commands that correspond to functions in algebraic notation are written: C ( calc-cos ) [ cos ]. This means the C key is equivalent to M-x calc-cos , and that the corresponding function in an algebraic-style formula would be ‘ cos( x ) ’.

A few commands don’t have key equivalents: calc-sincos [ sincos ].

1.4 A 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 emacs does this), and type C-x * c to start the Calculator. (You can also use M-x calc if this doesn’t work. See 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, RET , TAB , DEL , and SPC are the Return, Tab, Delete, and Space keys.

RPN calculation. In RPN, you type the input number(s) first, then the command to operate on the numbers.

Type 2 RET 3 + Q to compute the square root of 2+3, which is 2.2360679775.

Type P 2 ^ to compute the value of ‘ pi ’ squared, 9.86960440109.

Type TAB to exchange the order of these two results.

Type - I H S to subtract these results and compute the Inverse Hyperbolic sine of the difference, 2.72996136574.

Type DEL to erase this result.

Algebraic calculation. You can also enter calculations using conventional “algebraic” notation. To enter an algebraic formula, use the apostrophe key.

Type ' sqrt(2+3) RET to compute the square root of 2+3.

Type ' pi^2 RET to enter ‘ pi ’ squared. To evaluate this symbolic formula as a number, type = .

Type ' arcsinh($ - $$) RET to subtract the second-most-recent result from the most-recent and compute the Inverse Hyperbolic sine.

Keypad mode. If you are using the X window system, press C-x * k to get Keypad mode. (If you don’t use X, skip to the next section.)

Click on the 2 , ENTER , 3 , + , and SQRT “buttons” using your left mouse button.

Click on PI , 2 , and y^x .

Click on INV , then ENTER to swap the two results.

Click on - , INV , HYP , and SIN .

Click on <- to erase the result, then click OFF to turn the Keypad Calculator off.

Grabbing data. Type 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 C-SPC or 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 C-x * i , or just type these numbers into a scratch file.) Now type C-x * g to “grab” these numbers into Calc.

1.23 1.97 1.6 2 1.19 1.08

The result ‘ [1.23, 1.97, 1.6, 2, 1.19, 1.08] ’ is a Calc “vector.” Type V R + to compute the sum of these numbers.

Type U to Undo this command, then type V R * to compute the product of the numbers.

You can also grab data as a rectangular matrix. Place the cursor on the upper-leftmost ‘ 1 ’ and set the mark, then move to just after the lower-right ‘ 8 ’ and press C-x * r .

Type v t to transpose this 3x2 matrix into a 2x3 matrix. Type v u to unpack the rows into two separate vectors. Now type V R + TAB V R + to compute the sums of the two original columns. (There is also a special grab-and-sum-columns command, C-x * : .)

Units conversion. Units are entered algebraically. Type ' 43 mi/hr RET to enter the quantity 43 miles-per-hour. Type u c km/hr RET . Type u c m/s RET .

Date arithmetic. Type t N to get the current date and time. Type 90 + to find the date 90 days from now. Type ' <25 dec 87> RET to enter a date, then - 7 / to see how many weeks have passed since then.

Algebra. Algebraic entries can also include formulas or equations involving variables. Type ' [x + y = a, x y = 1] RET to enter a pair of equations involving three variables. (Note the leading apostrophe in this example; also, note that the space in ‘ x y ’ is required.) Type a S x,y RET to solve these equations for the variables ‘ x ’ and ‘ y ’.

Type d B to view the solutions in more readable notation. Type d C to view them in C language notation, d T to view them in the notation for the TeX typesetting system, and d L to view them in the notation for the LaTeX typesetting system. Type d N to return to normal notation.

Type 7.5 , then s l a RET to let ‘ a = 7.5 ’ in these formulas. (That’s the letter l , not the numeral 1 .)

Help functions. You can read about any command in the on-line manual. Type C-x * c to return to Calc after each of these commands: h k t N to read about the t N command, h f sqrt RET to read about the sqrt function, and h s to read the Calc summary.

Press DEL repeatedly to remove any leftover results from the stack. To exit from Calc, press q or C-x * c again.

1.5 Using Calc

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.

1.5.1 Starting Calc

On most systems, you can type C-x * to start the Calculator. The key sequence C-x * is bound to the command calc-dispatch , which can be rebound if convenient (see Customizing Calc).

When you press C-x * , Emacs waits for you to press a second key to complete the command. In this case, you will follow C-x * with a letter (upper- or lower-case, it doesn’t matter for C-x * ) that says which Calc interface you want to use.

To get Calc’s standard interface, type C-x * c . To get Keypad mode, type C-x * k . Type C-x * ? to get a brief list of the available options, and type a second ? to get a complete list.

To ease typing, C-x * * also works to start Calc. It starts the same interface (either C-x * c or C-x * k ) that you last used, selecting the C-x * c interface by default.

If C-x * doesn’t work for you, you can always type explicit commands like M-x calc (for the standard user interface) or M-x calc-keypad (for Keypad mode). First type M-x (that’s Meta with the letter x ), then, at the prompt, type the full command (like calc-keypad ) and press Return.

The same commands (like C-x * c or C-x * * ) that start the Calculator also turn it off if it is already on.

1.5.2 The Standard Calc Interface

Calc’s standard interface acts like a traditional RPN calculator, operated by the normal Emacs keyboard. When you type 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.

... --**-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----- --%*- *Calc Trail*

In this figure, the mode-line for 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 stack window and the righthand one is called the 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 -5. (The ‘ > ’ symbol shows that this was the most recent calculation.) The net result is the two numbers 17.3 and -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 prefix keys that begin two-letter commands. For example, e means “enter exponent” and shifted E means ‘ e^x ’. With the d (“display modes”) prefix the letter “e” takes on very different meanings: d e means “engineering notation” and d E means “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 C-x o ( 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 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 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, C-x * c will give you a fresh stack and trail. There is a command ( 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 C-x * * the same as C-x * c .

The q key is another equivalent way to turn the Calculator off.

If you type C-x * b first and then C-x * c , you get a full-screen version of Calc ( 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 q or C-x * c again to quit, the file you were editing before reappears. The C-x * b key switches back and forth between “big” full-screen mode and the normal partial-screen mode.

Finally, C-x * o ( calc-other-window ) is like C-x * c except that the Calc window is not selected. The buffer you were editing before remains selected instead. If you are in a Calc window, then C-x * o will switch you out of it, being careful not to switch you to the Calc Trail window. So C-x * o is a handy way to switch out of Calc momentarily to edit your file; you can then type C-x * c to switch back into Calc when you are done.

1.5.3 Quick Mode (Overview)

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 C-x * q ( quick-calc ) in any regular editing buffer.

Quick mode is very simple: It prompts you to type any formula in standard algebraic notation (like ‘ 4 - 2/3 ’) and then displays the result at the bottom of the Emacs screen (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 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 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 C-x * c ) to change the mode settings.

See Quick Calculator, for further information.

1.5.4 Keypad Mode (Overview)

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 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.

|--- Emacs Calculator Mode --- |2: 17.3 |1: -5 | . |--%*-Calc: 12 Deg (Calcul |----+----+--Calc---+----+----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 | + | |-----+-----+-----+-----+-----+

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 1 7 . 3 ENTER 5 +/- ENTER ; to add them together you would then click + (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 C-x * b first, you get a full-screen Keypad mode ( full-calc-keypad ) with three windows: The keypad in the lower left, the stack in the lower right, and the trail on top.

See Keypad Mode, for further information.

1.5.5 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:

emacs -f full-calc

or

emacs -f full-calc-keypad

which run a full-screen Calculator (as if by C-x * b C-x * c ) or a full-screen X-based Calculator (as if by C-x * b C-x * k ). In standalone operation, quitting the Calculator (by pressing q or clicking on the keypad EXIT button) quits Emacs itself.

1.5.6 Embedded Mode (Overview)

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:

The derivative of ln(ln(x)) is

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, leaving a blank line before and after the formula:

The derivative of ln(ln(x)) is ln(ln(x))

Now, move the cursor onto this new formula and press 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 line with the formula will now appear as it would on the Calc stack (in this case, it will be left-aligned) and the buffer’s mode line will change to look like the Calc mode line (with mode indicators like ‘ 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 a d x RET .

The derivative of ln(ln(x)) is 1 / x ln(x)

(Note that by default, Calc gives division lower precedence than multiplication, so that ‘ 1 / x ln(x) ’ is equivalent to ‘ 1 / (x ln(x)) ’.)

To make this look nicer, you might want to press d = to center the formula, and even d B to use Big display mode.

The derivative of ln(ln(x)) is % [calc-mode: justify: center] % [calc-mode: language: big] 1 ------- x ln(x)

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 LaTeX. (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 d } (1) RET .

% [calc-mode: justify: center] % [calc-mode: language: big] % [calc-mode: right-label: " (1)"] 1 ------- (1) ln(x) x

To leave Embedded mode, type C-x * e again. The mode line and keyboard will revert to the way they were before.

The related command C-x * w operates on a single word, which generally means a single number, inside text. It searches for an expression which “looks” like a number containing the point. Here’s an example of its use (before you try this, remove the Calc annotations or use a new buffer so that the extra settings in the annotations don’t take effect):

A slope of one-third corresponds to an angle of 1 degrees.

Place the cursor on the ‘ 1 ’, then type C-x * w to enable Embedded mode on that number. Now type 3 / (to get one-third), and I T (the Inverse Tangent converts a slope into an angle), then C-x * w again to exit Embedded mode.

A slope of one-third corresponds to an angle of 18.4349488229 degrees.

See Embedded Mode, for full details.

1.5.7 Other C-x * Commands

Two more Calc-related commands are C-x * g and 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 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 v u if you want to unpack this vector into separate numbers on the stack. Also, C-u C-x * g interprets the region as a single number or formula.

The 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 C-x * y , which “yanks” the value at the top of the Calc stack back into an editing buffer. If you type C-x * y while in such a buffer, the value is yanked at the current position. If you type 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 C-x * commands. The shift, control, and meta keys are ignored for the keystroke following C-x * .

Commands for turning Calc on and off:

* Turn Calc on or off, employing the same user interface as last time. =, +, -, /, \, &, # Alternatives for * . 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. O Same as 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. B Control whether C-x * c and C-x * k use the full screen. Q Use Quick mode for a single short calculation. K Turn Calc Keypad mode on or off. E Turn Calc Embedded mode on or off at the current formula. J Turn Calc Embedded mode on or off, select the interesting part. W Turn Calc Embedded mode on or off at the current word (number). Z Turn Calc on in a user-defined way, as defined by a Z I command. X Quit Calc; turn off standard, Keypad, or Embedded mode if on. (This is like q or OFF inside of Calc.)

Commands for moving data into and out of the Calculator:

G Grab the region into the Calculator as a vector. R Grab the rectangular region into the Calculator as a matrix. : Grab the rectangular region and compute the sums of its columns. _ Grab the rectangular region and compute the sums of its rows. Y Yank a value from the Calculator into the current editing buffer.

Commands for use with Embedded mode:

A “Activate” the current buffer. Locate all formulas that contain ‘ := ’ or ‘ => ’ symbols and record their locations so that they can be updated automatically as variables are changed. D Duplicate the current formula immediately below and select the duplicate. F Insert a new formula at the current point. N Move the cursor to the next active formula in the buffer. P Move the cursor to the previous active formula in the buffer. U Update (i.e., as if by the = key) the formula at the current point. ` Edit (as if by calc-edit ) the formula at the current point.

Miscellaneous commands:

I Run the Emacs Info system to read the Calc manual. (This is the same as h i inside of Calc.) T Run the Emacs Info system to read the Calc Tutorial. S Run the Emacs Info system to read the Calc Summary. L Load Calc entirely into memory. (Normally the various parts are loaded only as they are needed.) M Read a region of written keystroke names (like C-n a b c RET ) and record them as the current keyboard macro. 0 (This is the “zero” digit key.) Reset the Calculator to its initial state: Empty stack, and initial mode settings.

1.6 History and Acknowledgments

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 ‘ 2^32 ’. I didn’t offhand, but I said, “that’s easy, just call up an xcalc .” Xcalc duly reported that the answer to our question was ‘ 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 would only comfortably fit six decimal digits or so (at the time)—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; François 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 calc-eval function; Juha Sarlin, who first worked out how to split Calc into quickly-loading parts; Bob Weiner, who helped immensely with the Lucid Emacs port; and Robert J. Chassell, who suggested the Calc Tutorial and exercises as well as many other things.

Among the books used in the development of Calc were Knuth’s Art of Computer Programming (especially volume II, Seminumerical Algorithms); Numerical Recipes by Press, Flannery, Teukolsky, and Vetterling; Bevington’s Data Reduction and Error Analysis for the Physical Sciences; Concrete Mathematics by Graham, Knuth, and Patashnik; Steele’s Common Lisp, the Language; the CRC Standard Math Tables (William H. Beyer, ed.); and Abramowitz and Stegun’s venerable Handbook of Mathematical Functions. Also, of course, Calc could not have been written without the excellent 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.

2 Tutorial

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 (see Starting Calc). If you are already familiar with advanced calculators, you may wish to skip on to the rest of this manual.

This tutorial describes the standard user interface of Calc only. The Quick mode and Keypad mode interfaces are fairly self-explanatory. See Embedded Mode, for a description of the Embedded mode interface.

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. Press C-x * t to set this up; the on-line tutorial will be opened in the current window and Calc will be started in another window. From the Info window, the command C-x * c can be used to switch to the Calc window and C-x * o can be used to switch back to the Info window. (If you have a printed copy of the manual you can use that instead; in that case you only need to press C-x * c to start Calc.)

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.

You may wish to print out a copy of the Calc Summary and keep notes on it as you learn Calc. See About This Manual, to see how to make a printed summary. See Summary.

2.1 Basic Tutorial

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.

• 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.

2.1.1 RPN Calculations and the Stack

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.)

The central component of an RPN calculator is the 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.

In an operation like ‘ 2+3 ’, the 2 and 3 are called the operands and the ‘ + ’ is the operator. In an RPN calculator you always enter the operands first, then the operator. Each time you type a number, Calc adds or pushes it onto the top of the Stack. When you press an operator key like + , Calc 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: 2 RET 3 RET + . (The RET key, Return, corresponds to the ENTER key on traditional RPN calculators.) Try this now if you wish; type C-x * c to switch into the Calc window (you can type C-x * c again or C-x * o to switch back to the Tutorial window). The first four keystrokes “push” the numbers 2 and 3 onto the stack. The + 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:

. 1: 2 2: 2 1: 5 . . 1: 3 . . C-x * c 2 RET 3 RET + DEL

The ‘ . ’ 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.

The numbers ‘ 1: ’ and ‘ 2: ’ on the left are stack level numbers. Old RPN calculators always had four stack levels called ‘ x ’, ‘ y ’, ‘ z ’, and ‘ 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 + always work on the top few levels of 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 ‘ . ’ 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 ‘ . ’ marker upwards through the stack, temporarily “hiding” some numbers from commands like + . This is called stack truncation and we will not cover it in this tutorial; see Truncating the Stack, if you are interested.

You don’t really need the second RET in 2 RET 3 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 2 RET 3 + will work just as well.

Examples in this tutorial will often omit RET even when the stack displays shown would only happen if you did press RET :

1: 2 2: 2 1: 5 . 1: 3 . . 2 RET 3 +

Here, after pressing 3 the stack would really show ‘ 1: 2 ’ with ‘ Calc: 3 ’ in the minibuffer. In these situations, you can press the optional RET to see the stack as the figure shows.

(•) 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 f and the exercise number to go to the answer, then the letter l to return to where you were.)

Here’s the first exercise: What will the keystrokes 1 RET 2 RET 3 RET 4 + * - compute? (‘ * ’ is the symbol for multiplication.) Figure it out by hand, then try it with Calc to see if you’re right. See 1. (•)

(•) Exercise 2. Compute ‘ 2*4 + 7*9.5 + 5/4 ’ using the stack. See 2. (•)

The 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 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 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 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 - key is also an operator (it subtracts the top two stack elements), how does one enter a negative number? Calc uses the _ (underscore) key to act like the minus sign in a number. So, typing -5 RET won’t work because the - key will try to do a subtraction, but _5 RET works just fine.

You can also press 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: 5 n RET .

If you press RET when you’re not entering a number, the effect is to duplicate the top number on the stack. Consider this calculation:

1: 3 2: 3 1: 9 2: 9 1: 81 . 1: 3 . 1: 9 . . . 3 RET RET * RET *

(Of course, an easier way to do this would be 3 RET 4 ^ , to raise 3 to the fourth power.)

The space-bar key (denoted SPC here) performs the same function as RET ; you could replace all three occurrences of RET in the above example with SPC and the effect would be the same.

Another stack manipulation key is TAB . This exchanges the top two stack entries. Suppose you have computed 2 RET 3 + to get 5, and then you realize what you really wanted to compute was ‘ 20 / (2+3) ’.

1: 5 2: 5 2: 20 1: 4 . 1: 20 1: 5 . . . 2 RET 3 + 20 TAB /

Planning ahead, the calculation would have gone like this:

1: 20 2: 20 3: 20 2: 20 1: 4 . 1: 2 2: 2 1: 5 . . 1: 3 . . 20 RET 2 RET 3 + /

A related stack command is M-TAB (hold META and type TAB ). It rotates the top three elements of the stack upward, bringing the object in level 3 to the top.

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 RET 20 RET 30 RET M- TAB M- TAB

(•) 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. See 3. (•)

Operations like + , - , * , / , and ^ pop two arguments from the stack and push a result. Operations like n and 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.

1: 3 1: 9 2: 9 1: 25 1: 5 . . 1: 16 . . . 3 RET RET * 4 RET RET * + Q

(Note that capital Q means to hold down the Shift key while typing q . Remember, plain unshifted q is the Quit command.)

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 f h , but let’s suppose we can’t remember the necessary keystrokes. We can still enter it by its full name using M-x notation:

1: 3 2: 3 1: 5 . 1: 4 . . 3 RET 4 RET M-x calc-hypot

All Calculator commands begin with the word ‘ calc- ’. Since it gets tiring to type this, Calc provides an x key which is just like the regular Emacs M-x key except that it types the ‘ calc- ’ prefix for you:

1: 3 2: 3 1: 5 . 1: 4 . . 3 RET 4 RET x hypot

What happens if you take the square root of a negative number?

1: 4 1: -4 1: (0, 2) . . . 4 RET n Q

The notation ‘ (a, b) ’ represents a complex number. Complex numbers are more traditionally written ‘ a + b i ’; Calc can display in this format, too, but for now we’ll stick to the ‘ (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 ( and , and ) keys manipulate “incomplete complex numbers.”

1: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3) . 1: 2 . 3 . . . ( 2 , 3 )

You can perform calculations while entering parts of incomplete objects. However, an incomplete object cannot actually participate in a calculation:

1: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ... . 1: 2 2: 2 5 5 . 1: 3 . . . (error) ( 2 RET 3 + +

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.

2: 2 3: 2 3: 3 1: ( ... 1: (2, 3) 1: 3 2: 3 2: ( ... 2 . . 1: ( ... 1: 2 3 . . . 2 RET 3 RET ( M- TAB M- TAB )

Note that the , (comma) key did not have to be used here. When you press ) 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.

(•) Exercise 4. To enter the complex number ‘ (2, 3) ’, your friend Joe typed ( 2 , 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.) See 4. (•)

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 numeric prefix argument by typing a series of META -digits beforehand. If META is awkward for you, you can instead type C-u followed by the necessary digits. Numeric prefix arguments can be negative, as in M-- M-3 M-5 or C-u - 3 5 . Calc commands use numeric prefix arguments in a variety of ways. For example, a numeric prefix on the + operator adds any number of stack entries at once:

1: 10 2: 10 3: 10 3: 10 1: 60 . 1: 20 2: 20 2: 20 . . 1: 30 1: 30 . . 10 RET 20 RET 30 RET C-u 3 +

For stack manipulation commands like RET , a positive numeric prefix argument operates on the top n stack entries at once. A negative argument operates on the entry in level n only. An argument of zero operates on the entire stack. In this example, we copy the second-to-top element of the stack:

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 RET 20 RET 30 RET C-u -2 RET

Another common idiom is M-0 DEL , which clears the stack. (The M-0 numeric prefix tells DEL to operate on the entire stack.)

2.1.2 Algebraic-Style Calculations

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 ‘ 2+3 ’ notation.

Notice: Calc gives ‘ / ’ lower precedence than ‘ * ’, so that ‘ a/b*c ’ is interpreted as ‘ a/(b*c) ’; this is not standard across all computer languages. 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 ( ' ) key. Answer the prompt with the desired formula, then press 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 DEL to delete it from the stack.

Try pressing the apostrophe key, then 2+3+4 , then RET . The result should be the number 9.

Algebraic formulas use the operators ‘ + ’, ‘ - ’, ‘ * ’, ‘ / ’, and ‘ ^ ’. You can use parentheses to make the order of evaluation clear. In the absence of parentheses, ‘ ^ ’ is evaluated first, then ‘ * ’, then ‘ / ’, then finally ‘ + ’ and ‘ - ’. For example, the expression

2 + 3*4*5 / 6*7^8 - 9

is equivalent to

2 + ((3*4*5) / (6*(7^8))) - 9

or, in large mathematical notation,

3 * 4 * 5 2 + --------- - 9 8 6 * 7

The result of this expression will be the number -6.99999826533.

Calc’s order of evaluation is the same as for most computer languages, except that ‘ * ’ binds more strongly than ‘ / ’, as the above example shows. As in normal mathematical notation, the ‘ * ’ symbol can often be omitted: ‘ 2 a ’ is the same as ‘ 2*a ’.

Operators at the same level are evaluated from left to right, except that ‘ ^ ’ is evaluated from right to left. Thus, ‘ 2-3-4 ’ is equivalent to ‘ (2-3)-4 ’ or -5, whereas ‘ 2^3^4 ’ is equivalent to ‘ 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 m a . (An ‘ Alg ’ indicator should appear in the Calc window’s mode line.)

Press m a , then 2+3+4 with no apostrophe, then 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 _ key), or if you press ( or [ , Calc automatically begins an algebraic entry.

Functions which do not have operator symbols like ‘ + ’ and ‘ * ’ must be entered in formulas using function-call notation. For example, the function name corresponding to the square-root key Q is sqrt . To compute a square root in a formula, you would use the notation ‘ sqrt( x ) ’.

Press the apostrophe, then type sqrt(5*2) - 3 . The result should be ‘ 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 arcsin out of the blue, the a r will be taken as an Algebraic Rewrite command, and the 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:

1: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1) . 1: (1, -2) . 1: 1 . . . (2,3) RET (1,-2) RET * 1 RET +

Algebraic mode allows us to enter complex numbers without pressing an apostrophe first, but it also means we need to press RET after every entry, even for a simple number like ‘ 1 ’.

(You can type C-u m a to enable a special Incomplete Algebraic mode in which the ( and [ keys use algebraic entry even though regular numeric keys still use RPN numeric entry. There is also Total Algebraic mode, started by typing m t , in which all normal keys begin algebraic entry. You must then use the META key to type Calc commands: M-m t to get back out of Total Algebraic mode, M-q to quit, etc.)

If you’re still in Algebraic mode, press 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 + and * ) use algebraic form, but operators of one number (like n and 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 $ sign to tie them together. In an algebraic formula, $ represents the number on the top of the stack. Here, we perform the calculation ‘ sqrt(2*4+1) ’, which on a traditional calculator would be done by pressing 2 * 4 + 1 = and then the square-root key.

1: 8 1: 9 1: 3 . . . ' 2*4 RET $+1 RET Q

Notice that we didn’t need to press an apostrophe for the $+1 , because the dollar sign always begins an algebraic entry.

(•) Exercise 1. How could you get the same effect as pressing Q but using an algebraic entry instead? How about if the Q key on your keyboard were broken? See 1. (•)

The notations $$ , $$$ , and so on stand for higher stack entries. For example, ' $$+$ RET is just like typing + .

Algebraic formulas can include variables. To store in a variable, press s s , then type the variable name, then press RET . (There are actually two flavors of store command: s s stores a number in a variable but also leaves the number on the stack, while 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.

1: 17 . 1: a + a^2 1: 306 . . . 17 s t a RET ' a+a^2 RET =

The = key 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 = , or by using the s r command.

1: 17 2: 17 3: 17 2: 17 1: 306 . 1: 17 2: 17 1: 289 . . 1: 2 . . s r a RET ' a RET = 2 ^ +

If you press a single digit for a variable name (as in s t 3 , you get one of ten quick variables q0 through q9 . They are “quick” simply because you don’t have to type the letter q or the RET after their names. In fact, you can type simply s 3 as a shorthand for s s 3 , and likewise for t 3 and r 3 .

Any variables in an algebraic formula for which you have not stored values are left alone, even when you evaluate the formula.

1: 2 a + 2 b 1: 2 b + 34 . . ' 2a+2b RET =

Calls to function names which are undefined in Calc are also left alone, as are calls for which the value is undefined.

1: log10(0) + log10(x) + log10(5, 6) + foo(3) + 2 . ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) RET

In this example, the first call to 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 foo . You will see a “Wrong number of arguments” message referring to ‘ log10(5,6) ’. Press the 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: 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: x ” will only show up if you explicitly press the w key.

(•) Exercise 2. Joe entered the formula ‘ 2 x y ’, stored 5 in x , pressed = , and got the expected result, ‘ 10 y ’. He then tried the same for the formula ‘ 2 x (1+y) ’, expecting ‘ 10 (1+y) ’, but it didn’t work. Why not? See 2. (•)

(•) Exercise 3. What result would you expect 1 RET 0 / to give? What if you then type 0 * ? See 3. (•)

One interesting way to work with variables is to use the evaluates-to (‘ => ’) operator. It works like this: Enter a formula algebraically in the usual way, but follow the formula with an ‘ => ’ symbol. (There is also an s = command which builds an ‘ => ’ formula using the stack.) On the stack, you will see two copies of the formula with an ‘ => ’ between them. The lefthand formula is exactly like you typed it; the righthand formula has been evaluated as if by typing = .

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 => RET ' 2a+2b RET s = 10 s t a RET

Notice that the instant we stored a new value in a , all ‘ => ’ operators already on the stack that referred to ‘ a ’ were updated to use the new value. With ‘ => ’, 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:

2: 2 + 3 => 5 1: 2 a + 2 b => 2 a + 2 b . s u a RET

We will encounter formulas involving variables and functions again when we discuss the algebra and calculus features of the Calculator.

2.1.3 Undo and Redo

If you make a mistake, you can usually correct it by pressing shift- U , the “undo” command. First, clear the stack ( M-0 DEL ) and exit and restart Calc ( C-x * * C-x * * ) to make sure things start off with a clean slate. Now:

1: 2 2: 2 1: 8 2: 2 1: 6 . 1: 3 . 1: 3 . . . 2 RET 3 ^ U *

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:

1: 6 2: 2 1: 2 . . . 1: 3 . . (error) U U U U

You can also type D to “redo” a command that you have undone mistakenly.

. 1: 2 2: 2 1: 6 1: 6 . 1: 3 . . . (error) D D D D

It was not possible to redo past the ‘ 6 ’, since that was placed there by something other than an undo command.

You can think of undo and redo as a sort of “time machine.” Press U to go backward in time, D to go forward. If you go backward and do something (like * ) 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 ‘ 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 t d now to turn it on.

Let’s try grabbing an earlier result. The ‘ 8 ’ we computed was undone by a U command, and was lost even to Redo when we pressed * , but it’s still there in the trail. There should be a little ‘ > ’ arrow (the trail pointer) resting on the last trail entry. If there isn’t, press t ] to reset the trail pointer. Now, press t p to move the arrow onto the line containing ‘ 8 ’, and press t y to “yank” that number back onto the stack.

If you press 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 ‘ 2^3^4 ’. We don’t remember what it was, but the first digits were “241”. Press t r (which stands for trail-search-reverse), then type 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 C-s or C-r to continue the search forwards or backwards as you like.

To finish the search, press RET . This halts the incremental search and leaves the trail pointer at the thing we found. Now we can type t y to yank that number onto the stack. If we hadn’t remembered the “241”, we could simply have searched for 2^3^4 , then pressed 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 t . (The store-and-recall commands, on the other hand, all began with 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 prefix key. If you type a prefix key by accident, you can press C-g to cancel it. (In fact, you can press C-g to cancel almost anything in Emacs.) To get help on a prefix key, press that key followed by ? . Some prefixes have several lines of help, so you need to press ? repeatedly to see them all. You can also type h h to see all the help at once.

Try pressing t ? now. You will see a line of the form,

trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-

The word “trail” indicates that the 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 t n , t p , t ] , and t y so far. The ‘ [MORE] ’ means you can press ? again to see more 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 y for example, it will be interpreted as a t y command. If all you wanted was to look at the help messages, press 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 ` (grave accent) to edit a stack entry.

Try entering ‘ 3.141439 ’ now. If this is supposed to represent ‘ pi ’, it’s got several errors. Press ` 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 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 ` key also works during entry of a number or algebraic formula.

2.1.4 Mode-Setting Commands

Calc has many types of 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 precision. Notice the ‘ 12 ’ on the Calc window’s mode line:

--%*-Calc: 12 Deg (Calculator)----All------

Most of the symbols there are Emacs things you don’t need to worry about, but the ‘ 12 ’ and the ‘ Deg ’ are mode indicators. The ‘ 12 ’ means that calculations should always be carried to 12 significant figures. That is why, when we type 1 RET 7 / , we get ‘ 0.142857142857 ’ with exactly 12 digits, not counting leading and trailing zeros.

You can set the precision to anything you like by pressing p , then entering a suitable number. Try pressing p 30 RET , then doing 1 RET 7 / again:

1: 0.142857142857 2: 0.142857142857142857142857142857 .

Although the precision can be set arbitrarily high, Calc always has to have some value for the current precision. After all, the true value ‘ 1/7 ’ is an infinitely repeating decimal; Calc has to stop somewhere.

Of course, calculations are slower the more digits you request. Press 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 ‘ 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 RET to duplicate the number, then 1 + . Notice that the RET key didn’t round the number, because it doesn’t do any calculation. But the instant we pressed + , the number was rounded down.

1: 0.142857142857 2: 0.142857142857142857142857142857 3: 1.14285714286 .

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 ‘ 1/7 ’.

How did we get more than 12 digits when we computed ‘ 2^3^4 ’? The answer is that Calc makes a distinction between integers and floating-point numbers, or 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 ‘ 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 ‘ 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 F ( calc-floor ) command to convert a floating-point value to an integer, and c f ( calc-float ) to convert an integer to floating-point form.

Let’s try entering that last calculation:

1: 2. 2: 2. 1: 1.99506311689e3010 . 1: 10000 . . 2.0 RET 10000 RET ^

Notice the letter ‘ 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.

1: 2. 2: 2. 1: 1.99506311678e3010 . 1: 10000. . . 2.0 RET 1e4 RET ^

Hey, the answer is different! Look closely at the middle columns of the two examples. In the first, the stack contained the exact integer ‘ 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:

. 1: 2. 2: 2. 1: 1.995063116880828e3010 . 1: 10000. . . p 16 RET 2. RET 1e4 ^ p 12 RET

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… Integer powers were more accurate; in fact, the result was only off by one unit in the last place.

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 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 float format. Calc supports four major formats for floating-point numbers, called normal, fixed-point, scientific notation, and engineering notation. You get them by pressing d n , d f , d s , and 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 M-0 DEL to clear the stack, then enter the four numbers shown here:

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

Notice that when we typed M-3 d n , the numbers were rounded down to three significant digits, but then when we typed 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- 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.

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 DEL U TAB d SPC d n

Here the 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 d SPC command refreshes the whole stack. The d n command changes back to the normal float format; since it doesn’t have an H prefix, it also updates all the stack entries to be in d n format.

Notice that the integer ‘ 12345 ’ was not affected by any of the float formats. Integers are integers, and are always displayed exactly.

Large integers have their own problems. Let’s look back at the result of 2^3^4 .

2417851639229258349412352

Quick—how many digits does this have? Try typing d g :

2,417,851,639,229,258,349,412,352

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 M-5 d g :

24178,51639,22925,83494,12352

Let’s see what happens to floating-point numbers when they are grouped. First, type p 25 RET to make sure we have enough precision to get ourselves into trouble. Now, type 1e13 / :

24,17851,63922.9258349412352

The integer part is grouped but the fractional part isn’t. Now try M-- M-5 d g (that’s meta-minus-sign, meta-five):

24,17851,63922.92583,49412,352

If you find it hard to tell the decimal point from the commas, try changing the grouping character to a space with d , SPC :

24 17851 63922.92583 49412 352

Type d , , to restore the normal grouping character, then d g again to turn grouping off. Also, press p 12 to restore the default precision.

Press U enough times to get the original big integer back. (Notice that 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 d r 16 RET :

16#200000000000000000000

The number is now displayed in 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 d r 2 RET to see it in actual binary form:

2#1000000000000000000000000000000000000000000000000000000 …

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 < and > to scroll the stack window left and right by half its width. Another way to view something large is to press ` (grave accent) to edit the top of stack in a separate window. (Press C-c C-c when you are done.)

You can enter non-decimal numbers using the # symbol, too. Let’s see what the hexadecimal number ‘ 5FE ’ looks like in binary. Type 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 d g :

2#101,1111,1110

Notice that 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 d r 10 :

1,534

Numbers are not 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 d r . The current radix applies to integers, fractions, and floats.

(•) Exercise 1. Your friend Joe tried to enter one-third as ‘ 3#0.1 ’ in d r 3 mode with a precision of 12. He got ‘ 3#0.0222222... ’ (with 25 2’s) in the display. When he multiplied that by three, he got ‘ 3#0.222222... ’ instead of the expected ‘ 3#1 ’. Next, Joe entered ‘ 3#0.2 ’ and, to his great relief, saw ‘ 3#0.2 ’ on the screen. But when he typed 2 / , he got ‘ 3#0.10000001 ’ (some zeros omitted). What’s going on here? See 1. (•)

(•) 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 ‘ 8#1.23e3 = 8#1230.0 ’. Suppose we have the hexadecimal number ‘ f.e8f ’ times 16 to the 15th power: We write ‘ 16#f.e8fe15 ’. What is wrong with this picture? What could we write instead that would work better? See 2. (•)

The m prefix key has another set of modes, relating to the way Calc interprets your inputs and does computations. Whereas d -prefix modes generally affect the way things look, m -prefix modes affect the way they are actually computed.

The most popular m -prefix mode is the angular mode. Notice the ‘ 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,

1: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5 . . . . 45 S 2 ^ c 1

The shift- S command computes the sine of an angle. The sine of 45 degrees is ‘ sqrt(2)/2 ’; squaring this yields ‘ 2/4 = 0.5 ’. However, there has been a slight roundoff error because the representation of ‘ sqrt(2)/2 ’ wasn’t exact. The 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.

(•) 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? See 3. (•)

To do this calculation in radians, we would type m r first. (The indicator changes to ‘ Rad ’.) 45 degrees corresponds to ‘ pi/4 ’ radians. To get ‘ pi ’, press the P key. (Once again, this is a shifted capital P . Remember, unshifted p sets the precision.)

1: 3.14159265359 1: 0.785398163398 1: 0.707106781187 . . . P 4 / m r S

Likewise, inverse trigonometric functions generate results in either radians or degrees, depending on the current angular mode.

1: 0.707106781187 1: 0.785398163398 1: 45. . . . .5 Q m r I S m d U I S

Here we compute the Inverse Sine of ‘ sqrt(0.5) ’, first in radians, then in degrees.

Use c d and c r to convert a number from radians to degrees and vice-versa.

1: 45 1: 0.785398163397 1: 45. . . . 45 c r c d

Another interesting mode is 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.

2: 12 1: 1.33333333333 1: 4:3 1: 9 . . . 12 RET 9 / m f U / m f

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 : notation. (Calc uses : instead of / as the fraction separator because / 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.

(•) Exercise 4. If fractional arithmetic is exact, why would you ever use floating-point numbers instead? See 4. (•)

Typing 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 m f to recompute for you.

1: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3 . . . ' 12/9 => RET p 4 RET m f

In this example, the righthand side of the ‘ => ’ operator on the stack is recomputed when we change the precision, then again when we change to Fraction mode. All ‘ => ’ expressions on the stack are recomputed every time you change any mode that might affect their values.

2.2 Arithmetic Tutorial

In this section, we explore the arithmetic and scientific functions available in the Calculator.

The standard arithmetic commands are + , - , * , / , and ^ . Each normally takes two numbers from the top of the stack and pushes back a result. The n and & keys perform change-sign and reciprocal operations, respectively.

1: 5 1: 0.2 1: 5. 1: -5. 1: 5. . . . . . 5 & & n n

You can apply a “binary operator” like + 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.

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 RET 3 RET 4 M-3 + U 10 M-- M-3 +

You can apply a “unary operator” like & to the top n stack entries with a numeric prefix, too.

3: 2 3: 0.5 3: 0.5 2: 3 2: 0.333333333333 2: 3. 1: 4 1: 0.25 1: 4. . . . 2 RET 3 RET 4 M-3 & M-2 &

Notice that the results here are left in floating-point form. We can convert them back to integers by pressing F , the “floor” function. This function rounds down to the next lower integer. There is also R , which rounds to the nearest integer.

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

Since dividing-and-flooring (i.e., “integer quotient”) is such a common operation, Calc provides a special command for that purpose, the backslash \ . Another common arithmetic operator is % , which computes the remainder that would arise from a \ operation, i.e., the “modulo” of two numbers. For example,

2: 1234 1: 12 2: 1234 1: 34 1: 100 . 1: 100 . . . 1234 RET 100 \ U %

These commands actually work for any real numbers, not just integers.

2: 3.1415 1: 3 2: 3.1415 1: 0.1415 1: 1 . 1: 1 . . . 3.1415 RET 1 \ U %

(•) Exercise 1. The \ command would appear to be a frill, since you could always do the same thing with / F . Think of a situation where this is not true— / F would be inadequate. Now think of a way you could get around the problem if Calc didn’t provide a \ command. See 1. (•)

We’ve already seen the Q (square root) and S (sine) commands. Other commands along those lines are C (cosine), T (tangent), E (‘ e^x ’) and L (natural logarithm). These can be modified by the I (inverse) and H (hyperbolic) prefix keys.

Let’s compute the sine and cosine of an angle, and verify the identity ‘ sin(x)^2 + cos(x)^2 = 1 ’. We’ll arbitrarily pick -64 degrees as a good value for ‘ x ’. With the angular mode set to degrees (type m d ), do:

2: -64 2: -64 2: -0.89879 2: -0.89879 1: 1. 1: -64 1: -0.89879 1: -64 1: 0.43837 . . . . . 64 n RET RET S TAB C f h

(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, f h is the calc-hypot , or square-root of sum of squares, command.

Another identity is ‘ tan(x) = sin(x) / cos(x) ’.

2: -0.89879 1: -2.0503 1: -64. 1: 0.43837 . . . U / I T

A physical interpretation of this calculation is that if you move ‘ 0.89879 ’ units downward and ‘ 0.43837 ’ units to the right, your direction of motion is -64 degrees from horizontal. Suppose we move in the opposite direction, up and to the left:

2: -0.89879 2: 0.89879 1: -2.0503 1: -64. 1: 0.43837 1: -0.43837 . . . . U U M-2 n / I T

How can the angle be the same? The answer is that the / 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 f T [ 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.

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- RET M-2 n f T -

The resulting angles differ by 180 degrees; in other words, they point in opposite directions, just as we would expect.

The META - 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 M-2 RET to duplicate the top two stack elements right after the U U , then a pair of M-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 difference ‘ cosh(x)^2 - sinh(x)^2 ’ that always equals one. Let’s try to verify this identity.

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 RET RET H C 2 ^ TAB H S 2 ^

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 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 ‘ x ’!

Some Calculator commands use the Hyperbolic prefix for other purposes. The logarithm and exponential functions, for example, work to the base ‘ e ’ normally but use base-10 instead if you use the Hyperbolic prefix.

1: 1000 1: 6.9077 1: 1000 1: 3 . . . . 1000 L U H L

First, we mistakenly compute a natural logarithm. Then we undo and compute a common logarithm instead.

The B key computes a general base- b logarithm for any value of b .

2: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077 1: 10 . . 1: 2.71828 . . . 1000 RET 10 B H E H P B

Here we first use B to compute the base-10 logarithm, then use the “hyperbolic” exponential as a cheap hack to recover the number 1000, then use B again to compute the natural logarithm. Note that P with the hyperbolic prefix pushes the constant ‘ 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 H E , the result was a floating-point number for no apparent reason. In fact, if we had computed 10 RET 3 ^ we would have gotten an exact integer 1000. But the H E command is rigged to generate a floating-point result all of the time so that 1000 H E will not waste time computing a thousand-digit integer when all you probably wanted was ‘ 1e1000 ’.

(•) Exercise 2. Find a pair of integer inputs to the B command for which Calc could find an exact rational result but doesn’t. See 2. (•)

The Calculator also has a set of functions relating to combinatorics and statistics. You may be familiar with the factorial function, which computes the product of all the integers up to a given number.

1: 100 1: 93326215443... 1: 100. 1: 9.3326e157 . . . . 100 ! U c f !

Recall, the 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 ! 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 ‘ gamma(n) ’ (which is itself available as the f g command).

3: 4. 3: 24. 1: 5.5 1: 52.342777847 2: 4.5 2: 52.3427777847 . . 1: 5. 1: 120. . . M-3 ! M-0 DEL 5.5 f g

Here we verify the identity ‘ n ! = gamma( n +1) ’.

The binomial coefficient n -choose- m is defined by ‘ n! / m! (n-m)! ’ for all reals ‘ n ’ and ‘ m ’. The intermediate results in this formula can become quite large even if the final result is small; the k c command computes a binomial coefficient in a way that avoids large intermediate values.

The 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.

2: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29] 1: 20 . . . 30 RET 20 k c k f

You can verify these prime factors by using V R * to multiply together the elements of this vector. The result is the original number, 30045015.

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:

1: 10000 1: 10007 1: 9973 . . . 10000 k n I k n

Just for kicks we’ve also computed the next prime less than 10000.

See Financial Functions, for a description of the Calculator commands that deal with business and financial calculations (functions like pv , rate , and sln ).

See Binary Functions, to read about the commands for operating on binary numbers (like and , xor , and lsh ).

2.3 Vector/Matrix Tutorial

A 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.

2.3.1 Vector Analysis

If you add two vectors, the result is a vector of the sums of the elements, taken pairwise.

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 +

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 s 1 and 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 dot product of the vectors.

2: [1, 2, 3] 1: 19 1: [7, 6, 0] . . r 1 r 2 *

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 ‘ (0,0,0) ’ to the specified point in three-dimensional space.) The A (absolute value) command can be used to compute the length of a vector.

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- RET M-2 A * / I C

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.

The 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.

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- RET M-2 A * / A I S

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!

Vector-related commands generally begin with the v prefix key. Some are uppercase letters and some are lowercase. To make it easier to type these commands, the shift- V prefix key acts the same as the v key. (See 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:

2: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0 1: [-18, 21, -8] . 1: [-18, 21, -8] . . . r 1 r 3 * DEL r 2 r 3 *

(•) Exercise 1. Given a vector on the top of the stack, what keystrokes would you use to normalize the vector, i.e., to reduce its length to one without changing its direction? See 1. (•)

(•) 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. See 2. (•)

2.3.2 Matrices

A 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:

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] RET

We’ll be using this matrix again, so type 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 ‘ i ’, column ‘ j ’ of the result is effectively the dot product of row ‘ i ’ of the left matrix by column ‘ 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:

1: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] . RET *

Though rather hard to read, this is a formula which shows the product of two matrices. The ‘ * ’ function, having invalid arguments, has been left in symbolic form.

We can multiply the matrices if we transpose one of them first.

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 TAB *

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.

2: [ [ 1, 2, 3 ] 1: [14, 32] [ 4, 5, 6 ] ] . 1: [1, 2, 3] . r 4 r 1 *

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.

(•) Exercise 1. Use ‘ * ’ to sum along the rows of the above 2x3 matrix to get ‘ [6, 15] ’. Now use ‘ * ’ to sum along the columns to get ‘ [5, 7, 9] ’. See 1. (•)

An 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.

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 RET *

If a matrix is square, it is often possible to find its inverse, that is, a matrix which, when multiplied by the original matrix, yields an identity matrix. The & (reciprocal) key also computes the inverse of a matrix.

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 &

The vertical bar | 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.

1: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ] [ 0., 1., 0. ] [ 0., 1., 0. ] [ 0., 0., 1. ] ] [ 0., 0., 1. ] ] . . M- RET * U TAB *

Matrix inverses are related to systems of linear equations in algebra. Suppose we had the following set of equations:

a + 2b + 3c = 6 4a + 5b + 6c = 2 7a + 6b = 3

This can be cast into the matrix equation,

[ [ 1, 2, 3 ] [ [ a ] [ [ 6 ] [ 4, 5, 6 ] * [ b ] = [ 2 ] [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]

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:

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 /

The result is the ‘ [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:

2: [ [ 1, 2, 3 ] 1: [6., 2., 3.] [ 4, 5, 6 ] . [ 7, 6, 0 ] ] 1: [-12.6, 15.2, -3.93333] . r 5 TAB *

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 Nx1 or 1xN matrices instead. In this case, you would enter the original column vector as ‘ [[6], [2], [3]] ’ or ‘ [6; 2; 3] ’.

(•) Exercise 2. Algebraic entry allows you to make vectors and matrices that include variables. Solve the following system of equations to get expressions for ‘ x ’ and ‘ y ’ in terms of ‘ a ’ and ‘ b ’.

x + a y = 6 x + b y = 10

See 2. (•)

(•) 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 ‘ A X = B ’ directly because the matrix ‘ 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 ‘ A ’: ‘ trn(A)*A*X = trn(A)*B ’. Now ‘ trn(A)*A ’ is a square matrix so a solution is possible. It turns out that the ‘ 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:

a + 2b + 3c = 6 4a + 5b + 6c = 2 7a + 6b = 3 2a + 4b + 6c = 11

See 3. (•)

2.3.3 Vectors as 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 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:

3: 10 1: [10, 20, 30] 3: 10 2: 20 . 2: 20 1: 30 1: 30 . . M-3 v p v u

You can also build vectors out of consecutive integers, or out of many copies of a given value:

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 RET 17 v b 4 RET

You can apply an operator to every element of a vector using the map command.

1: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68] . . . V M * 2 V M ^ V M Q

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.

(•) Exercise 1. Compute a vector of powers of two from ‘ 2^-4 ’ to ‘ 2^4 ’. See 1. (•)

You can also reduce a binary operator across a vector. For example, reducing ‘ * ’ computes the product of all the elements in the vector:

1: 123123 1: [3, 7, 11, 13, 41] 1: 123123 . . . 123123 k f V R *

In this example, we decompose 123123 into its prime factors, then multiply those factors together again to yield the original number.

We could compute a dot product “by hand” using mapping and reduction:

2: [1, 2, 3] 1: [7, 12, 0] 1: 19 1: [7, 6, 0] . . . r 1 r 2 V M * V R +

Recalling two vectors from the previous section, we compute the sum of pairwise products of the elements to get the same answer for the dot product as before.

A slight variant of vector reduction is the accumulate operation, V U . This produces a vector of the intermediate results from a corresponding reduction. Here we compute a table of factorials:

1: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720] . . v x 6 RET V U *

Calc allows vectors to grow as large as you like, although it gets rather slow if vectors have more than about a hundred elements. Actually, most of the time is spent formatting these large vectors for display, not calculating on them. Try the following experiment (if your computer is very fast you may need to substitute a larger vector size).

1: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ... . . v x 500 RET 1 V M +

Now press v . (the letter v , then a period) and try the experiment again. In v . mode, long vectors are displayed “abbreviated” like this:

1: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501] . . v x 500 RET 1 V M +

(where now the ‘ ... ’ is actually part of the Calc display). You will find both operations are now much faster. But notice that even in v . mode, the full vectors are still shown in the Trail. Type t . to cause the trail to abbreviate as well, and try the experiment one more time. Operations on long vectors are now quite fast! (But of course if you use t . you will lose the ability to get old vectors back using the t y command.)

An easy way to view a full vector when v . mode is active is to press ` (grave accent) to edit the vector; editing always works with the full, unabbreviated value.

As a larger example, let’s try to fit a straight line to some data, using the method of least squares. (Calc has a built-in command for least-squares curve fitting, but we’ll do it by hand here just to practice working with vectors.) Suppose we have the following list of values in a file we have loaded into Emacs:

x y --- --- 1.34 0.234 1.41 0.298 1.49 0.402 1.56 0.412 1.64 0.466 1.73 0.473 1.82 0.601 1.91 0.519 2.01 0.603 2.11 0.637 2.22 0.645 2.33 0.705 2.45 0.917 2.58 1.009 2.71 0.971 2.85 1.062 3.00 1.148 3.15 1.157 3.32 1.354

If you are reading this tutorial in printed form, you will find it easiest to press C-x * i to enter the on-line Info version of the manual and find this table there. (Press g , then type List Tutorial , to jump straight to this section.)

Position the cursor at the upper-left corner of this table, just to the left of the ‘ 1.34 ’. Press C-@ to set the mark. (On your system this may be C-2 , C-SPC , or NUL .) Now position the cursor to the lower-right, just after the ‘ 1.354 ’. You have now defined this region as an Emacs “rectangle.” Still in the Info buffer, type C-x * r . This command ( calc-grab-rectangle ) will pop you back into the Calculator, with the contents of the rectangle you specified in the form of a matrix.

1: [ [ 1.34, 0.234 ] [ 1.41, 0.298 ] …

(You may wish to use v . mode to abbreviate the display of this large matrix.)

We want to treat this as a pair of lists. The first step is to transpose this matrix into a pair of rows. Remember, a matrix is just a vector of vectors. So we can unpack the matrix into a pair of row vectors on the stack.

1: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ] [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ] . . v t v u

Let’s store these in quick variables 1 and 2, respectively.

1: [1.34, 1.41, 1.49, ... ] . . t 2 t 1

(Recall that t 2 is a variant of s 2 that removes the stored value from the stack.)

In a least squares fit, the slope ‘ m ’ is given by the formula

m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)

where ‘ sum(x) ’ represents the sum of all the values of ‘ x ’. While there is an actual sum function in Calc, it’s easier to sum a vector using a simple reduction. First, let’s compute the four different sums that this formula uses.

1: 41.63 1: 98.0003 . . r 1 V R + t 3 r 1 2 V M ^ V R + t 4

1: 13.613 1: 33.36554 . . r 2 V R + t 5 r 1 r 2 V M * V R + t 6

These are ‘ sum(x) ’, ‘ sum(x^2) ’, ‘ sum(y) ’, and ‘ sum(x y) ’, respectively. (We could have used * to compute ‘ sum(x^2) ’ and ‘ sum(x y) ’.)

Finally, we also need ‘ N ’, the number of data points. This is just the length of either of our lists.

1: 19 . r 1 v l t 7

(That’s v followed by a lower-case l .)

Now we grind through the formula:

1: 633.94526 2: 633.94526 1: 67.23607 . 1: 566.70919 . . r 7 r 6 * r 3 r 5 * -

2: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679 1: 1862.0057 2: 1862.0057 1: 128.9488 . . 1: 1733.0569 . . r 7 r 4 * r 3 2 ^ - / t 8

That gives us the slope ‘ m ’. The y-intercept ‘ b ’ can now be found with the simple formula,

b = (sum(y) - m sum(x)) / N

1: 13.613 2: 13.613 1: -8.09358 1: -0.425978 . 1: 21.70658 . . . r 5 r 8 r 3 * - r 7 / t 9

Let’s “plot” this straight line approximation, ‘ m x + b ’, and compare it with the original data.

1: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ] . . r 1 r 8 * r 9 + s 0

Notice that multiplying a vector by a constant, and adding a constant to a vector, can be done without mapping commands since these are common operations from vector algebra. As far as Calc is concerned, we’ve just been doing geometry in 19-dimensional space!

We can subtract this vector from our original ‘ y ’ vector to get a feel for the error of our fit. Let’s find the maximum error:

1: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897 . . . r 2 - V M A V R X

First we compute a vector of di