MathPad Manual


MathPad

Version 2.6.5
MathPad is a general purpose graphing scientific calculator for the Macintosh. It uses a text window rather than simulating buttons on a hand held calculator. This live scratchpad interface allows you to see and edit your entire calculation.

This manual lists the basic capabilities of MathPad mainly by giving short examples. The "Examples" folder included with the distribution contains some longer examples and utility functions. These examples show how to implement such things as equation solving, curve fitting, vector calculations and numerical solution of differential equations.

Table of contents


Using MathPad as a calculator

MathPad may be used as a calculator simply by typing in numbers and operators. When the ENTER key is hit, each line is evaluated and the results are inserted into the text.

2*(3+4):14.0

MathPad inserts the ":" and the result "14.0". A status line at the bottom of the window will show a check mark to indicate that evaluation is complete. If any problems are encountered, they will be reported in the status line and the cursor will be moved to the problem in the text. You can edit and reevaluate the text at any time.

The RETURN key simply terminates a line. It does not cause any evaluation. The ENTER key is on the numeric keypad (or next to the space bar on powerbook keyboards).

An expression will be continued if the line ends with an operator

2 *
(3+4):14.0

More than one expression can be placed on a line if they are separated by semicolons.

2*3+4:10.0; 2.1*(.3+4.2):9.5

The character # may be used to reference the last result

10*234:2340.0
#+5:2345.0

Numeric Constants

Numbers may be entered in "e" format as in "12.3e-4".

Metric letter suffixes may also be used:
Suffix Multiplier
G giga 1e+9
M mega 1e+6
K kilo 1e+3
m milli 1e-3
u micro 1e-6
n nano 1e-9
p pico 1e-12
f fempto 1e-15

Hex numbers can be entered by preceding with 0x as in 0xAF23. Hex input is treated as a bit pattern for a 32-bit signed integer.

The constant pi can be entered via the menu or by typing option-p or "pi".

The constant infinity can be entered via typing option-5. The quantities positive infinity (1/0), negative infinity (-1/0) and undefined (0/0) have numeric representations and can be used in calculations.

Numeric output format can be controlled via the menu or the Preferences... dialog.

Comments

MathPad ignores text between "--" and the next RETURN.

-- This is a comment.

Large blocks of text can be commented out by using ~ characters. All text between ~ characters is ignored and can span multiple lines.

Pasted Graphics

MathPad allows graphics to be pasted into the text of the worksheet. This is intended as a way of including sketches or diagrams that help explain and document the calculation.

volume = pi*r^2 * h

h=4; r=2
volume:50.265
The graphic can be created with any draw program. Then simply copy and paste it into MathPad's text. MathPad does not provide any editing or resizing of the graphic so you must create the graphic exactly as you want it before pasting it in.

Syntax Coloring

Text styles and colors are used to highlight results, keywords and comments. The standard scheme uses red for results, blue for comments and bold for keywords. The Preferences... dialog can be used disable coloring or to change colors and styles.

If the "color while typing" option is on, coloring will be updated as you type. This local updating may not always color correctly. Coloring is updated after evaluation.

Equations and Functions

MathPad allows the user to type in equations using variables that will be given numeric values elsewhere in the text.

force=mass*accel
force:160.0
mass=5
accel=32

MathPad evaluates the entire text so numeric values can be given before or after they are used.

When MathPad cannot calculate a numeric value from the information given, it will print '?' and the name of the variable whose value is unknown.

a=b+c
d=a*4
d:? b?

MathPad does not perform algebra. The equation x=y+z (or y+z=x) tells how to compute x given y and z but MathPad does not derive any information about how to compute values for y or z from x.

Users can define their own functions. Functions differ from equations in that their parameter names refer to temporary variables that can take on different values each time the function is called.

mass=5
accel=32
Force(mass,accel)=mass*accel
Force(10,12):120.0
Force(6,8):48.0

mass*accel:160.0; -- uses the global values

In this example the parameters "accel" and "mass" are separate from the global variables "accel" and "mass". Any variables used in the definition that do not appear in the parameter list will refer to global variables.

Functions can be referenced before they are defined. All references to a function must have the same number of parameters. Multiple definitions of function names are not allowed.

Variable names can contain upper or lower case letters, digits and the underscore character. There are also a few option characters allowed:

   option-

Conditionals

The value of an expression can be made dependent on a condition.

p = -a when a < 0,
    1 when a = 0,
    a^2 otherwise

The result will be the value corresponding to the first condition in the list that evaluates true. Commas separate expressions in the list.

The keyword otherwise is optional and is used only to help readability.

