Go to the previous, next section.
This chapter describes commands that set modes in the Calculator. They do not affect the contents of the stack, although they may change the appearance or interpretation of the stack's contents.
You can save all of the current mode settings in your `.emacs' file
with the m m (calc-save-modes
) command. This will cause
Emacs to reestablish these modes each time it starts up. The modes saved
in the file include everything controlled by the m and d
prefix keys, the current precision and binary word size, whether or not
the trail is displayed, the current height of the Calc window, and more.
The current interface (used when you type M-# M-#) is also saved.
If there were already saved mode settings in the file, they are replaced.
Otherwise, the new mode information is appended to the end of the file.
The m R (calc-mode-record-mode
) command tells Calc to
record the new mode settings (as if by pressing m m) every
time a mode setting changes. If Embedded Mode is enabled, other
options are available; see section Mode Settings in Embedded Mode.
The m F (calc-settings-file-name
) command allows you to
choose a different place than your `.emacs' file for m m,
Z P, and similar commands to save permanent information.
You are prompted for a file name. All Calc modes are then reset to
their default values, then settings from the file you named are loaded
if this file exists, and this file becomes the one that Calc will
use in the future for commands like m m. The default settings
file name is `~/.emacs'. You can see the current file name by
giving a blank response to the m F prompt. See also the
discussion of the calc-settings-file
variable; see section Installation.
If the file name you give contains the string `.emacs' anywhere inside it, m F will not automatically load the new file. This is because you are presumably switching to your `~/.emacs' file, which may contain other things you don't want to reread. You can give a numeric prefix argument of 1 to m F to force it to read the file no matter what its name. Conversely, an argument of -1 tells m F not to read the new file. An argument of 2 or -2 tells m F not to reset the modes to their defaults beforehand, which is useful if you intend your new file to have a variant of the modes present in the file you were using before.
The m x (calc-always-load-extensions
) command enables a mode
in which the first use of Calc loads the entire program, including all
extensions modules. Otherwise, the extensions modules will not be loaded
until the various advanced Calc features are used. Since this mode only
has effect when Calc is first loaded, m x is usually followed by
m m to make the mode-setting permanent. To load all of Calc just
once, rather than always in the future, you can press M-# L.
The m S (calc-shift-prefix
) command enables a mode in which
all of Calc's letter prefix keys may be typed shifted as well as unshifted.
If you are typing, say, a S (calc-solve-for
) quite often
you might find it easier to turn this mode on so that you can type
A S instead. When this mode is enabled, the commands that used to
be on those single shifted letters (e.g., A (calc-abs
)) can
now be invoked by pressing the shifted letter twice: A A. Note
that the v prefix key always works both shifted and unshifted, and
the z and Z prefix keys are always distinct. Also, the h
prefix is not affected by this mode. Press m S again to disable
shifted-prefix mode.
The p (calc-precision
) command controls the precision to
which floating-point calculations are carried. The precision must be
at least 3 digits and may be arbitrarily high, within the limits of
memory and time. This affects only floats: Integer and rational
calculations are always carried out with as many digits as necessary.
The p key prompts for the current precision. If you wish you can instead give the precision as a numeric prefix argument.
Many internal calculations are carried to one or two digits higher precision than normal. Results are rounded down afterward to the current precision. Unless a special display mode has been selected, floats are always displayed with their full stored precision, i.e., what you see is what you get. Reducing the current precision does not round values already on the stack, but those values will be rounded down before being used in any calculation. The c 0 through c 9 commands (see section Conversions) can be used to round an existing value to a new precision.
It is important to distinguish the concepts of precision and accuracy. In the normal usage of these words, the number 123.4567 has a precision of 7 digits but an accuracy of 4 digits. The precision is the total number of digits not counting leading or trailing zeros (regardless of the position of the decimal point). The accuracy is simply the number of digits after the decimal point (again not counting trailing zeros). In Calc you control the precision, not the accuracy of computations. If you were to set the accuracy instead, then calculations like `exp(100)' would generate many more digits than you would typically need, while `exp(-100)' would probably round to zero! In Calc, both these computations give you exactly 12 (or the requested number of) significant digits.
The only Calc features that deal with accuracy instead of precision
are fixed-point display mode for floats (d f; see section Float Formats),
and the rounding functions like floor
and round
(see section Integer Truncation). Also, c 0 through c 9
deal with both precision and accuracy depending on the magnitudes
of the numbers involved.
If you need to work with a particular fixed accuracy (say, dollars and cents with two digits after the decimal point), one solution is to work with integers and an "implied" decimal point. For example, $8.99 divided by 6 would be entered 899 RET 6 /, yielding 149.833 (actually $1.49833 with our implied decimal point); pressing R would round this to 150 cents, i.e., $1.50.
See section Floats, for still more on floating-point precision and related issues.
There is no single-key equivalent to the calc-arcsin
function.
Instead, you must first press I (calc-inverse
) to set
the Inverse Flag, then press S (calc-sin
).
The I key actually toggles the Inverse Flag. When this flag
is set, the word `Inv' appears in the mode line.
Likewise, the H key (calc-hyperbolic
) sets or clears the
Hyperbolic Flag, which transforms calc-sin
into calc-sinh
.
If both of these flags are set at once, the effect will be
calc-arcsinh
. (The Hyperbolic flag is also used by some
non-trigonometric commands; for example H L computes a base-10,
instead of base-e, logarithm.)
Command names like calc-arcsin
are provided for completeness, and
may be executed with x or M-x. Their effect is simply to
toggle the Inverse and/or Hyperbolic flags and then execute the
corresponding base command (calc-sin
in this case).
The Inverse and Hyperbolic flags apply only to the next Calculator command, after which they are automatically cleared. (They are also cleared if the next keystroke is not a Calc command.) Digits you type after I or H (or K) are treated as prefix arguments for the next command, not as numeric entries. The same is true of C-u, but not of the minus sign (K - means to subtract and keep arguments).
The third Calc prefix flag, K (keep-arguments), is discussed elsewhere. See section Keep Arguments.
The commands in this section are two-key sequences beginning with
the m prefix. (That's the letter m, not the META key.)
The `m a' (calc-algebraic-mode
) command is described elsewhere
(see section Algebraic Entry).
The Calculator supports three notations for angles: radians, degrees,
and degrees-minutes-seconds. When a number is presented to a function
like sin
that requires an angle, the current angular mode is
used to interpret the number as either radians or degrees. If an HMS
form is presented to sin
, it is always interpreted as
degrees-minutes-seconds.
Functions that compute angles produce a number in radians, a number in degrees, or an HMS form depending on the current angular mode. If the result is a complex number and the current mode is HMS, the number is instead expressed in degrees. (Complex-number calculations would normally be done in radians mode, though. Complex numbers are converted to degrees by calculating the complex result in radians and then multiplying by 180 over @c{$\pi$} pi.)
The m r (calc-radians-mode
), m d (calc-degrees-mode
),
and m h (calc-hms-mode
) commands control the angular mode.
The current angular mode is displayed on the Emacs mode line.
The default angular mode is degrees.
The Calculator normally "prefers" rectangular complex numbers in the sense that rectangular form is used when the proper form can not be decided from the input. This might happen by multiplying a rectangular number by a polar one, by taking the square root of a negative real number, or by entering ( 2 SPC 3 ).
The m p (calc-polar-mode
) command toggles complex-number
preference between rectangular and polar forms. In polar mode, all
of the above example situations would produce polar complex numbers.
Division of two integers normally yields a floating-point number if the result cannot be expressed as an integer. In some cases you would rather get an exact fractional answer. One way to accomplish this is to multiply fractions instead: 6 RET 1:4 * produces 3:2 even though 6 RET 4 / produces 1.5.
To set the Calculator to produce fractional results for normal integer
divisions, use the m f (calc-frac-mode
) command.
For example, 8/4 produces 2 in either mode,
but 6/4 produces 3:2 in Fraction Mode, 1.5 in
Float Mode.
At any time you can use c f (calc-float
) to convert a
fraction to a float, or c F (calc-fraction
) to convert a
float to a fraction. See section Conversions.
The Calculator normally treats results like 1 / 0 as errors; formulas like this are left in unsimplified form. But Calc can be put into a mode where such calculations instead produce "infinite" results.
The m i (calc-infinite-mode
) command turns this mode
on and off. When the mode is off, infinities do not arise except
in calculations that already had infinities as inputs. (One exception
is that infinite open intervals like `[0 .. inf)' can be
generated; however, intervals closed at infinity (`[0 .. inf]')
will not be generated when infinite mode is off.)
With infinite mode turned on, `1 / 0' will generate uinf
,
an undirected infinity. See section Infinities, for a discussion of the
difference between inf
and uinf
. Also, 0 / 0
evaluates to nan
, the "indeterminate" symbol. Various other
functions can also return infinities in this mode; for example,
`ln(0) = -inf', and `gamma(-7) = uinf'. Once again,
note that `exp(inf) = inf' regardless of infinite mode because
this calculation has infinity as an input.
The m i command with a numeric prefix argument of zero,
i.e., C-u 0 m i, turns on a "positive infinite mode" in
which zero is treated as positive instead of being directionless.
Thus, `1 / 0 = inf' and `-1 / 0 = -inf' in this mode.
Note that zero never actually has a sign in Calc; there are no
separate representations for +0 and -0. Positive
infinite mode merely changes the interpretation given to the
single symbol, `0'. One consequence of this is that, while
you might expect `1 / -0 = -inf', actually `1 / -0'
is equivalent to `1 / 0', which is equal to positive inf
.
Calculations are normally performed numerically wherever possible.
For example, the calc-sqrt
command, or sqrt
function in an
algebraic expression, produces a numeric answer if the argument is a
number or a symbolic expression if the argument is an expression:
2 Q pushes 1.4142 but ' x+1 RET Q pushes `sqrt(x+1)'.
In symbolic mode, controlled by the m s (calc-symbolic-mode
)
command, functions which would produce inexact, irrational results are
left in symbolic form. Thus 16 Q pushes 4, but 2 Q pushes
`sqrt(2)'.
The shift-N (calc-eval-num
) command evaluates numerically
the expression at the top of the stack, by temporarily disabling
calc-symbolic-mode
and executing = (calc-evaluate
).
Given a numeric prefix argument, it also
sets the floating-point precision to the specified value for the duration
of the command.
To evaluate a formula numerically without expanding the variables it
contains, you can use the key sequence m s a v m s (this uses
calc-alg-evaluate
, which resimplifies but doesn't evaluate
variables.)
Calc sometimes makes assumptions during algebraic manipulation that are awkward or incorrect when vectors and matrices are involved. Calc has two modes, matrix mode and scalar mode, which modify its behavior around vectors in useful ways.
Press m v (calc-matrix-mode
) once to enter matrix mode.
In this mode, all objects are assumed to be matrices unless provably
otherwise. One major effect is that Calc will no longer consider
multiplication to be commutative. (Recall that in matrix arithmetic,
`A*B' is not the same as `B*A'.) This assumption affects
rewrite rules and algebraic simplification. Another effect of this
mode is that calculations that would normally produce constants like
0 and 1 (e.g., a - a and a / a, respectively) will now
produce function calls that represent "generic" zero or identity
matrices: `idn(0)', `idn(1)'. The idn
function
`idn(a,n)' returns a times an nxn
identity matrix; if n is omitted, it doesn't know what
dimension to use and so the idn
call remains in symbolic
form. However, if this generic identity matrix is later combined
with a matrix whose size is known, it will be converted into
a true identity matrix of the appropriate size. On the other hand,
if it is combined with a scalar (as in `idn(1) + 2'), Calc
will assume it really was a scalar after all and produce, e.g., 3.
Press m v a second time to get scalar mode. Here, objects are assumed not to be vectors or matrices unless provably so. For example, normally adding a variable to a vector, as in `[x, y, z] + a', will leave the sum in symbolic form because as far as Calc knows, `a' could represent either a number or another 3-vector. In scalar mode, `a' is assumed to be a non-vector, and the addition is evaluated to `[x+a, y+a, z+a]'.
Press m v a third time to return to the normal mode of operation.
If you press m v with a numeric prefix argument n, you get a special "dimensioned matrix mode" in which matrices of unknown size are assumed to be nxn square matrices. Then, the function call `idn(1)' will expand into an actual matrix rather than representing a "generic" matrix.
Of course these modes are approximations to the true state of affairs, which is probably that some quantities will be matrices and others will be scalars. One solution is to "declare" certain variables or functions to be scalar-valued. See section Declarations, to see how to make declarations in Calc.
There is nothing stopping you from declaring a variable to be scalar and then storing a matrix in it; however, if you do, the results you get from Calc may not be valid. Suppose you let Calc get the result `[x+a, y+a, z+a]' shown above, and then stored `[1, 2, 3]' in `a'. The result would not be the same as for `[x, y, z] + [1, 2, 3]', but that's because you have broken your earlier promise to Calc that `a' would be scalar.
Another way to mix scalars and matrices is to use selections (see section Selecting Sub-Formulas). Use matrix mode when operating on your formula normally; then, to apply scalar mode to a certain part of the formula without affecting the rest just select that part, change into scalar mode and press = to resimplify the part under this mode, then change back to matrix mode before deselecting.
The evaluates-to operator, `=>', has the special property that any `=>' formulas on the stack are recomputed whenever variable values or mode settings that might affect them are changed. See section The Evaluates-To Operator.
The m C (calc-auto-recompute
) command turns this
automatic recomputation on and off. If you turn it off, Calc will
not update `=>' operators on the stack (nor those in the
attached Embedded Mode buffer, if there is one). They will not
be updated unless you explicitly do so by pressing = or until
you press m C to turn recomputation back on. (While automatic
recomputation is off, you can think of m C m C as a command
to update all `=>' operators while leaving recomputation off.)
To update `=>' operators in an Embedded buffer while automatic recomputation is off, use M-# u. See section Embedded Mode.
Since the Calculator is written entirely in Emacs Lisp, which is not designed for heavy numerical work, many operations are quite slow. The Calculator normally displays the message `Working...' in the echo area during any command that may be slow. In addition, iterative operations such as square roots and trigonometric functions display the intermediate result at each step. Both of these types of messages can be disabled if you find them distracting.
Type m w (calc-working
) with a numeric prefix of 0 to
disable all "working" messages. Use a numeric prefix of 1 to enable
only the plain `Working...' message. Use a numeric prefix of 2 to
see intermediate results as well. With no numeric prefix this displays
the current mode.
While it may seem that the "working" messages will slow Calc down considerably, experiments have shown that their impact is actually quite small. But if your terminal is slow you may find that it helps to turn the messages off.
The current simplification mode controls how numbers and formulas are "normalized" when being taken from or pushed onto the stack. Some normalizations are unavoidable, such as rounding floating-point results to the current precision, and reducing fractions to simplest form. Others, such as simplifying a formula like a+a (or 2+3), are done by default but can be turned off when necessary.
When you press a key like + when 2 and 3 are on the stack, Calc pops these numbers, normalizes them, creates the formula 2+3, normalizes it, and pushes the result. Of course the standard rules for normalizing 2+3 will produce the result 5.
Simplification mode commands consist of the lower-case m prefix key followed by a shifted letter.
The m O (calc-no-simplify-mode
) command turns off all optional
simplifications. These would leave a formula like 2+3 alone. In
fact, nothing except simple numbers are ever affected by normalization
in this mode.
The m N (calc-num-simplify-mode
) command turns off simplification
of any formulas except those for which all arguments are constants. For
example, 1+2 is simplified to 3, and a+(2-2) is
simplified to a+0 but no further, since one argument of the sum
is not a constant. Unfortunately, (a+2)-2 is not simplified
because the top-level `-' operator's arguments are not both
constant numbers (one of them is the formula a+2).
A constant is a number or other numeric object (such as a constant
error form or modulo form), or a vector all of whose
elements are constant.
The m D (calc-default-simplify-mode
) command restores the
default simplifications for all formulas. This includes many easy and
fast algebraic simplifications such as a+0 to a, and
a + 2 a to 3 a, as well as evaluating functions like
deriv(x^2, x) to 2 x.
The m B (calc-bin-simplify-mode
) mode applies the default
simplifications to a result and then, if the result is an integer,
uses the b c (calc-clip
) command to clip the integer according
to the current binary word size. See section Binary Number Functions. Real numbers
are rounded to the nearest integer and then clipped; other kinds of
results (after the default simplifications) are left alone.
The m A (calc-alg-simplify-mode
) mode does algebraic
simplification; it applies all the default simplifications, and also
the more powerful (and slower) simplifications made by a s
(calc-simplify
). See section Algebraic Simplifications.
The m E (calc-ext-simplify-mode
) mode does "extended"
algebraic simplification, as by the a e (calc-simplify-extended
)
command. See section "Unsafe" Simplifications.
The m U (calc-units-simplify-mode
) mode does units
simplification; it applies the command u s
(calc-simplify-units
), which in turn
is a superset of a s. In this mode, variable names which
are identifiable as unit names (like `mm' for "millimeters")
are simplified with their unit definitions in mind.
A common technique is to set the simplification mode down to the lowest
amount of simplification you will allow to be applied automatically, then
use manual commands like a s and c c (calc-clean
) to
perform higher types of simplifications on demand. See section Programming with Formulas, for another sample use of no-simplification mode.
A declaration is a statement you make that promises you will use a certain variable or function in a restricted way. This may give Calc the freedom to do things that it couldn't do if it had to take the fully general situation into account.
The s d (calc-declare-variable
) command is the easiest
way to make a declaration for a variable. This command prompts for
the variable name, then prompts for the declaration. The default
at the declaration prompt is the previous declaration, if any.
You can edit this declaration, or press C-k to erase it and
type a new declaration. (Or, erase it and press RET to clear
the declaration, effectively "undeclaring" the variable.)
A declaration is in general a vector of type symbols and
range values. If there is only one type symbol or range value,
you can write it directly rather than enclosing it in a vector.
For example, s d foo RET real RET declares foo
to
be a real number, and s d bar RET [int, const, [1..6]] RET
declares bar
to be a constant integer between 1 and 6.
(Actually, you can omit the outermost brackets and Calc will
provide them for you: s d bar RET int, const, [1..6] RET.)
Declarations in Calc are kept in a special variable called Decls
.
This variable encodes the set of all outstanding declarations in
the form of a matrix. Each row has two elements: A variable or
vector of variables declared by that row, and the declaration
specifier as described above. You can use the s D command to
edit this variable if you wish to see all the declarations at once.
See section Other Operations on Variables, for a description of this command
and the s p command that allows you to save your declarations
permanently if you wish.
Items being declared can also be function calls. The arguments in
the call are ignored; the effect is to say that this function returns
values of the declared type for any valid arguments. The s d
command declares only variables, so if you wish to make a function
declaration you will have to edit the Decls
matrix yourself.
For example, the declaration matrix
[ [ foo, real ] [ [j, k, n], int ] [ f(1,2,3), [0 .. inf) ] ]
declares that foo
represents a real number, j
, k
and n
represent integers, and the function f
always
returns a real number in the interval shown.
If there is a declaration for the variable All
, then that
declaration applies to all variables that are not otherwise declared.
It does not apply to function names. For example, using the row
`[All, real]' says that all your variables are real unless they
are explicitly declared without real
in some other row.
The s d command declares All
if you give a blank
response to the variable-name prompt.
The type-specifier part of a declaration (that is, the second prompt in the s d command) can be a type symbol, an interval, or a vector consisting of zero or more type symbols followed by zero or more intervals or numbers that represent the set of possible values for the variable.
[ [ a, [1, 2, 3, 4, 5] ] [ b, [1 .. 5] ] [ c, [int, 1 .. 5] ] ]
Here a
is declared to contain one of the five integers shown;
b
is any number in the interval from 1 to 5 (any real number
since we haven't specified), and c
is any integer in that
interval. Thus the declarations for a
and c
are
nearly equivalent (see below).
The type-specifier can be the empty vector `[]' to say that
nothing is known about a given variable's value. This is the same
as not declaring the variable at all except that it overrides any
All
declaration which would otherwise apply.
The initial value of Decls
is the empty vector `[]'.
If Decls
has no stored value or if the value stored in it
is not valid, it is ignored and there are no declarations as far
as Calc is concerned. (The s d command will replace such a
malformed value with a fresh empty matrix, `[]', before recording
the new declaration.) Unrecognized type symbols are ignored.
The following type symbols describe what sorts of numbers will be stored in a variable:
int
numint
frac
rat
float
real
pos
nonneg
number
Calc uses this information to determine when certain simplifications
of formulas are safe. For example, `(x^y)^z' cannot be
simplified to `x^(y z)' in general; for example,
`((-3)^2)^1:2' is 3, but `(-3)^(2*1:2) = (-3)^1' is -3.
However, this simplification is safe if z
is known
to be an integer, or if x
is known to be a nonnegative
real number. If you have given declarations that allow Calc to
deduce either of these facts, Calc will perform this simplification
of the formula.
Calc can apply a certain amount of logic when using declarations.
For example, `(x^y)^(2n+1)' will be simplified if n
has been declared int
; Calc knows that an integer times an
integer, plus an integer, must always be an integer. (In fact,
Calc would simplify `(-x)^(2n+1)' to `-(x^(2n+1))' since
it is able to determine that `2n+1' must be an odd integer.)
Similarly, `(abs(x)^y)^z' will be simplified to `abs(x)^(y z)'
because Calc knows that the abs
function always returns a
nonnegative real. If you had a myabs
function that also had
this property, you could get Calc to recognize it by adding the row
`[myabs(), nonneg]' to the Decls
matrix.
One instance of this simplification is `sqrt(x^2)' (since the
sqrt
function is effectively a one-half power). Normally
Calc leaves this formula alone. After the command
s d x RET real RET, however, it can simplify the formula to
`abs(x)'. And after s d x RET nonneg RET, Calc can
simplify this formula all the way to `x'.
If there are any intervals or real numbers in the type specifier,
they comprise the set of possible values that the variable or
function being declared can have. In particular, the type symbol
real
is effectively the same as the range `[-inf .. inf]'
(note that infinity is included in the range of possible values);
pos
is the same as `(0 .. inf]', and nonneg
is
the same as `[0 .. inf]'. Saying `[real, [-5 .. 5]]' is
redundant because the fact that the variable is real can be
deduced just from the interval, but `[int, [-5 .. 5]]' and
`[rat, [-5 .. 5]]' are useful combinations.
Note that the vector of intervals or numbers is in the same format used by Calc's set-manipulation commands. See section Set Operations using Vectors.
The type specifier `[1, 2, 3]' is equivalent to `[numint, 1, 2, 3]', not to `[int, 1, 2, 3]'. In other words, the range of possible values means only that the variable's value must be numerically equal to a number in that range, but not that it must be equal in type as well. Calc's set operations act the same way; `in(2, [1., 2., 3.])' and `in(1.5, [1:2, 3:2, 5:2])' both report "true."
If you use a conflicting combination of type specifiers, the results are unpredictable. An example is `[pos, [0 .. 5]]', where the interval does not lie in the range described by the type symbol.
"Real" declarations mostly affect simplifications involving powers like the one described above. Another case where they are used is in the a P command which returns a list of all roots of a polynomial; if the variable has been declared real, only the real roots (if any) will be included in the list.
"Integer" declarations are used for simplifications which are valid only when certain values are integers (such as `(x^y)^z' shown above).
Another command that makes use of declarations is a s, when
simplifying equations and inequalities. It will cancel x
from both sides of `a x = b x' only if it is sure x
is non-zero, say, because it has a pos
declaration.
To declare specifically that x
is real and non-zero,
use `[[-inf .. 0), (0 .. inf]]'. (There is no way in the
current notation to say that x
is nonzero but not necessarily
real.) The a e command does "unsafe" simplifications,
including cancelling `x' from the equation when `x' is
not known to be nonzero.
Another set of type symbols distinguish between scalars and vectors.
scalar
vector
matrix
These type symbols can be combined with the other type symbols described above; `[int, matrix]' describes an object which is a matrix of integers.
Scalar/vector declarations are used to determine whether certain
algebraic operations are safe. For example, `[a, b, c] + x'
is normally not simplified to `[a + x, b + x, c + x]', but
it will be if x
has been declared scalar
. On the
other hand, multiplication is usually assumed to be commutative,
but the terms in `x y' will never be exchanged if both x
and y
are known to be vectors or matrices. (Calc currently
never distinguishes between vector
and matrix
declarations.)
See section Matrix and Scalar Modes, for a discussion of "matrix mode" and "scalar mode," which are similar to declaring `[All, matrix]' or `[All, scalar]' but much more convenient.
One more type symbol that is recognized is used with the H a d command for taking total derivatives of a formula. See section Calculus.
const
Calc does not check the declarations for a variable when you store
a value in it. However, storing -3.5 in a variable that has
been declared pos
, int
, or matrix
may have
unexpected effects; Calc may evaluate `sqrt(x^2)' to 3.5
if it substitutes the value first, or to -3.5 if x
was declared pos
and the formula `sqrt(x^2)' is
simplified to `x' before the value is substituted. Before
using a variable for a new purpose, it is best to use s d
or s D to check to make sure you don't still have an old
declaration for the variable that will conflict with its new meaning.
Calc has a set of functions for accessing the current declarations in a convenient manner. These functions return 1 if the argument can be shown to have the specified property, or 0 if the argument can be shown not to have that property; otherwise they are left unevaluated. These functions are suitable for use with rewrite rules (see section Conditional Rewrite Rules) or programming constructs (see section Conditionals in Keyboard Macros). They can be entered only using algebraic notation. See section Logical Operations, for functions that perform other tests not related to declarations.
For example, `dint(17)' returns 1 because 17 is an integer, as
do `dint(n)' and `dint(2 n - 3)' if n
has been declared
int
, but `dint(2.5)' and `dint(n + 0.5)' return 0.
Calc consults knowledge of its own built-in functions as well as your
own declarations: `dint(floor(x))' returns 1.
The dint
function checks if its argument is an integer.
The dnatnum
function checks if its argument is a natural
number, i.e., a nonnegative integer. The dnumint
function
checks if its argument is numerically an integer, i.e., either an
integer or an integer-valued float. Note that these and the other
data type functions also accept vectors or matrices composed of
suitable elements, and that real infinities `inf' and `-inf'
are considered to be integers for the purposes of these functions.
The drat
function checks if its argument is rational, i.e.,
an integer or fraction. Infinities count as rational, but intervals
and error forms do not.
The dreal
function checks if its argument is real. This
includes integers, fractions, floats, real error forms, and intervals.
The dimag
function checks if its argument is imaginary,
i.e., is mathematically equal to a real number times i.
The dpos
function checks for positive (but nonzero) reals.
The dneg
function checks for negative reals. The dnonneg
function checks for nonnegative reals, i.e., reals greater than or
equal to zero. Note that the a s command can simplify an
expression like x > 0 to 1 or 0 using dpos
, and that
a s is effectively applied to all conditions in rewrite rules,
so the actual functions dpos
, dneg
, and dnonneg
are rarely necessary.
The dnonzero
function checks that its argument is nonzero.
This includes all nonzero real or complex numbers, all intervals that
do not include zero, all nonzero modulo forms, vectors all of whose
elements are nonzero, and variables or formulas whose values can be
deduced to be nonzero. It does not include error forms, since they
represent values which could be anything including zero. (This is
also the set of objects considered "true" in conditional contexts.)
The deven
function returns 1 if its argument is known to be
an even integer (or integer-valued float); it returns 0 if its argument
is known not to be even (because it is known to be odd or a non-integer).
The a s command uses this to simplify a test of the form
`x % 2 = 0'. There is also an analogous dodd
function.
The drange
function returns a set (an interval or a vector
of intervals and/or numbers; see section Set Operations using Vectors) that describes
the set of possible values of its argument. If the argument is
a variable or a function with a declaration, the range is copied
from the declaration. Otherwise, the possible signs of the
expression are determined using a method similar to dpos
,
etc., and a suitable set like `[0 .. inf]' is returned. If
the expression is not provably real, the drange
function
remains unevaluated.
The dscalar
function returns 1 if its argument is provably
scalar, or 0 if its argument is provably non-scalar. It is left
unevaluated if this cannot be determined. (If matrix mode or scalar
mode are in effect, this function returns 1 or 0, respectively,
if it has no other information.) When Calc interprets a condition
(say, in a rewrite rule) it considers an unevaluated formula to be
"false." Thus, `dscalar(a)' is "true" only if a
is
provably scalar, and `!dscalar(a)' is "true" only if a
is provably non-scalar; both are "false" if there is insufficient
information to tell.
The commands in this section are two-key sequences beginning with the
d prefix. The d l (calc-line-numbering
) and d b
(calc-line-breaking
) commands are described elsewhere;
see section Stack Basics and see section Normal Language Modes, respectively.
Display formats for vectors and matrices are also covered elsewhere;
see section Vector and Matrix Display Formats.
One thing all display modes have in common is their treatment of the H prefix. This prefix causes any mode command that would normally refresh the stack to leave the stack display alone. The word "Dirty" will appear in the mode line when Calc thinks the stack display may not reflect the latest mode settings.
The d RET (calc-refresh-top
) command reformats the
top stack entry according to all the current modes. Positive prefix
arguments reformat the top n entries; negative prefix arguments
reformat the specified entry, and a prefix of zero is equivalent to
d SPC (calc-refresh
), which reformats the entire stack.
For example, H d s M-2 d RET changes to scientific notation
but reformats only the top two stack entries in the new mode.
The I prefix has another effect on the display modes. The mode is set only temporarily; the top stack entry is reformatted according to that mode, then the original mode setting is restored. In other words, I d s is equivalent to H d s d RET H d (old mode).
Calc normally displays numbers in decimal (base-10 or radix-10)
notation. Calc can actually display in any radix from two (binary) to 36.
When the radix is above 10, the letters A
to Z
are used as
digits. When entering such a number, letter keys are interpreted as
potential digits rather than terminating numeric entry mode.
The key sequences d 2, d 8, d 6, and d 0 select binary, octal, hexadecimal, and decimal as the current display radix, respectively. Numbers can always be entered in any radix, though the current radix is used as a default if you press # without any initial digits. A number entered without a # is always interpreted as decimal.
To set the radix generally, use d r (calc-radix
) and enter
an integer from 2 to 36. You can specify the radix as a numeric prefix
argument; otherwise you will be prompted for it.
Integers normally are displayed with however many digits are necessary to
represent the integer and no more. The d z (calc-leading-zeros
)
command causes integers to be padded out with leading zeros according to the
current binary word size. (See section Binary Number Functions, for a discussion of
word size.) If the absolute value of the word size is w, all integers
are displayed with at least enough digits to represent @c{$2^w-1$}
(2^w)-1 in the
current radix. (Larger integers will still be displayed in their entirety.)
Long numbers can be hard to read if they have too many digits. For
example, the factorial of 30 is 33 digits long! Press d g
(calc-group-digits
) to enable grouping mode, in which digits
are displayed in clumps of 3 or 4 (depending on the current radix)
separated by commas.
The d g command toggles grouping on and off. With a numerix prefix of 0, this command displays the current state of the grouping flag; with an argument of minus one it disables grouping; with a positive argument N it enables grouping on every N digits. For floating-point numbers, grouping normally occurs only before the decimal point. A negative prefix argument -N enables grouping every N digits both before and after the decimal point.
The d , (calc-group-char
) command allows you to choose any
character as the grouping separator. The default is the comma character.
If you find it difficult to read vectors of large integers grouped with
commas, you may wish to use spaces or some other character instead.
This command takes the next character you type, whatever it is, and
uses it as the digit separator. As a special case, d , \ selects
`\,' (TeX's thin-space symbol) as the digit separator.
Please note that grouped numbers will not generally be parsed correctly if re-read in textual form, say by the use of M-# y and M-# g. (See section Kill and Yank Functions, for details on these commands.) One exception is the `\,' separator, which doesn't interfere with parsing because it is ignored by TeX language mode.
Floating-point quantities are normally displayed in standard decimal form, with scientific notation used if the exponent is especially high or low. All significant digits are normally displayed. The commands in this section allow you to choose among several alternative display formats for floats.
The d n (calc-normal-notation
) command selects the normal
display format. All significant figures in a number are displayed.
With a positive numeric prefix, numbers are rounded if necessary to
that number of significant digits. With a negative numerix prefix,
the specified number of significant digits less than the current
precision is used. (Thus C-u -2 d n displays 10 digits if the
current precision is 12.)
The d f (calc-fix-notation
) command selects fixed-point
notation. The numeric argument is the number of digits after the
decimal point, zero or more. This format will relax into scientific
notation if a nonzero number would otherwise have been rounded all the
way to zero. Specifying a negative number of digits is the same as
for a positive number, except that small nonzero numbers will be rounded
to zero rather than switching to scientific notation.
The d s (calc-sci-notation
) command selects scientific
notation. A positive argument sets the number of significant figures
displayed, of which one will be before and the rest after the decimal
point. A negative argument works the same as for d n format.
The default is to display all significant digits.
The d e (calc-eng-notation
) command selects engineering
notation. This is similar to scientific notation except that the
exponent is rounded down to a multiple of three, with from one to three
digits before the decimal point. An optional numeric prefix sets the
number of significant digits to display, as for d s.
It is important to distinguish between the current precision and the current display format. After the commands C-u 10 p and C-u 6 d n the Calculator computes all results to ten significant figures but displays only six. (In fact, intermediate calculations are often carried to one or two more significant figures, but values placed on the stack will be rounded down to ten figures.) Numbers are never actually rounded to the display precision for storage, except by commands like C-k and M-# y which operate on the actual displayed text in the Calculator buffer.
The d . (calc-point-char
) command selects the character used
as a decimal point. Normally this is a period; users in some countries
may wish to change this to a comma. Note that this is only a display
style; on entry, periods must always be used to denote floating-point
numbers, and commas to separate elements in a list.
There are three supported notations for complex numbers in rectangular
form. The default is as a pair of real numbers enclosed in parentheses
and separated by a comma: `(a,b)'. The d c
(calc-complex-notation
) command selects this style.
The other notations are d i (calc-i-notation
), in which
numbers are displayed in `a+bi' form, and d j
(calc-j-notation
) which displays the form `a+bj' preferred
in some disciplines.
Complex numbers are normally entered in `(a,b)' format.
If you enter `2+3i' as an algebraic formula, it will be stored as
the formula `2 + 3 * i'. However, if you use = to evaluate
this formula and you have not changed the variable `i', the `i'
will be interpreted as `(0,1)' and the formula will be simplified
to `(2,3)'. Other commands (like calc-sin
) will not
interpret the formula `2 + 3 * i' as a complex number.
See section Variables, under "special constants."
Display of fractional numbers is controlled by the d o
(calc-over-notation
) command. By default, a number like
eight thirds is displayed in the form `8:3'. The d o command
prompts for a one- or two-character format. If you give one character,
that character is used as the fraction separator. Common separators are
`:' and `/'. (During input of numbers, the : key must be
used regardless of the display format; in particular, the / is used
for RPN-style division, not for entering fractions.)
If you give two characters, fractions use "integer-plus-fractional-part" notation. For example, the format `+/' would display eight thirds as `2+2/3'. If two colons are present in a number being entered, the number is interpreted in this form (so that the entries 2:2:3 and 8:3 are equivalent).
It is also possible to follow the one- or two-character format with a number. For example: `:10' or `+/3'. In this case, Calc adjusts all fractions that are displayed to have the specified denominator, if possible. Otherwise it adjusts the denominator to be a multiple of the specified value. For example, in `:6' mode the fraction 1:6 will be unaffected, but 2:3 will be displayed as 4:6, 1:2 will be displayed as 3:6, and 1:8 will be displayed as 3:24. Integers are also affected by this mode: 3 is displayed as 18:6. Note that the format `:1' writes fractions the same as `:', but it writes integers as n:1.
The fraction format does not affect the way fractions or integers are stored, only the way they appear on the screen. The fraction format never affects floats.
The d h (calc-hms-notation
) command controls the display of
HMS (hours-minutes-seconds) forms. It prompts for a string which
consists basically of an "hours" marker, optional punctuation, a
"minutes" marker, more optional punctuation, and a "seconds" marker.
Punctuation is zero or more spaces, commas, or semicolons. The hours
marker is one or more non-punctuation characters. The minutes and
seconds markers must be single non-punctuation characters.
The default HMS format is `@ ' "', producing HMS values of the form `23@ 30' 15.75"'. The format `deg, ms' would display this same value as `23deg, 30m15.75s'. During numeric entry, the h or o keys are recognized as synonyms for @ regardless of display format. The m and s keys are recognized as synonyms for ' and ", respectively, but only if an @ (or h or o) has already been typed; otherwise, they have their usual meanings (m- prefix and s- prefix). Thus, 5 ", 0 @ 5 ", and 0 h 5 s are some of the ways to enter the quantity "five seconds." The ' key is recognized as "minutes" only if @ (or h or o) has already been pressed; otherwise it means to switch to algebraic entry.
The d d (calc-date-notation
) command controls the display
of date forms (see section Date Forms). It prompts for a string which
contains letters that represent the various parts of a date and time.
To show which parts should be omitted when the form represents a pure
date with no time, parts of the string can be enclosed in `< >'
marks. If you don't include `< >' markers in the format, Calc
guesses at which parts, if any, should be omitted when formatting
pure dates.
The default format is: `<H:mm:SSpp >Www Mmm D, YYYY'. An example string in this format is `3:32pm Wed Jan 9, 1991'. If you enter a blank format string, this default format is reestablished.
Calc uses `< >' notation for nameless functions as well as for dates. See section Specifying Operators. To avoid confusion with nameless functions, your date formats should avoid using the `#' character.
When displaying a date, the current date format is used. All characters except for letters and `<' and `>' are copied literally when dates are formatted. The portion between `< >' markers is omitted for pure dates, or included for date/time forms. Letters are interpreted according to the table below.
When dates are read in during algebraic entry, Calc first tries to match the input string to the current format either with or without the time part. The punctuation characters (including spaces) must match exactly; letter fields must correspond to suitable text in the input. If this doesn't work, Calc checks if the input is a simple number; if so, the number is interpreted as a number of days since Jan 1, 1 AD. Otherwise, Calc tries a much more relaxed and flexible algorithm which is described in the next section.
Weekday names are ignored during reading.
Two-digit year numbers are interpreted as lying in the range from 1941 to 2039. Years outside that range are always entered and displayed in full. Year numbers with a leading `+' sign are always interpreted exactly, allowing the entry and display of the years 1 through 99 AD.
Here is a complete list of the formatting codes for dates:
If "SS" or "BS" (optional seconds) is preceded by a colon, the colon is also omitted if the seconds part is zero.
If "bb," "bbb" or "bbbb" or their upper-case equivalents appear in the format, then negative year numbers are displayed without a minus sign. Note that "aa" and "bb" are mutually exclusive. Some typical usages would be `YYYY AABB'; `AAAYYYYBBB'; `YYYYBBB'.
The formats "YY," "YYYY," "MM," "DD," "ddd," "hh," "HH," "mm," "ss," and "SS" actually match any number of digits during reading unless several of these codes are strung together with no punctuation in between, in which case the input must have exactly as many digits as there are letters in the format.
The "j," "J," and "U" formats do not make any time zone adjustment. They effectively use `julian(x,0)' and `unixtime(x,0)' to make the conversion; see section Date Arithmetic.
When reading a date form during algebraic entry, Calc falls back on the algorithm described here if the input does not exactly match the current date format. This algorithm generally "does the right thing" and you don't have to worry about it, but it is described here in full detail for the curious.
Calc does not distinguish between upper- and lower-case letters while interpreting dates.
First, the time portion, if present, is located somewhere in the text and then removed. The remaining text is then interpreted as the date.
A time is of the form `hh:mm:ss', possibly with the seconds part omitted and possibly with an AM/PM indicator added to indicate 12-hour time. If the AM/PM is present, the minutes may also be omitted. The AM/PM part may be any of the words `am', `pm', `noon', or `midnight'; each of these may be abbreviated to one letter, and the alternate forms `a.m.', `p.m.', and `mid' are also understood. Obviously `noon' and `midnight' are allowed only on 12:00:00. The words `noon', `mid', and `midnight' are also recognized with no number attached.
If there is no AM/PM indicator, the time is interpreted in 24-hour format.
To read the date portion, all words and numbers are isolated from the string; other characters are ignored. All words must be either month names or day-of-week names (the latter of which are ignored). Names can be written in full or as three-letter abbreviations.
Large numbers, or numbers with `+' or `-' signs, are interpreted as years. If one of the other numbers is greater than 12, then that must be the day and the remaining number in the input is therefore the month. Otherwise, Calc assumes the month, day and year are in the same order that they appear in the current date format. If the year is omitted, the current year is taken from the system clock.
If there are too many or too few numbers, or any unrecognizable words, then the input is rejected.
If there are any large numbers (of five digits or more) other than the year, they are ignored on the assumption that they are something like Julian dates that were included along with the traditional date components when the date was formatted.
One of the words `ad', `a.d.', `bc', or `b.c.' may optionally be used; the latter two are equivalent to a minus sign on the year value.
If you always enter a four-digit year, and use a name instead of a number for the month, there is no danger of ambiguity.
There are actually ten standard date formats, numbered 0 through 9. Entering a blank line at the d d command's prompt gives you format number 1, Calc's usual format. You can enter any digit to select the other formats.
To create your own standard date formats, give a numeric prefix argument from 0 to 9 to the d d command. The format you enter will be recorded as the new standard format of that number, as well as becoming the new current date format. You can save your formats permanently with the m m command (see section Mode Settings).
The d t (calc-truncate-stack
) command moves the `.'
line that marks the top-of-stack up or down in the Calculator buffer.
The number right above that line is considered to the be at the top of
the stack. Any numbers below that line are "hidden" from all stack
operations. This is similar to the Emacs "narrowing" feature, except
that the values below the `.' are visible, just temporarily
frozen. This feature allows you to keep several independent calculations
running at once in different parts of the stack, or to apply a certain
command to an element buried deep in the stack.
Pressing d t by itself moves the `.' to the line the cursor is on. Thus, this line and all those below it become hidden. To un-hide these lines, move down to the end of the buffer and press d t. With a positive numeric prefix argument n, d t hides the bottom n values in the buffer. With a negative argument, it hides all but the top n values. With an argument of zero, it hides zero values, i.e., moves the `.' all the way down to the bottom.
The d [ (calc-truncate-up
) and d ]
(calc-truncate-down
) commands move the `.' up or down one
line at a time (or several lines with a prefix argument).
Values on the stack are normally left-justified in the window. You can
control this arrangement by typing d < (calc-left-justify
),
d > (calc-right-justify
), or d =
(calc-center-justify
). For example, in right-justification mode,
stack entries are displayed flush-right against the right edge of the
window.
If you change the width of the Calculator window you may have to type
d SPC (calc-refresh
) to re-align right-justified or centered
text.
Right-justification is especially useful together with fixed-point
notation (see d f
; calc-fix-notation
). With these modes
together, the decimal points on numbers will always line up.
With a numeric prefix argument, the justification commands give you a little extra control over the display. The argument specifies the horizontal "origin" of a display line. It is also possible to specify a maximum line width using the d b command (see section Normal Language Modes). For reference, the precise rules for formatting and breaking lines are given below. Notice that the interaction between origin and line width is slightly different in each justification mode.
In left-justified mode, the line is indented by a number of spaces given by the origin (default zero). If the result is longer than the maximum line width, if given, or too wide to fit in the Calc window otherwise, then it is broken into lines which will fit; each broken line is indented to the origin.
In right-justified mode, lines are shifted right so that the rightmost character is just before the origin, or just before the current window width if no origin was specified. If the line is too long for this, then it is broken; the current line width is used, if specified, or else the origin is used as a width if that is specified, or else the line is broken to fit in the window.
In centering mode, the origin is the column number of the center of each stack entry. If a line width is specified, lines will not be allowed to go past that width; Calc will either indent less or break the lines if necessary. If no origin is specified, half the line width or Calc window width is used.
Note that, in each case, if line numbering is enabled the display is indented an additional four spaces to make room for the line number. The width of the line number is taken into account when positioning according to the current Calc window width, but not when positioning by explicit origins and widths. In the latter case, the display is formatted as specified, and then uniformly shifted over four spaces to fit the line numbers.
The d { (calc-left-label
) command prompts for a string,
then displays that string to the left of every stack entry. If the
entries are left-justified (see section Justification), then they will
appear immediately after the label (unless you specified an origin
greater than the length of the label). If the entries are centered
or right-justified, the label appears on the far left and does not
affect the horizontal position of the stack entry.
Give a blank string (with d { RET) to turn the label off.
The d } (calc-right-label
) command similarly adds a
label on the righthand side. It does not affect positioning of
the stack entries unless they are right-justified. Also, if both
a line width and an origin are given in right-justified mode, the
stack entry is justified to the origin and the righthand label is
justified to the line width.
One application of labels would be to add equation numbers to formulas you are manipulating in Calc and then copying into a document (possibly using Embedded Mode). The equations would typically be centered, and the equation numbers would be on the left or right as you prefer.
The commands in this section change Calc to use a different notation for entry and display of formulas, corresponding to the conventions of some other common language such as Pascal or TeX. Objects displayed on the stack or yanked from the Calculator to an editing buffer will be formatted in the current language; objects entered in algebraic entry or yanked from another buffer will be interpreted according to the current language.
The current language has no effect on things written to or read from the trail buffer, nor does it affect numeric entry. Only algebraic entry is affected. You can make even algebraic entry ignore the current language and use the standard notation by giving a numeric prefix, e.g., C-u '.
For example, suppose the formula `2*a[1] + atan(a[2])' occurs in a C
program; elsewhere in the program you need the derivatives of this formula
with respect to `a[1]' and `a[2]'. First, type d C
to switch to C notation. Now use C-u M-# g
to grab the formula
into the Calculator, a d a[1] RET to differentiate with respect
to the first variable, and M-# y to yank the formula for the derivative
back into your C program. Press U to undo the differentiation and
repeat with a d a[2] RET for the other derivative.
Without being switched into C mode first, Calc would have misinterpreted
the brackets in `a[1]' and `a[2]', would not have known that
atan
was equivalent to Calc's built-in arctan
function,
and would have written the formula back with notations (like implicit
multiplication) which would not have been legal for a C program.
As another example, suppose you are maintaining a C program and a TeX document, each of which needs a copy of the same formula. You can grab the formula from the program in C mode, switch to TeX mode, and yank the formula into the document in TeX math-mode format.
Language modes are selected by typing the letter d followed by a shifted letter key.
The d N (calc-normal-language
) command selects the usual
notation for Calc formulas, as described in the rest of this manual.
Matrices are displayed in a multi-line tabular format, but all other
objects are written in linear form, as they would be typed from the
keyboard.
The d O (calc-flat-language
) command selects a language
identical with the normal one, except that matrices are written in
one-line form along with everything else. In some applications this
form may be more suitable for yanking data into other buffers.
Even in one-line mode, long formulas or vectors will still be split
across multiple lines if they exceed the width of the Calculator window.
The d b (calc-line-breaking
) command turns this line-breaking
feature on and off. (It works independently of the current language.)
If you give a numeric prefix argument of five or greater to the d b
command, that argument will specify the line width used when breaking
long lines.
The d B (calc-big-language
) command selects a language
which uses textual approximations to various mathematical notations,
such as powers, quotients, and square roots:
____________ | a + 1 2 | ----- + c \| b
in place of `sqrt((a+1)/b + c^2)'.
Subscripts like `a_i' are displayed as actual subscripts in "big" mode. Double subscripts, `a_i_j' (`subscr(subscr(a, i), j)') are displayed as `a' with subscripts separated by commas: `i, j'. They must still be entered in the usual underscore notation.
One slight ambiguity of Big notation is that
3 - - 4
can represent either the negative rational number -3:4, or the actual expression `-(3/4)'; but the latter formula would normally never be displayed because it would immediately be evaluated to -3:4 or -0.75, so this ambiguity is not a problem in typical use.
Non-decimal numbers are displayed with subscripts. Thus there is no way to tell the difference between `16#C2' and `C2_16', though generally you will know which interpretation is correct. Logarithms `log(x,b)' and `log10(x)' also use subscripts in Big mode.
In Big mode, stack entries often take up several lines. To aid
readability, stack entries are separated by a blank line in this mode.
You may find it useful to expand the Calc window's height using
C-x ^ (enlarge-window
) or to make the Calc window the only
one on the screen with C-x 1 (delete-other-windows
).
Long lines are currently not rearranged to fit the window width in Big mode, so you may need to use the < and > keys to scroll across a wide formula. For really big formulas, you may even need to use { and } to scroll up and down.
The d U (calc-unformatted-language
) command altogether disables
the use of operator notation in formulas. In this mode, the formula
shown above would be displayed:
sqrt(add(div(add(a, 1), b), pow(c, 2)))
These four modes differ only in display format, not in the format expected for algebraic entry. The standard Calc operators work in all four modes, and unformatted notation works in any language mode (except that Mathematica mode expects square brackets instead of parentheses).
The d C (calc-c-language
) command selects the conventions
of the C language for display and entry of formulas. This differs from
the normal language mode in a variety of (mostly minor) ways. In
particular, C language operators and operator precedences are used in
place of Calc's usual ones. For example, `a^b' means `xor(a,b)'
in C mode; a value raised to a power is written as a function call,
`pow(a,b)'.
In C mode, vectors and matrices use curly braces instead of brackets.
Octal and hexadecimal values are written with leading `0' or `0x'
rather than using the `#' symbol. Array subscripting is
translated into subscr
calls, so that `a[i]' in C
mode is the same as `a_i' in normal mode. Assignments
turn into the assign
function, which Calc normally displays
using the `:=' symbol.
The variables var-pi
and var-e
would be displayed `pi'
and `e' in normal mode, but in C mode they are displayed as
`M_PI' and `M_E', corresponding to the names of constants
typically provided in the `<math.h>' header. Functions whose
names are different in C are translated automatically for entry and
display purposes. For example, entering `asin(x)' will push the
formula `arcsin(x)' onto the stack; this formula will be displayed
as `asin(x)' as long as C mode is in effect.
The d P (calc-pascal-language
) command selects Pascal
conventions. Like C mode, Pascal mode interprets array brackets and uses
a different table of operators. Hexadecimal numbers are entered and
displayed with a preceding dollar sign. (Thus the regular meaning of
$2 during algebraic entry does not work in Pascal mode, though
$ (and $$, etc.) not followed by digits works the same as
always.) No special provisions are made for other non-decimal numbers,
vectors, and so on, since there is no universally accepted standard way
of handling these in Pascal.
The d F (calc-fortran-language
) command selects FORTRAN
conventions. Various function names are transformed into FORTRAN
equivalents. Vectors are written as `/1, 2, 3/', and may be
entered this way or using square brackets. Since FORTRAN uses round
parentheses for both function calls and array subscripts, Calc displays
both in the same way; `a(i)' is interpreted as a function call
upon reading, and subscripts must be entered as `subscr(a, i)'.
Also, if the variable a
has been declared to have type
vector
or matrix
then `a(i)' will be parsed as a
subscript. (See section Declarations.) Usually it doesn't matter, though;
if you enter the subscript expression `a(i)' and Calc interprets
it as a function call, you'll never know the difference unless you
switch to another language mode or replace a
with an actual
vector (or unless a
happens to be the name of a built-in
function!).
Underscores are allowed in variable and function names in all of these language modes. The underscore here is equivalent to the `#' in normal mode, or to hyphens in the underlying Emacs Lisp variable names.
FORTRAN and Pascal modes normally do not adjust the case of letters in formulas. Most built-in Calc names use lower-case letters. If you use a positive numeric prefix argument with d P or d F, these modes will use upper-case letters exclusively for display, and will convert to lower-case on input. With a negative prefix, these modes convert to lower-case for display and input.
The d T (calc-tex-language
) command selects the conventions
of "math mode" in the TeX typesetting language, by Donald Knuth.
Formulas are entered
and displayed in TeX notation, as in `\sin\left( a \over b \right)'.
Math formulas are usually enclosed by `$ $' signs in TeX; these
should be omitted when interfacing with Calc. To Calc, the `$' sign
has the same meaning it always does in algebraic formulas (a reference to
an existing entry on the stack).
Complex numbers are displayed as in `3 + 4i'. Fractions and
quotients are written using \over
;
binomial coefficients are written with \choose
.
Interval forms are written with \ldots
, and
error forms are written with \pm
.
Absolute values are written as in `|x + 1|', and the floor and
ceiling functions are written with \lfloor
, \rfloor
, etc.
The words \left
and \right
are ignored when reading
formulas in TeX mode. Both inf
and uinf
are written
as \infty
; when read, \infty
always translates to
inf
.
Function calls are written the usual way, with the function name followed
by the arguments in parentheses. However, functions for which TeX has
special names (like \sin
) will use curly braces instead of
parentheses for very simple arguments. During input, curly braces and
parentheses work equally well for grouping, but when the document is
formatted the curly braces will be invisible. Thus the printed result is
sin 2x but @c{$\sin(2 + x)$}
sin(2 + x).
Function and variable names not treated specially by TeX are simply
written out as-is, which will cause them to come out in italic letters
in the printed document. If you invoke d T with a positive numeric
prefix argument, names of more than one character will instead be written
`\hbox{name}'. The `\hbox{ }' notation is ignored
during reading. If you use a negative prefix argument, such function
names are written `\name', and function names that begin
with \
during reading have the \
removed. (Note that
in this mode, long variable names are still written with \hbox
.
However, you can always make an actual variable name like \bar
in any TeX mode.)
During reading, text of the form `\matrix{ ... }' is replaced
by `[ ... ]'. The same also applies to \pmatrix
and
\bmatrix
. The symbol `&' is interpreted as a comma,
and the symbols `\cr' and `\\' are interpreted as semicolons.
During output, matrices are displayed in `\matrix{ a & b \\ c & d}'
format; you may need to edit this afterwards to change \matrix
to \pmatrix
or \\
to \cr
.
Accents like \tilde
and \bar
translate into function
calls internally (`tilde(x)', `bar(x)'). The \underline
sequence is treated as an accent. The \vec
accent corresponds
to the function name Vec
, because vec
is the name of
a built-in Calc function. The following table shows the accents
in Calc, TeX, and eqn (described in the next section):
@begingroup @let@calcindexershow=@calcindexernoshow @let@calcindexersh=@calcindexernoshow @endgroup
Calc TeX eqn ---- -- --- acute \acute bar \bar bar breve \breve check \check dot \dot dot dotdot \ddot dotdot dyad dyad grave \grave hat \hat hat Prime prime tilde \tilde tilde under \underline under Vec \vec vec
The `=>' (evaluates-to) operator appears as a \to
symbol:
`{a \to b}'. TeX defines \to
as an
alias for \rightarrow
. However, if the `=>' is the
top-level expression being formatted, a slightly different notation
is used: `\evalto a \to b'. The \evalto
word is ignored by Calc's input routines, and is undefined in TeX.
You will typically want to include one of the following definitions
at the top of a TeX file that uses \evalto
:
\def\evalto{} \def\evalto#1\to{}
The first definition formats evaluates-to operators in the usual
way. The second causes only the b part to appear in the
printed document; the a part and the arrow are hidden.
Another definition you may wish to use is `\let\to=\Rightarrow'
which causes \to
to appear more like Calc's `=>' symbol.
See section The Evaluates-To Operator, for a discussion of evalto
.
The complete set of TeX control sequences that are ignored during reading is:
\hbox \mbox \text \left \right \, \> \: \; \! \quad \qquad \hfil \hfill \displaystyle \textstyle \dsize \tsize \scriptstyle \scriptscriptstyle \ssize \ssize \rm \bf \it \sl \roman \bold \italic \slanted \cal \mit \Cal \Bbb \frak \goth \evalto
Note that, because these symbols are ignored, reading a TeX formula into Calc and writing it back out may lose spacing and font information.
Also, the "discretionary multiplication sign" `\*' is read the same as `*'.
Here are some examples of how various Calc formulas are formatted in TeX:
sin(a^2 / b_i) \sin\left( {a^2 \over b_i} \right)
[(3, 4), 3:4, 3 +/- 4, [3 .. inf)] [3 + 4i, {3 \over 4}, 3 \pm 4, [3 \ldots \infty)]
[abs(a), abs(a / b), floor(a), ceil(a / b)] [|a|, \left| a \over b \right|, \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
[sin(a), sin(2 a), sin(2 + a), sin(a / b)] [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)]
First with plain d T, then with C-u d T, then finally with C-u - d T (using the example definition `\def\foo#1{\tilde F(#1)}':
[f(a), foo(bar), sin(pi)] [f(a), foo(bar), \sin{\pi}] [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] [f(a), \foo{\hbox{bar}}, \sin{\pi}]
First with `\def\evalto{}', then with `\def\evalto#1\to{}':
2 + 3 => 5 \evalto 2 + 3 \to 5
First with standard \to
, then with `\let\to\Rightarrow':
[2 + 3 => 5, a / 2 => (b + c) / 2] [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}]
Matrices normally, then changing \matrix
to \pmatrix
:
[ [ a / b, 0 ], [ 0, 2^(x + 1) ] ] \matrix{ {a \over b} & 0 \\ 0 & 2^{(x + 1)} } \pmatrix{ {a \over b} & 0 \\ 0 & 2^{(x + 1)} }
Eqn is another popular formatter for math formulas. It is
designed for use with the TROFF text formatter, and comes standard
with many versions of Unix. The d E (calc-eqn-language
)
command selects eqn notation.
The eqn language's main idiosyncrasy is that whitespace plays
a significant part in the parsing of the language. For example,
`sqrt x+1 + y' treats `x+1' as the argument of the
sqrt
operator. Eqn also understands more conventional
grouping using curly braces: `sqrt{x+1} + y'. Braces are
required only when the argument contains spaces.
In Calc's eqn mode, however, curly braces are required to
delimit arguments of operators like sqrt
. The first of the
above examples would treat only the `x' as the argument of
sqrt
, and in fact `sin x+1' would be interpreted as
`sin * x + 1', because sin
is not a special operator
in the eqn language. If you always surround the argument
with curly braces, Calc will never misunderstand.
Calc also understands parentheses as grouping characters. Another
peculiarity of eqn's syntax makes it advisable to separate
words with spaces from any surrounding characters that aren't curly
braces, so Calc writes `sin ( x + y )' in eqn mode.
(The spaces around sin
are important to make eqn
recognize that sin
should be typeset in a roman font, and
the spaces around x
and y
are a good idea just in
case the eqn document has defined special meanings for these
names, too.)
Powers and subscripts are written with the sub
and sup
operators, respectively. Note that the caret symbol `^' is
treated the same as a space in eqn mode, as is the `~'
symbol (these are used to introduce spaces of various widths into
the typeset output of eqn).
As in TeX mode, Calc's formatter omits parentheses around the
arguments of functions like ln
and sin
if they are
"simple-looking"; in this case Calc surrounds the argument with
braces, separated by a `~' from the function name: `sin~{x}'.
Font change codes (like `roman x') and positioning codes
(like `~' and `down n x') are ignored by the
eqn reader. Also ignored are the words left
, right
,
mark
, and lineup
. Quotation marks in eqn mode input
are treated the same as curly braces: `sqrt "1+x"' is equivalent to
`sqrt {1+x}'; this is only an approximation to the true meaning
of quotes in eqn, but it is good enough for most uses.
Accent codes (`x dot') are handled by treating them as
function calls (`dot(x)') internally. See section TeX Language Mode for a table of these accent functions. The prime
accent
is treated specially if it occurs on a variable or function name:
`f prime prime ( x prime )' is stored internally as
`f''(x')'. For example, taking the derivative of `f(2 x)'
with a d x will produce `2 f'(2 x)', which eqn mode
will display as `2 f prime ( 2 x )'.
Assignments are written with the `<-' (left-arrow) symbol,
and evalto
operators are written with `->' or
`evalto ... ->' (see section TeX Language Mode, for a discussion
of this). The regular Calc symbols `:=' and `=>' are also
recognized for these operators during reading.
Vectors in eqn mode use regular Calc square brackets, but
matrices are formatted as `matrix { ccol { a above b } ... }'.
The words lcol
and rcol
are recognized as synonyms
for ccol
during input, and are generated instead of ccol
if the matrix justification mode so specifies.
The d M (calc-mathematica-language
) command selects the
conventions of Mathematica, a powerful and popular mathematical tool
from Wolfram Research, Inc. Notable differences in Mathematica mode
are that the names of built-in functions are capitalized, and function
calls use square brackets instead of parentheses. Thus the Calc
formula `sin(2 x)' is entered and displayed `Sin[2 x]' in
Mathematica mode.
Vectors and matrices use curly braces in Mathematica. Complex numbers
are written `3 + 4 I'. The standard special constants in Calc are
written Pi
, E
, I
, GoldenRatio
, EulerGamma
,
Infinity
, ComplexInfinity
, and Indeterminate
in
Mathematica mode.
Non-decimal numbers are written, e.g., `16^^7fff'. Floating-point
numbers in scientific notation are written `1.23*10.^3'.
Subscripts use double square brackets: `a[[i]]'.
The d W (calc-maple-language
) command selects the
conventions of Maple, another mathematical tool from the University
of Waterloo.
Maple's language is much like C. Underscores are allowed in symbol names; square brackets are used for subscripts; explicit `*'s for multiplications are required. Use either `^' or `**' to denote powers.
Maple uses square brackets for lists and curly braces for sets. Calc
interprets both notations as vectors, and displays vectors with square
brackets. This means Maple sets will be converted to lists when they
pass through Calc. As a special case, matrices are written as calls
to the function matrix
, given a list of lists as the argument,
and can be read in this form or with all-capitals MATRIX
.
The Maple interval notation `2 .. 3' has no surrounding brackets; Calc reads `2 .. 3' as the closed interval `[2 .. 3]', and writes any kind of interval as `2 .. 3'. This means you cannot see the difference between an open and a closed interval while in Maple display mode.
Maple writes complex numbers as `3 + 4*I'. Its special constants
are Pi
, E
, I
, and infinity
(all three of
inf
, uinf
, and nan
display as infinity
).
Floating-point numbers are written `1.23*10.^3'.
Among things not currently handled by Calc's Maple mode are the various quote symbols, procedures and functional operators, and inert (`&') operators.
There are several composition functions which allow you to get displays in a variety of formats similar to those in Big language mode. Most of these functions do not evaluate to anything; they are placeholders which are left in symbolic form by Calc's evaluator but are recognized by Calc's display formatting routines.
Two of these, string
and bstring
, are described elsewhere.
See section Strings. For example, `string("ABC")' is displayed as
`ABC'. When viewed on the stack it will be indistinguishable from
the variable ABC
, but internally it will be stored as
`string([65, 66, 67])' and can still be manipulated this way; for
example, the selection and vector commands j 1 v v j u would
select the vector portion of this object and reverse the elements, then
deselect to reveal a string whose characters had been reversed.
The composition functions do the same thing in all language modes (although their components will of course be formatted in the current language mode). The one exception is Unformatted mode (d U), which does not give the composition functions any special treatment. The functions are discussed here because of their relationship to the language modes.
Compositions are generally formed by stacking formulas together horizontally or vertically in various ways. Those formulas are themselves compositions. TeX users will find this analogous to TeX's "boxes." Each multi-line composition has a baseline; horizontal compositions use the baselines to decide how formulas should be positioned relative to one another. For example, in the Big mode formula
2 a + b 17 + ------ c
the second term of the sum is four lines tall and has line three as its baseline. Thus when the term is combined with 17, line three is placed on the same level as the baseline of 17.
Another important composition concept is precedence. This is an integer that represents the binding strength of various operators. For example, `*' has higher precedence (195) than `+' (180), which means that `(a * b) + c' will be formatted without the parentheses, but `a * (b + c)' will keep the parentheses.
The operator table used by normal and Big language modes has the following precedences:
_ 1200 (subscripts) % 1100 (as in n%) - 1000 (as in -n) ! 1000 (as in !n) mod 400 +/- 300 !! 210 (as in n!!) ! 210 (as in n!) ^ 200 * 195 (or implicit multiplication) / % \ 190 + - 180 (as in a+b) | 170 < = 160 (and other relations) && 110 || 100 ? : 90 !!! 85 &&& 80 ||| 75 := 50 :: 45 => 40
The general rule is that if an operator with precedence n occurs as an argument to an operator with precedence m, then the argument is enclosed in parentheses if n < m. Top-level expressions and expressions which are function arguments, vector components, etc., are formatted with precedence zero (so that they normally never get additional parentheses).
For binary left-associative operators like `+', the righthand argument is actually formatted with one-higher precedence than shown in the table. This makes sure `(a + b) + c' omits the parentheses, but the unnatural form `a + (b + c)' keeps its parentheses. Right-associative operators like `^' format the lefthand argument with one-higher precedence.
The cprec
function formats an expression with an arbitrary
precedence. For example, `cprec(abc, 185)' will combine into
sums and products as follows: `7 + abc', `7 (abc)' (because
this cprec
form has higher precedence than addition, but lower
precedence than multiplication).
A final composition issue is line breaking. Calc uses two different strategies for "flat" and "non-flat" compositions. A non-flat composition is anything that appears on multiple lines (not counting line breaking). Examples would be matrices and Big mode powers and quotients. Non-flat compositions are displayed exactly as specified. If they come out wider than the current window, you must use horizontal scrolling (< and >) to view them.
Flat compositions, on the other hand, will be broken across several lines if they are too wide to fit the window. Certain points in a composition are noted internally as break points. Calc's general strategy is to fill each line as much as possible, then to move down to the next line starting at the first break point that didn't fit. However, the line breaker understands the hierarchical structure of formulas. It will not break an "inner" formula if it can use an earlier break point from an "outer" formula instead. For example, a vector of sums might be formatted as:
[ a + b + c, d + e + f, g + h + i, j + k + l, m ]
If the `m' can fit, then so, it seems, could the `g'. But Calc prefers to break at the comma since the comma is part of a "more outer" formula. Calc would break at a plus sign only if it had to, say, if the very first sum in the vector had itself been too large to fit.
Of the composition functions described below, only choriz
generates break points. The bstring
function (see section Strings)
also generates breakable items: A break point is added after every
space (or group of spaces) except for spaces at the very beginning or
end of the string.
Composition functions themselves count as levels in the formula
hierarchy, so a choriz
that is a component of a larger
choriz
will be less likely to be broken. As a special case,
if a bstring
occurs as a component of a choriz
or
choriz
-like object (such as a vector or a list of arguments
in a function call), then the break points in that bstring
will be on the same level as the break points of the surrounding
object.
The choriz
function takes a vector of objects and composes
them horizontally. For example, `choriz([17, a b/c, d])' formats
as `17a b / cd' in normal language mode, or as
a b 17--d c
in Big language mode. This is actually one case of the general function `choriz(vec, sep, prec)', where either or both of sep and prec may be omitted. Prec gives the precedence to use when formatting each of the components of vec. The default precedence is the precedence from the surrounding environment.
Sep is a string (i.e., a vector of character codes as might
be entered with " "
notation) which should separate components
of the composition. Also, if sep is given, the line breaker
will allow lines to be broken after each occurrence of sep.
If sep is omitted, the composition will not be breakable
(unless any of its component compositions are breakable).
For example, `2 choriz([a, b c, d = e], " + ", 180)' is
formatted as `2 a + b c + (d = e)'. To get the choriz
to have precedence 180 "outwards" as well as "inwards,"
enclose it in a cprec
form: `2 cprec(choriz(...), 180)'
formats as `2 (a + b c + (d = e))'.
The baseline of a horizontal composition is the same as the baselines of the component compositions, which are all aligned.
The cvert
function makes a vertical composition. Each
component of the vector is centered in a column. The baseline of
the result is by default the top line of the resulting composition.
For example, `f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))'
formats in Big mode as
f( a , 2 ) bb a + 1 ccc 2 b
There are several special composition functions that work only as
components of a vertical composition. The cbase
function
controls the baseline of the vertical composition; the baseline
will be the same as the baseline of whatever component is enclosed
in cbase
. Thus `f(cvert([a, cbase(bb), ccc]),
cvert([a^2 + 1, cbase(b^2)]))' displays as
2 a + 1 a 2 f(bb , b ) ccc
There are also ctbase
and cbbase
functions which
make the baseline of the vertical composition equal to the top
or bottom line (rather than the baseline) of that component.
Thus `cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
cvert([cbbase(a / b)])' gives
a a - - + a + b b - b
There should be only one cbase
, ctbase
, or cbbase
function in a given vertical composition. These functions can also
be written with no arguments: `ctbase()' is a zero-height object
which means the baseline is the top line of the following item, and
`cbbase()' means the baseline is the bottom line of the preceding
item.
The crule
function builds a "rule," or horizontal line,
across a vertical composition. By itself `crule()' uses `-'
characters to build the rule. You can specify any other character,
e.g., `crule("=")'. The argument must be a character code or
vector of exactly one character code. It is repeated to match the
width of the widest item in the stack. For example, a quotient
with a thick line is `cvert([a + 1, cbase(crule("=")), b^2])':
a + 1 ===== 2 b
Finally, the functions clvert
and crvert
act exactly
like cvert
except that the items are left- or right-justified
in the stack. Thus `clvert([a, bb, ccc]) + crvert([a, bb, ccc])'
gives:
a + a bb bb ccc ccc
Like choriz
, the vertical compositions accept a second argument
which gives the precedence to use when formatting the components.
Vertical compositions do not support separator strings.
The csup
function builds a superscripted expression. For
example, `csup(a, b)' looks the same as `a^b' does in Big
language mode. This is essentially a horizontal composition of
`a' and `b', where `b' is shifted up so that its
bottom line is one above the baseline.
Likewise, the csub
function builds a subscripted expression.
This shifts `b' down so that its top line is one below the
bottom line of `a' (note that this is not quite analogous to
csup
). Other arrangements can be obtained by using
choriz
and cvert
directly.
The cflat
function formats its argument in "flat" mode,
as obtained by `d O', if the current language mode is normal
or Big. It has no effect in other language modes. For example,
`a^(b/c)' is formatted by Big mode like `csup(a, cflat(b/c))'
to improve its readability.
The cspace
function creates horizontal space. For example,
`cspace(4)' is effectively the same as `string(" ")'.
A second string (i.e., vector of characters) argument is repeated
instead of the space character. For example, `cspace(4, "ab")'
looks like `abababab'. If the second argument is not a string,
it is formatted in the normal way and then several copies of that
are composed together: `cspace(4, a^2)' yields
2 2 2 2 a a a a
If the number argument is zero, this is a zero-width object.
The cvspace
function creates vertical space, or a vertical
stack of copies of a certain string or formatted object. The
baseline is the center line of the resulting stack. A numerical
argument of zero will produce an object which contributes zero
height if used in a vertical composition.
There are also ctspace
and cbspace
functions which
create vertical space with the baseline the same as the baseline
of the top or bottom copy, respectively, of the second argument.
Thus `cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)'
displays as:
a - a b - a a b + - + - a b b - a b - b
The functions in this section are actual functions; they compose their arguments according to the current language and other display modes, then return a certain measurement of the composition as an integer.
The cwidth
function measures the width, in characters, of a
composition. For example, `cwidth(a + b)' is 5, and
`cwidth(a / b)' is 5 in normal mode, 1 in Big mode, and 11 in
TeX mode (for `{a \over b}'). The argument may involve
the composition functions described in this section.
The cheight
function measures the height of a composition.
This is the total number of lines in the argument's printed form.
The functions cascent
and cdescent
measure the amount
of the height that is above (and including) the baseline, or below
the baseline, respectively. Thus `cascent(x) + cdescent(x)'
always equals `cheight(x)'. For a one-line formula like
`a + b', cascent
returns 1 and cdescent
returns 0.
For `a / b' in Big mode, cascent
returns 2 and cdescent
returns 1. The only formula for which cascent
will return zero
is `cvspace(0)' or equivalents.
The Z C (calc-user-define-composition
) command lets you
define the display format for any algebraic function. You provide a
formula containing a certain number of argument variables on the stack.
Any time Calc formats a call to the specified function in the current
language mode and with that number of arguments, Calc effectively
replaces the function call with that formula with the arguments
replaced.
Calc builds the default argument list by sorting all the variable names that appear in the formula into alphabetical order. You can edit this argument list before pressing RET if you wish. Any variables in the formula that do not appear in the argument list will be displayed literally; any arguments that do not appear in the formula will not affect the display at all.
You can define formats for built-in functions, for functions you have defined with Z F (see section Programming with Formulas), or for functions which have no definitions but are being used as purely syntactic objects. You can define different formats for each language mode, and for each number of arguments, using a succession of Z C commands. When Calc formats a function call, it first searches for a format defined for the current language mode (and number of arguments); if there is none, it uses the format defined for the Normal language mode. If neither format exists, Calc uses its built-in standard format for that function (usually just `func(args)').
If you execute Z C with the number 0 on the stack instead of a formula, any defined formats for the function in the current language mode will be removed. The function will revert to its standard format.
For example, the default format for the binomial coefficient function `choose(n, m)' in the Big language mode is
n ( ) m
You might prefer the notation,
C n m
To define this notation, first make sure you are in Big mode, then put the formula
choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
on the stack and type Z C. Answer the first prompt with
choose
. The second prompt will be the default argument list
of `(C m n)'. Edit this list to be `(n m)' and press
RET. Now, try it out: For example, turn simplification
off with m O and enter `choose(a,b) + choose(7,3)'
as an algebraic entry.
C + C a b 7 3
As another example, let's define the usual notation for Stirling numbers of the first kind, `stir1(n, m)'. This is just like the regular format for binomial coefficients but with square brackets instead of parentheses.
choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
Now type Z C stir1 RET, edit the argument list to `(n m)', and type RET.
The formula provided to Z C usually will involve composition functions, but it doesn't have to. Putting the formula `a + b + c' onto the stack and typing Z C foo RET RET would define the function `foo(x,y,z)' to display like `x + y + z'. This "sum" will act exactly like a real sum for all formatting purposes (it will be parenthesized the same, and so on). However it will be computationally unrelated to a sum. For example, the formula `2 * foo(1, 2, 3)' will display as `2 (1 + 2 + 3)'. Operator precedences have caused the "sum" to be written in parentheses, but the arguments have not actually been summed. (Generally a display format like this would be undesirable, since it can easily be confused with a real sum.)
The special function eval
can be used inside a Z C
composition formula to cause all or part of the formula to be
evaluated at display time. For example, if the formula is
`a + eval(b + c)', then `foo(1, 2, 3)' will be displayed
as `1 + 5'. Evaluation will use the default simplifications,
regardless of the current simplification mode. There are also
evalsimp
and evalextsimp
which simplify as if by
a s and a e (respectively). Note that these "functions"
operate only in the context of composition formulas (and also in
rewrite rules, where they serve a similar purpose; see section Rewrite Rules). On the stack, a call to eval
will be left in
symbolic form.
It is not a good idea to use eval
except as a last resort.
It can cause the display of formulas to be extremely slow. For
example, while `eval(a + b)' might seem quite fast and simple,
there are several situations where it could be slow. For example,
`a' and/or `b' could be polar complex numbers, in which
case doing the sum requires trigonometry. Or, `a' could be
the factorial `fact(100)' which is unevaluated because you
have typed m O; eval
will evaluate it anyway to
produce a large, unwieldy integer.
You can save your display formats permanently using the Z P command (see section Creating User Keys).
Syntax tables do for input what compositions do for output: They allow you to teach custom notations to Calc's formula parser. Calc keeps a separate syntax table for each language mode.
(Note that the Calc "syntax tables" discussed here are completely unrelated to the syntax tables described in the Emacs manual.)
The Z S (calc-edit-user-syntax
) command edits the
syntax table for the current language mode. If you want your
syntax to work in any language, define it in the normal language
mode. Type M-# M-# to finish editing the syntax table, or
M-# x to cancel the edit. The m m command saves all
the syntax tables along with the other mode settings;
see section General Mode Commands.
Parsing is the process of converting a raw string of characters, such as you would type in during algebraic entry, into a Calc formula. Calc's parser works in two stages. First, the input is broken down into tokens, such as words, numbers, and punctuation symbols like `+', `:=', and `+/-'. Space between tokens is ignored (except when it serves to separate adjacent words). Next, the parser matches this string of tokens against various built-in syntactic patterns, such as "an expression followed by `+' followed by another expression" or "a name followed by `(', zero or more expressions separated by commas, and `)'."
A syntax table is a list of user-defined syntax rules, which allow you to specify new patterns to define your own favorite input notations. Calc's parser always checks the syntax table for the current language mode, then the table for the normal language mode, before it uses its built-in rules to parse an algebraic formula you have entered. Each syntax rule should go on its own line; it consists of a pattern, a `:=' symbol, and a Calc formula with an optional condition. (Syntax rules resemble algebraic rewrite rules, but the notation for patterns is completely different.)
A syntax pattern is a list of tokens, separated by spaces. Except for a few special symbols, tokens in syntax patterns are matched literally, from left to right. For example, the rule,
foo ( ) := 2+3
would cause Calc to parse the formula `4+foo()*5' as if it were `4+(2+3)*5'. Notice that the parentheses were written as two separate tokens in the rule. As a result, the rule works for both `foo()' and `foo ( )'. If we had written the rule as `foo () := 2+3', then Calc would treat `()' as a single, indivisible token, so that `foo( )' would not be recognized by the rule. (It would be parsed as a regular zero-argument function call instead.) In fact, this rule would also make trouble for the rest of Calc's parser: An unrelated formula like `bar()' would now be tokenized into `bar ()' instead of `bar ( )', so that the standard parser for function calls would no longer recognize it!
While it is possible to make a token with a mixture of letters and punctuation symbols, this is not recommended. It is better to break it into several tokens, as we did with `foo()' above.
The symbol `#' in a syntax pattern matches any Calc expression. On the righthand side, the things that matched the `#'s can be referred to as `#1', `#2', and so on (where `#1' matches the leftmost `#' in the pattern). For example, these rules match a user-defined function, prefix operator, infix operator, and postfix operator, respectively:
foo ( # ) := myfunc(#1) foo # := myprefix(#1) # foo # := myinfix(#1,#2) # foo := mypostfix(#1)
Thus `foo(3)' will parse as `myfunc(3)', and `2+3 foo' will parse as `mypostfix(2+3)'.
It is important to write the first two rules in the order shown, because Calc tries rules in order from first to last. If the pattern `foo #' came first, it would match anything that could match the `foo ( # )' rule, since an expression in parentheses is itself a valid expression. Thus the `foo ( # )' rule would never get to match anything. Likewise, the last two rules must be written in the order shown or else `3 foo 4' will be parsed as `mypostfix(3) * 4'. (Of course, the best way to avoid these ambiguities is not to use the same symbol in more than one way at the same time! In case you're not convinced, try the following exercise: How will the above rules parse the input `foo(3,4)', if at all? Work it out for yourself, then try it in Calc and see.)
Calc is quite flexible about what sorts of patterns are allowed. The only rule is that every pattern must begin with a literal token (like `foo' in the first two patterns above), or with a `#' followed by a literal token (as in the last two patterns). After that, any mixture is allowed, although putting two `#'s in a row will not be very useful since two expressions with nothing between them will be parsed as one expression that uses implicit multiplication.
As a more practical example, Maple uses the notation `sum(a(i), i=1..10)' for sums, which Calc's Maple mode doesn't recognize at present. To handle this syntax, we simply add the rule,
sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
to the Maple mode syntax table. As another example, C mode can't read assignment operators like `++' and `*='. We can define these operators quite easily:
# *= # := muleq(#1,#2) # ++ := postinc(#1) ++ # := preinc(#1)
To complete the job, we would use corresponding composition functions and Z C to cause these functions to display in their respective Maple and C notations. (Note that the C example ignores issues of operator precedence, which are discussed in the next section.)
You can enclose any token in quotes to prevent its usual interpretation in syntax patterns:
# ":=" # := becomes(#1,#2)
Quotes also allow you to include spaces in a token, although once again it is generally better to use two tokens than one token with an embedded space. To include an actual quotation mark in a quoted token, precede it with a backslash. (This also works to include backslashes in tokens.)
# "bad token" # "/\"\\" # := silly(#1,#2,#3)
This will parse `3 bad token 4 /"\ 5' to `silly(3,4,5)'.
The token # has a predefined meaning in Calc's formula parser; it is not legal to use `"#"' in a syntax rule. However, longer tokens that include the `#' character are allowed. Also, while `"$"' and `"\""' are allowed as tokens, their presence in the syntax table will prevent those characters from working in their usual ways (referring to stack entries and quoting strings, respectively).
Finally, the notation `%%' anywhere in a syntax table causes the rest of the line to be ignored as a comment.
Different operators are generally assigned different precedences. By default, an operator defined by a rule like
# foo # := foo(#1,#2)
will have an extremely low precedence, so that `2*3+4 foo 5 == 6' will be parsed as `(2*3+4) foo (5 == 6)'. To change the precedence of an operator, use the notation `#/p' in place of `#', where p is an integer precedence level. For example, 185 lies between the precedences for `+' and `*', so if we change this rule to
#/185 foo #/186 := foo(#1,#2)
then `2+3 foo 4*5' will be parsed as `2+(3 foo (4*5))'. Also, because we've given the righthand expression slightly higher precedence, our new operator will be left-associative: `1 foo 2 foo 3' will be parsed as `(1 foo 2) foo 3'. By raising the precedence of the lefthand expression instead, we can create a right-associative operator.
See section Composition Basics, for a table of precedences of the standard Calc operators. For the precedences of operators in other language modes, look in the Calc source file `calc-lang.el'.
To match a function with a variable number of arguments, you could write
foo ( # ) := myfunc(#1) foo ( # , # ) := myfunc(#1,#2) foo ( # , # , # ) := myfunc(#1,#2,#3)
but this isn't very elegant. To match variable numbers of items, Calc uses some notations inspired regular expressions and the "extended BNF" style used by some language designers.
foo ( { # }*, ) := apply(myfunc,#1)
The token `{' introduces a repeated or optional portion. One of the three tokens `}*', `}+', or `}?' ends the portion. These will match zero or more, one or more, or zero or one copies of the enclosed pattern, respectively. In addition, `}*' and `}+' can be followed by a separator token (with no space in between, as shown above). Thus `{ # }*,' matches nothing, or one expression, or several expressions separated by commas.
A complete `{ ... }' item matches as a vector of the
items that matched inside it. For example, the above rule will
match `foo(1,2,3)' to get `apply(myfunc,[1,2,3])'.
The Calc apply
function takes a function name and a vector
of arguments and builds a call to the function with those
arguments, so the net result is the formula `myfunc(1,2,3)'.
If the body of a `{ ... }' contains several `#'s (or nested `{ ... }' constructs), then the items will be strung together into the resulting vector. If the body does not contain anything but literal tokens, the result will always be an empty vector.
foo ( { # , # }+, ) := bar(#1) foo ( { { # }*, }*; ) := matrix(#1)
will parse `foo(1,2,3,4)' as `bar([1,2,3,4])', and `foo(1,2;3,4)' as `matrix([[1,2],[3,4]])'. Also, after some thought it's easy to see how this pair of rules will parse `foo(1,2,3)' as `matrix([[1,2,3]])', since the first rule will only match an even number of arguments. The rule
foo ( # { , # , # }? ) := bar(#1,#2)
will parse `foo(2,3,4)' as `bar(2,[3,4])', and `foo(2)' as `bar(2,[])'.
The notation `{ ... }?.' (note the trailing period) works just the same as regular `{ ... }?', except that it does not count as an argument; the following two rules are equivalent:
foo ( # , { also }? # ) := bar(#1,#3) foo ( # , { also }?. # ) := bar(#1,#2)
Note that in the first case the optional text counts as `#2', which will always be an empty vector, but in the second case no empty vector is produced.
Another variant is `{ ... }?$', which means the body is optional only at the end of the input formula. All built-in syntax rules in Calc use this for closing delimiters, so that during algebraic entry you can type [sqrt(2), sqrt(3 RET, omitting the closing parenthesis and bracket. Calc does this automatically for trailing `)', `]', and `>' tokens in syntax rules, but you can use `{ ... }?$' explicitly to get this effect with any token (such as `"}"' or `end'). Like `{ ... }?.', this notation does not count as an argument. Conversely, you can use quotes, as in `")"', to prevent a closing-delimiter token from being automatically treated as optional.
Calc's parser does not have full backtracking, which means some patterns will not work as you might expect:
foo ( { # , }? # , # ) := bar(#1,#2,#3)
Here we are trying to make the first argument optional, so that `foo(2,3)' parses as `bar([],2,3)'. Unfortunately, Calc first tries to match `2,' against the optional part of the pattern, finds a match, and so goes ahead to match the rest of the pattern. Later on it will fail to match the second comma, but it doesn't know how to go back and try the other alternative at that point. One way to get around this would be to use two rules:
foo ( # , # , # ) := bar([#1],#2,#3) foo ( # , # ) := bar([],#1,#2)
More precisely, when Calc wants to match an optional or repeated part of a pattern, it scans forward attempting to match that part. If it reaches the end of the optional part without failing, it "finalizes" its choice and proceeds. If it fails, though, it backs up and tries the other alternative. Thus Calc has "partial" backtracking. A fully backtracking parser would go on to make sure the rest of the pattern matched before finalizing the choice.
It is possible to attach a condition to a syntax rule. For example, the rules
foo ( # ) := ifoo(#1) :: integer(#1) foo ( # ) := gfoo(#1)
will parse `foo(3)' as `ifoo(3)', but will parse
`foo(3.5)' and `foo(x)' as calls to gfoo
. Any
number of conditions may be attached; all must be true for the
rule to succeed. A condition is "true" if it evaluates to a
nonzero number. See section Logical Operations, for a list of Calc
functions like integer
that perform logical tests.
The exact sequence of events is as follows: When Calc tries a rule, it first matches the pattern as usual. It then substitutes `#1', `#2', etc., in the conditions, if any. Next, the conditions are simplified and evaluated in order from left to right, as if by the a s algebra command (see section Simplifying Formulas). Each result is true if it is a nonzero number, or an expression that can be proven to be nonzero (see section Declarations). If the results of all conditions are true, the expression (such as `ifoo(#1)') has its `#'s substituted, and that is the result of the parse. If the result of any condition is false, Calc goes on to try the next rule in the syntax table.
Syntax rules also support let
conditions, which operate in
exactly the same way as they do in algebraic rewrite rules.
See section Other Features of Rewrite Rules, for details. A let
condition is always true, but as a side effect it defines a
variable which can be used in later conditions, and also in the
expression after the `:=' sign:
foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
The dnumint
function tests if a value is numerically an
integer, i.e., either a true integer or an integer-valued float.
This rule will parse foo
with a half-integer argument,
like `foo(3.5)', to a call like `hifoo(4.)'.
The lefthand side of a syntax rule let
must be a simple
variable, not the arbitrary pattern that is allowed in rewrite
rules.
The matches
function is also treated specially in syntax
rule conditions (again, in the same way as in rewrite rules).
See section Matching Commands. If the matching pattern contains
meta-variables, then those meta-variables may be used in later
conditions and in the result expression. The arguments to
matches
are not evaluated in this situation.
sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
This is another way to implement the Maple mode sum
notation.
In this approach, we allow `#2' to equal the whole expression
`i=1..10'. Then, we use matches
to break it apart into
its components. If the expression turns out not to match the pattern,
the syntax rule will fail. Note that Z S always uses Calc's
normal language mode for editing expressions in syntax rules, so we
must use regular Calc notation for the interval `[b..c]' that
will correspond to the Maple mode interval `1..10'.
Modes
Variable
The m g (calc-get-modes
) command pushes onto the stack
a vector of numbers that describes the various mode settings that
are in effect. With a numeric prefix argument, it pushes only the
nth mode, i.e., the nth element of this vector. Keyboard
macros can use the m g command to modify their behavior based
on the current mode settings.
The modes vector is also available in the special variable
Modes
. In other words, m g is like s r Modes RET.
It will not work to store into this variable; in fact, if you do,
Modes
will cease to track the current modes. (The m g
command will continue to work, however.)
In general, each number in this vector is suitable as a numeric prefix argument to the associated mode-setting command. (Recall that the ~ key takes a number from the stack and gives it as a numeric prefix to the next command.)
The elements of the modes vector are as follows:
For example, the sequence M-1 m g RET 2 + ~ p increases the precision by two, leaving a copy of the old precision on the stack. Later, ~ p will restore the original precision using that stack value. (This sequence might be especially useful inside a keyboard macro.)
As another example, M-3 m g 1 - ~ DEL deletes all but the oldest (bottommost) stack entry.
Yet another example: The HP-48 "round" command rounds a number to the current displayed precision. You could roughly emulate this in Calc with the sequence M-5 m g 10000 % ~ c c. (This would not work for fixed-point mode, but it wouldn't be hard to do a full emulation with the help of the Z [ and Z ] programming commands. See section Conditionals in Keyboard Macros.)
This section is a summary of all symbols that can appear on the Calc mode line, the highlighted bar that appears under the Calc stack window (or under an editing window in Embedded Mode).
The basic mode line format is:
--%%-Calc: 12 Deg other modes (Calculator)
The `%%' is the Emacs symbol for "read-only"; it shows that regular Emacs commands are not allowed to edit the stack buffer as if it were text.
The word `Calc:' changes to `CalcEmbed:' if Embedded Mode is enabled. The words after this describe the various Calc modes that are in effect.
The first mode is always the current precision, an integer.
The second mode is always the angular mode, either Deg
,
Rad
, or Hms
.
Here is a complete list of the remaining symbols that can appear on the mode line:
Alg
Alg[(
Alg*
Symb
Matrix
Matrixn
Scalar
Polar
Frac
Inf
+Inf
NoSimp
NumSimp
BinSimpw
AlgSimp
ExtSimp
UnitSimp
Bin
Oct
Hex
Radixn
Zero
Big
Flat
Unform
C
Pascal
Fortran
TeX
Eqn
Math
Maple
Normn
Fixn
Sci
Scin
Eng
Engn
Leftn
Right
Rightn
Center
Centern
Widn
Wide
Break
Save
Local
LocEdit
LocPerm
Global
Manual
Graph
Sel
Dirty
Inv
Hyp
Keep
Narrow
In addition, the symbols Active
and ~Active
can appear
as minor modes on an Embedded buffer's mode line. See section Embedded Mode.
Go to the previous, next section.