MathPad

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.

**What's New in Version 3.04**

- Using MathPad as a calculator

- Equations and Functions

- Arrays
- Plots
- Plotting Functions
- Plotting Arrays
- Plotting Surfaces
- Graphics File Overlay
- Multiple Axes
- Log Axes
- Plot Shape
- Saving and printing
**Plot Control Summary**

- Tables
- Programing
- Technical Details

- Frequently Asked Questions
- Distribution

MathPad may be used as a calculator simply by typing in numbers and operators. When the RUN button is pressed, 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. Key equivalents for the RUN button are fn-return, command-return or the single key \.

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

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

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.

Text colors are used to highlight results, keywords and comments. MathPad uses red for results, blue for comments and brown for keywords. The Format menu can be used disable coloring.

Coloring will be updated as you type. This local updating may not always color correctly. Coloring is updated after evaluation.

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

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.

MathPad allows recursive function definitions. Depth of recursion is limited to 10,000 to prevent infinite recursion.

Evaluation can also be stopped by the STOP button or by typing Command-period.

```
``````
fact(n) = 1
```**when** n < 2, fact(n-1)*n **when** n > 0

fact(50):3.0e+64

MathPad has most of the usual built-in functions. Built-in functions may either be typed in or selected from the "Functions" window.

The Functions window can be accessed either via "Show Functions" in the Edit menu or by "Show Function List" in the Help menu. This window can be used as a reference list of all the available functions and defined variables. Double click on the function name to select its text and then drag it or copy and paste it into your text document.

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

The defined constant **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 basic functions operate on arrays.
Array functions are described in a later section.

MathPad also includes a library of optional functions and can be used to extend MathPad's capabilities. MathPad is distributed with these functions disabled so that users can enable only the ones they need.

To enable a function check its enable column in the Functions window. You may be tempted to just enable everything. This will work, but there might be a small performance penalty and it will reserve many symbol names.

Many optional functions provide example help documents. If you click of the (?) button, a MathPad document will open showing more information about usage of the function. If you want to try the function be sure to enable it first.

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

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.

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

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. Absolute or relative path names are also 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.

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 = "./datafiles/"
```

f = path | "file3"

f:"./datafiles/file3"

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

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,

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

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.

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.

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.

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.

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 Documents/MathPad/. Full or relative path names are allowed. You may want to make a folder containing your favorite include files and put it in Documents/MathPad/. 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.

MathPad documents are standard Rich Text rtf files. Plain text or rtf files created by other applications may be opened by MathPad and vice versa.

MathPad will open generic text files either by dropping them onto the dock icon or or by adding a .mp extension. Adding the extension .mp will tell the Finder to treat the file as a MathPad document.

MathPad allows the option of saving as plain text. However, this will lose formatting information and MathPad document options. Plain text may be useful for exporting to other applications or for typing in data files.

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

MathPad is copyright 1993-2012 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 have a MathPad example that others might be interested in seeing. Check out the MathPad web page http://pubpages.unh.edu/~mwidholm/MathPad/ .