The conditional follows the keyword when and may use the comparison operators (   =    !=    >    < >=    <=  ). Conditionals also use the logical operators (   and    or    not   ). The option key versions of comparison operators are also accepted. Note that in this context "=" is a comparison operator. The C style operator "==" is also accepted. The "==" form must be used for comparison in cases where the meaning would be ambiguous.

Chained relations such as: a < b < c are allowed.

The prefix operators known and unknown can be used to test if a numeric value can be calculated for the given expression. Note that a expression can be 'known' even if its value is NAN04 (not a number). NAN04 results from calculations such as 0/0.

An arithmetic expression is considered true if it is non-zero. A conditional used as an arithmetic expression has a value of 1 for true and 0 for false.

Comma separated expressions can also be used without conditionals. The result will be the first item in the list that evaluates to a numeric value.

Recursion

MathPad allows recursive function definitions. Depth of recursion is limited by available memory space. If memory runs low during evaluation, recursion is stopped.

Evaluation can also be stopped by typing Command-period.

fact(n) = 1 when n < 2, fact(n-1)*n when n > 0
fact(50):3.0e+64

Built-in Functions

MathPad has most of the usual built-in functions. Built-in functions may either be typed in or selected from the "Functions" menu.
NameFunction
abs(n)absolute value
acos(n)arccosine
asin(n)arcsine
atan(n)arctangent
atan2(y,x)4 quadrant arctangent
cos(angle)cosine
exp(n)e^n
ln(n)natural log
log(n)log base 10
rand(n)pseudo random number generator
sin(angle)sine
sprintf(format,n)convert to string
sqrt(n)square root
sum(expr,i,lo,hi)summation
tan(angle)tangent
trunc(n)truncate

The argument units for trig functions can be changed to either degrees or radians with the menu.

The value Radians can be used to do trig calculations that are independent of the degrees/radians option choice. The value of Radians is 1.0 when radians are selected and 57.3 when degrees are selected.

cos(pi*Radians):-1.0; -- -1 for either Degrees/Radians setting

The function trunc(n) returns the integer part of n.

The function sprintf(format,n) converts n to a string based on the format specification. It is similar to the C standard library function. See the separate section on strings for a detailed description.

sprintf("pi/2 is %.4f",pi/2):"pi/2 is 1.5708"

The function sum(expr,var,lower,upper) performs a summation of "expr" while incrementing the named variable between "lower" and "upper". The expression given as the first parameter is reevaluated for each step. Expressions for "lower" and "upper" are evaluated only once.

series(n) = sum(2*k-1,k,1,n)
series(9):81.0

The function rand(n) returns a random number in the range 0 to n. More than 10^9 different values are possible. A rand(0) call restarts the sequence.

Some of the built-in functions operate on arrays. Array functions are described in a later section.

XFun Plug-ins

MathPad's function menu can be extended with optional plug-in modules called XFuns. Several XFun files are included with the distribution and can be used to extend MathPad's capabilities. MathPad is distributed without XFuns installed so that users can install only the ones they need.

To install an XFun, move it to MathPad's "Active XFuns" folder. When MathPad starts up it loads all the XFuns in this folder. Installed XFuns will be added to the Functions menu and may also add items to the Help menu.

Arrays

MathPad allows general purpose arrays.

A={10,20,30} -- Defines a 3 element array.

A[2]:20.0; -- Accesses the 2nd element. Index values start at 1.
B={A,{40,50,60},A+1} -- Multidimensional array.
B:{{10.0,20.0,30.0},{40.0,50.0,60.0},{11.0,21.0,31.0}}
B[1]:{10.0,20.0,30.0}
B[1][2]:20.0
B[1,2]:20.0; -- Both forms of indexing are allowed

A[2:3]:{20.0,30.0}; -- [lo:hi] selects a sub array.
A[2:3][2:2]:{30.0}; -- consecutive selections operate on the same dimension
A[:2]:{10.0,20.0}; -- lo and/or hi may be omitted.
B[2:]:{{40.0,50.0,60.0},{11.0,21.0,31.0}}

Q[i]=i*11 --Arrays can be defined in terms of their index values.
Q[2]:22.0

The syntax "dim[n]" is used to set the number of elements for an array definition. The default index values will be 1,2,3...n. If the expression for number of elements is unknown or < 0, that dimension becomes infinite. dim[0] is equivalent to dim[1].

I[i,j] = 1 when i=j, 0   dim[3,3]
I:{{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}

Arrays may be used freely in expressions. Operations are performed on each element. Scalars are extended to contain as many elements as needed.

A+Q:{21.0,42.0,63.0}
2+A:{12.0,22.0,32.0}
log(A):{1.0,1.3,1.5}
A*Q:{110.0,440.0,990.0}; --Note: this is NOT matrix multiply

Q[A]:? A[]?; --Arrays may not be used as index values.

For large arrays only the first few elements in each dimension are printed followed by ... to indicate that there are more elements.

Q:{11.0,22.0,33.0,...}

Use the table command to show medium sized 1D or 2D arrays.

table B
       10.0       20.0       30.0
       40.0       50.0       60.0
       11.0       21.0       31.0

Defining array functions

User defined functions can return arrays. The function specifies what value to return for each index in the same manner as an array definition.

skip(ZZ,by)[i] = ZZ[i*by]

Q[i]=i*11
skip(Q,2):{22.0,44.0,66.0,...}

multiply(A,B)[i,j] = sum(A[i,k]*B[k,j],k,1,count(B)) dim[count(A),count(B[1])]

A={10,20,30}
I[i,j] = 1 when i=j, 0   dim[3,3]
multiply({A},I):{{10.0,20.0,30.0}}

A dim[] statement is used to specify the dimensions of the function return value. It is not strictly required but it should be used when the function is returning a finite sized array.

Built-in functions for arrays

count(array)count elements in an array
det(matrix)determinant of a square matrix
read(filename)read data from a file
write(filename,array)write data to a file

The count function returns information about the dimensions of the array.

A={10,20,30}
B={A,{40,50,60},A+1}
Q[i]=i*11
count(A):3.0; -- count() returns the number of array elements
count(B):3.0; -- elements in 1st dimension
count(B[1]):3.0; -- elements in 2nd dimension
count(42):0.0; -- scalar
count(Q):?;    -- infinite array

Data Files

MathPad provides read and write functions for saving results and for importing or exporting data. The read() function returns an array of values from the named data file. The data file is assumed to be in the same folder as the source document. Aliases or Mac style path names such as "Hard Disk:DataFolder:file47" are allowed.

data = read("myfile")

The write() function writes the elements of a 1D or 2D array to the named file.

write("myfile",array)

See datafiles for more information.

Strings

Text strings are used for file names and plot labels. String constants must be enclosed in double quotes. They can contain blanks or punctuation but not RETURN characters.

Variables can be defined or assigned as strings and used to specify a filename indirectly. Strings can be combined with the concatenation operator '|'.

path = "Hard Disk:DataFolder:"
f = path | "myfile"
f:"Hard Disk:DataFolder:myfile"
write(f,array)

The built-in function sprintf(format,n) can be used to convert a number to a string. See the separate section on strings for more details.

Plots

MathPad can produce simple plots by using the plot command.

Xmin=-10; Xmax=10
plot X^3

The independent variable X (upper case) is stepped between Xmin and Xmax. Various aspects of the plot can be controlled by setting plot control variables. None of the control variables are required but usually at least Xmin and Xmax are specified.

An info line at the bottom of the plot window shows the lowest and highest Y values ("Ylo" and "Yhi") calculated during the plot. Clicking the mouse on the plot will show the trace number and the X,Y value of the plotted point nearest to the click.

The variables Ymin and Ymax can be used to set the Y axis limits. If Ymin and/or Ymax are not specified MathPad will auto-range based on Ylo and Yhi.

Multiple traces can be plotted simply by adding plot statements.

Evaluation of a long plot can be stopped by typing Command-period.

MathPad can also plot data points, parametric functions, image data etc. For detailed information see the separate section on plotting,

Tables

MathPad can produce tables of numeric results using the table command. Tables are handled in the same way as plots except that the results are inserted as columns in the text window. For tables the independent variable is N and the control variables are Nmin, Nmax and Nsteps.

Multiple column tables can be produced by giving a list of expressions separated by commas.

Nmin=1; Nmax=5; Nsteps=5
table    N,       N^2,       N^3
        1.0        1.0        1.0
        2.0        4.0        8.0
        3.0        9.0       27.0
        4.0       16.0       64.0
        5.0       25.0      125.0

Nsteps is limited to 1000 to prevent accidents from inserting huge amounts of text. Use the write() function for large tables.

Do not add any text to the output columns because the table command will not be able to properly delete the table before reevaluating.

The output format is right justified in a width of 8 spaces with tabs separating multiple columns. This gives nice looking right justified columns as long as the font is mono-spaced and the number being output takes less than 8 characters. A tab is inserted between columns so that the table can be copied and pasted into a spreadsheet.

The special variable Nspaces can be used to change the output field width (default is Nspaces=8). If Nspaces is set larger than the number of spaces needed to display the number, the extra positions are filled with leading spaces. If it is less, it has no effect. Nspaces can be set to anything between -60 and +60. Zero gives tab separated values with no spaces. Negative numbers give left justified fields with trailing spaces.

A special variable Tabwidth has been added to allow changing the tab width in points (1 to 900) from within the source text. Tabwidth= appearing anywhere sets the value for the entire document. It has the same effect as setting the tab width via the Preferences... dialog.

If table is used with a single expression that is a 1D or 2D array, the array elements will be printed out. The values of Nmin,Nmax and Nsteps are ignored.

Programing

The basic MathPad language is intended to be mathematical rather than procedural. Equations can be written and evaluated in a natural way that does not really require any programing. There are, however, some handy numerical algorithms that do require some procedural operations.

Assignment operator

The assignment operator := evaluates the right hand side expression and replaces any previous definition of the left hand variable with the result. This differs from = which gives a single definition of how to calculate the value of a variable. Accessing an assigned variable gives its current value and does not reevaluate the expression. Assigned variables do not necessarily have the same value everywhere in the text.

aa:3.0
aa:=aa+2:
aa:5.0
aa:={1,2,aa}:
aa:{1.0,2.0,5.0}
aa[2]:=7.6:
aa:{1.0,7.6,5.0}

Assignments can only be done to simple global variables.

Entire arrays may be assigned (if they are finite).

Assignments to array elements are permitted in restricted cases. A single value can be assigned to an element of an array that has previously been initialized by assignment.

Iteration

The while operator can be used to evaluate an expression repeatedly. The condition is checked before each evaluation. Note: i and m are global.

factorial(n) = i:=1,m:=1,(i:=i+1,m:=m*i) while i < n, m
factorial(100):9.3e+157

See the example file Programing.mp for more information.

Include Statement

Definitions in one file can be shared by other files. A document containing the command

   include "filename"

will open and read definitions from the named file. The folder of the source document will be searched first and then the folder containing the MathPad application. Full or relative path names are allowed. You may want to make a folder containing your favorite include files and put it in MathPad's folder. Then any document can access them with a short relative path name.

A window is opened for each included file. This file can be viewed and edited like any other MathPad document. Any changes made will be seen by the parent document when the parent is reevaluated. Include files should contain only definitions. They can contain other include commands.

Technical Details

Once you have used MathPad for awhile you will probably have some ideas about how you would like to set it up. The Preferences... dialog can be used to control many of MathPads features. Also see the section on customizing

File formats

MathPad documents are generic TEXT files. All MathPad specific information is stored in the resource fork. The resource fork is not modified until the file is saved. TEXT files created by other applications may be opened by MathPad and vice versa. MathPad automatically converts line terminators from UNIX or PC files to Mac format when it reads in a document.

Any graphics imbedded in Mathpad source files will be preserved only when the file is viewed and saved by MathPad. The file can still be read by other text editors but the graphics will not be shown.

MathPad will open generic text files in OS-X if they are named with a .txt or .mp extension. Adding the extension .mp will tell the Finder to treat the file as a MathPad document.

Files created by MathPad will be recognized and do not need to use extensions. The .mp extension may be useful for files created by other applications or files that have been transferred from other systems.

Data files can be either TEXT or binary. See datafiles.

Background computation

Clicking in another application's window or the desktop will switch MathPad to the background even when it is busy with a computation. MathPad will continue computation in the background. In some cases updating of the plot window will be deferred until MathPad is moved to the foreground.

Incremental evaluation

MathPad usually reevaluates the entire document when the enter key is pressed. This allows you to edit anything anywhere in the text and have everything updated properly. It does try to take advantage of the fact that when text is added at the very end of the document no changes are needed in the part of the document that has already been evaluated.

MathPad will hold off on reevaluating text that has been successfully evaluated. However, any edit other than at the very end of the document will cause the entire document to be reevaluated on the next enter. A ... is shown on the status line when a partial evaluation is pending.

If you wish to force a full reevaluation you can use command-R or hit enter twice.

AppleEvents

MathPad supports a few custom AppleEvents so it can be controlled by AppleScript etc. See Using AppleEvents.

Distribution

MathPad is copyright 1993-2006 by Mark Widholm. All rights reserved.

MathPad can be used and distributed for free. Selling it for profit without my permission is forbidden. If you wish to sell any software collection or product bundle containing MathPad contact me for permission.

If you use MathPad, send me some e-mail. I can notify you of any known bugs, updates etc.

Send comments, questions, suggestions and bug reports to:

Mark.Widholm@UNH.edu

Let me know if you are interested in seeing more examples or if you have a MathPad example that others might be interested in seeing. Check out the MathPad web page http://pubpages.unh.edu/~mwidholm/MathPad/ for more examples and XFuns.