The Super Calculator

William M. MacDonald © 1999

Numerical Calculations

Arithmetic Operations

User			Internal

      	a + b   			Plus[ a, b ]
       	a  b or a * b    		Times[ a,b ]
	- b			Times[ - 1, a ]
      	a- b       		Plus[ a,Times[ -1, b ]]
       	a ^ n                     	Power[ a, n ]
       	a/ b                     		Times[a, Power[ b, -1 ]
       	a!                       		Factorial[ a ]

FullForm[a/b]

The order of precedence for algebraic operators is the following:
    ^ / *  + -

The order of precedence is the order in which operations in an expressiion are carried out.  For example,  in this expression
           3^4 5
the 3 will be raised to the fourth power and the result will be multiplied by 5.

The arithmetic operations are Listable; they operate on lists element-by-element.

{a, b, c} + {e, f, g}

Exercises

1. Enter and evaluate each of the following expressions, noting the effect of the order of  precedence of arithmetic operations and the use of parentheses.
             a^b c   
          	a^(b c)
	a b + c

2. A space between two numbers or symbols stands for multiplication as in mathematics. The multiplication sign * used in procedural programming languages for multiplication is accepted, but  especially when working with symbols, your notebook will look more like computer code than mathematics.  Evaluate the expression:
              a*(b*c - e*f*g/h)
You wil see from the output that Mathematica doesn't like this style.

3. Evaluate each of the following expressions and explain the results.
   x  {a, b, c, d} 
   x^{a, b, c, d}
   {a, b, c, d} / {e, f, g, h}
   {a, b, c, d}  {e, f, g, h}

4. Land measurement in the United States uses a unit called the section  that is one square mile.  There are 640 acres in a section.   How many square feet are there in one acre?

5. Room temperatures are commonly set at about 68 degrees Fahrenheit for comfort.  Temperatures elsewhere in the world are quoted in degrees Celsius.  On a Fahrenheit thermometer water freezes at 32 degrees and boils at 212 degrees.  On a Celsius thermometer water freezes at 0 degrees and boils at 100 degrees.  What is the Celsius temperature in a room set at 68 degrees Fahrenheit?

Delimiters

Delimiters are symbols used to put boundaries around expressions and indicate how they are are to be evaluated.

parentheses 		grouping        		(a+b)c                      
brackets 		argument		h[ x ]        
braces          		list       			{a,b,c}
double brackets    	indexing       		 {a,b,c} [[ 2 ]]      
quotes			strings  		Print["Bill"] 
semicolons		expressions		u=Sin[v]; w=Cos[u];
commas		arguments		h [ x , y ]

Parentheses

Parentheses are used to group terms to control the order of evaluation.
23.2(1.23+4.56)

Never use parentheses to enclose arguments, as in conventional mathematical notation, that is ambiguous.  For example, in this expression
		r ((x^2) + y)
is r a function with the argument in parentheses, or is r a variable multiplying the expression in parentheses?  You may need to read a large document where the expression appears to interpret this expression.  A symbolic program must do the same. Using square brackets for function arguments simplifies and speeds evaluation.

Brackets

Square brackets are used only to enclose the arguments.  They can not be used for grouping, as in conventional mathematical notation.

Sin[1.2]

Braces

Braces are used to enclose a list of objects.  The list is the only storage unit in Mathematica, but a list can hold anything: numbers, symbols, names, and lists. Here is an example.      
	{"Tom", x, 1.2, 1.3, (x^2) , y, {3.2,  2.4,  5.6} }
A list can be a vector,
	{1.2, 3.4, 5.6}
a matrix,
	{{1.2, 3.4, 5.6},{4.5, 6.7, 8.9}, {3.0, 4.2, 5.6}}
or a data set.
	{{1.2, 3.2}, {3.4, 5.6}, ....}

Double-brackets

Double-brackets are used to index into elements of a list.

{"Tom", x, (x^2), 
        y, {3.2, 2.4, 
          5.6}}[[1]]

{"Tom", x, (x^2), y, {3.2, 2.4, 5.6}}[[5, 
      2]]

Semicolons

Semicolons are used to create "compound" expressions consisting of two or more expressions separated by semicolons.

x  =  (a^2);   y  =  1/a;  z  =  x  -  y

Terminating any expression in an input cell suppresses the display of the result of evaluating that expression.  Therefore,  only the result of evaluating the last expression was displayed.  If several expressions are placed in an input cell,  the evaluation of each expression will produce an output cell.

x  =  (a^2)
y  =  1/a 
z  =  x  -  y

This wastes space in your notebook and is very inelegant.  Instead, place the expressions in braces, like this.

{x = (a^2),  y = 1/a,  z = x - y}

Commas

Comma are used to separate arguments.  This is obvious when the arguments are single expressions, as here.

ArcTan[3.2 ,  - 4.5]

However, each argument can be a compound expression.   The symbol Do[expr , iterator] for iterative calculations accepts just two arguments.   The first argument is usually a compound expression; the second argument specifies the iteration.  A Do loop to calculate and display values of  a complicated function could look like this.

Do[x  = N[ n π/100];  y = N[Exp[-x] Tan[x]]; 
      Print[x, "  ", y], {n,  0,  5}]

The first argument is a compound expression separated from the iterator by a comma.

Mathematical Notation

You can typeset expressions in a notation closely resembling conventional mathermatical notation.  A simple introduction to using mathematical notation is given in Section 1.1.7 where you will learn about using a "palette" as well as typing Greek letters, powers, etc.  Note that there is a certain logic to the scheme developed for typing symbols.  For example, the standard notation for a power in symbolic algebra programs is 
		x^2
and this is accepted by Mathematica.  Note that you enter the caret by using shift-6 on the keyboard.  To typeset this as x raised to a power use ctrl-6 instead.  As you do this you will see a shaded area cover the x and a superscript that is a box enclosing a black square. As you type "2" it replaces the box.  To return to "ground" hit the right cursor key.  If this is just the first part of a mathematical expression continue typing and the shaded area will grow as you do so.   The correct spacing will automatically be entered before and after symbols and a mathematical font will be used.  When you are finished and want to leave the shaded area, hit the right cursor key.  You will then see something like this.
	(x^2) - 2 x y + (y^2)
To go back into an expression to change it, place the cursor just in front (behind) the expression and start hitting the forward (backward) cursor key.  You will see the shaded area reappear and the insertion point will move all the way through the expression, upward into superscripts and downward into subscripts.
	You can read more about the use of mathematical notation in Section 1.10.  For examples of typesetting, look through the topics in the "Formula Gallery".   The contents are display in CG.1 .

Constants

A number of constants are provided in Mathematica.  These are most commonly used.

Pi    			π                                        
	E			basis of natural logarithms
	Degree			π / 180
	GoldenRatio		( 1 + (Sqrt[5]) )/ 2

Numerical Conversion

N [ integer ] 			approximation to six digits
N [ integer, n ]			approximation to n digits
Round [ real ] 			integer closest to real	
Ceiling [ real ] 			smallest integer ≥ real
Floor [ real ]			greatest integer ≤ real
Rationalize [ real ]		rational number approximation
Re [ complex ]      		real part of complex
Im [ complex ]             		imaginary part of complex
Abs [ complex ]		absolute value of complex
Arg [  complex ]		argument of complex
ComplexExpand[ complex]	Re[ complex ] + I Im[ complex ]
Conjugate[ complex  ]		conjugate

Integer arguments or the use of precisely defined constants like π can lead to results of arbitrarily high precision.  Unless approximate answers are requested using N, Mathematica will not transform the input expression into an approximate output.

{Sin[3] ,  Sin [ 3 ] // N ,  Sin [ π/8 ], 
      Sin [ π /8] // N}

Mathematica is very happy to work with complex numbers.  In fact, in symbolic calculations it always assumes that every variable is complex unless instructed otherwise.  Complex numbers contain I, which is the symbol for the square root of -1. You can apply any arithmetic operation to complex numbers.

Ceiling[ π ]

Exercises

Built-in Functions

Almost every function used in science or engineering is available in Mathematica.

Elementary functions

Here are the elementary functions that you are most likely to use everyday.

Sqrt                      		square root
Exp,E				basis of natural logarithms
Log                       		natural logarithm
Abs                       		absolute value
Sin,Cos,Tan              	 	trigonometric functions
Csc, Sec
ArcSin, ArcCos,ArcTan     	inverse trigonometric functions
ArcCsc, ArcSec
Sinh,Cosh,Tanh            		hyperbolic functions
Csch, Sech
ArcSinh,ArcCosh,ArcTanh   	inverse hyperbolic functions
ArcCsch, ArcSech

Exercises

Special functions

And here are some special functions that you will be using in this course.

BesselJ			(Subscript[J, n])	regular Bessel functions
LegendreP			(Subscript[P, n])	Legendre polynomials
HermiteH			(Subscript[H, n])	Hermite polynomials
Laguerre			(Subscript[L, n])	Laguerre polynomials
SphericalHarmonicY		(Subscript[Y, l, m])	Spherical harmonics

Prefactor, postfactor, and infix notation

f [ x ]           		function notation
       f @ x          		prefactor notation
       x // f         		postfactor notation
       g [ x, y ]         	function of two variables
       x ~ g ~ y          	infix notation

Exercise

Listable functions

Most expressions based on built-in Mathematica functions are Listable, meaning that they operate on a list element-by-element.  Substituting a list of values for a  variable while evaluating an expression will give a corresponding list of values for the expression.  Many calculations can easily be done without using explicit looping by taking advantage of this attribute.  
	To take advantage of this attribute we need to have an easy way to make a list.  This is provided by Range.

Range[end ]			{1,2,..., last ≤ end}
Range[start,end]		{start, start+1,..., last ≤ end}
Range[start,end,step]		{start, start+step,..., last ≤ end}

Range[0.1, 0.9, 0.2]

Arithmetic operations provide the simplest illustrations of the Listable property.

a Range[5]

Make a list of angles in degrees instead of radians.

Degree Range[0, 90, 10]

Create a list of squared numbers.

Range[10]^2

Even the exponent of a symbol can be a list.

(x^Range)[0, 10]

Trigonometric functions are also listable so the argument can be a list.

Sin[Range[0, 90, 10] Degree]

Apply N as a postfactor to obtain numerical values.

Sin[Range[0, 90, 10] Degree] // N

Substitution can be used to make a table.

({x, Sin[x Degree]} /. x ->  Range[0, 90, 10]) // 
      N

Since a list was substituted into each element of a list, the result is a list-of-lists.  Use Transpose to pair angles with values.

SineTable = ({x, Sin[x Degree]} /. 
              x ->  Range[0, 90, 10]) // N // Transpose

And now, use TableForm to display the result as a table.

TableForm[SineTable, 
      TableHeadings -> {None, {"Degrees", "Sine"}}]

Note that TableHeadings can use two lists, the first for rows and the second for columns.  Using None for the first list specified that there were no labels for the rows.

Exercises

Plotting Functions

Graphics facilities include tools for making 2-dimensional and 3-dimensional representations of functions.

2-D Plotting

The functions commonly used for 2-D plots are the following:

Plot
	ContourPlot
	ParametricPlot
	ListPlot

Plot[x^2 - x , {x,0, 5}];

Here a list was used as an iterator that specifies the (1) parameter to be varied, (2) its starting value, and (3) its final value.
	The symbol Plot can be used with a number of Options.

Options[Plot]

For example, you can specify the labels on the axes and a title for the plot.

Plot[x^2 - x, {x, 0, 5},
AxesLabel->{"x", "y"},
PlotLabel->"Plot of x^2 - x"];

A list of functions can be plotted.

Plot[{x, x^2 - x} , {x,0,5}];

A contour plot displays a set of curves along which a function has a constant value.

ContourPlot[Sin[x] Exp[- 3 y^2],{x,0,2 Pi},{y, 0, 1},
FrameLabel->{"x","y"}];

A list of discrete {x,y} values can be displayed using ListPlot.

ListPlot[{{0,0},{1,1},{2,4},{3,9},{4,16}},PlotStyle->{RGBColor[1,0,0],PointSize[0.02]},Frame->True,FrameLabel->{"x","y"}];

Exercises

Plot some interesting functions in 2-D by modifying the expressions used here.

3-D Plotting

The functions commonly used for 3-D plots are the following:

Plot3D
	ParametricPlot3D

Plot3D[Sin[x] Exp[- 3 y^2],{x,0,2 Pi},{y, 0, 1},
AxesLabel->{"  x","  y","z   "}];

ParametricPlot3D[{Sin[t],Cos[t], 0.1 t},{t,0,6 Pi}]

Exercises

Try making some 3-D plots by modifying the expressions used above.

Using Variables

Assignments with Set ( = )

For any calcuation that takes more than one or two steps you need to use a symbol to store a value or an expression.  This can be done by using Set [ symb , expr ] or user-friendly expressions illustrated below.

x = expr     	assigns evaluated expr to x
 x = y = expr  	assigns evaluated expr to x and y

Before assigning an expression to a symbol using Set(=), Mathematica first evaluates the expression.   Therefore, use Clear to remove any assignments from symbols in the expression that you wish to use as variables. The result of the evaluation is displayed in an output cell, unless the assignment is followed by a semicolon.

The expression can be a number, as when you assign to the symbol g a value for the acceleration due to gravity for a ball thrown upward.  The symbol h is used to store an expression for the height of a ball launched vertically upward with velocity v0.

Clear[h, v0, g, t];
g = 9.8;
h = v0 t  -  (1/2) g (t^2)

Notice that the expression to be assigned to h was first evaluated using the rule for transforming g.  So the dependence of h on g is hidden.  Evaluate h by assigning values to v0 and t.

v0 = 40.0;  t = 2.1;
h

Assigning expressions to the symbols v0 and t do not change the rule attached to h.

?h

The dependence of h on g, v0, and t remains.  So we can repeat the calculation just by changing the values of v0 and t.

v0 = 50;  t = 3.1;
h

Therefore, h can be regarded as an implicit function of g, v0, and t..

Assignment with SetDelayed ( := )

Problems arising from assignments to expressions containing "contaminated" symbols can be avoided by using SetDelayed[ symbol , expr ] or the user-friendly forms shown below.

x := expr	assigns unevaluated expr to x

An expression assigned to a symbol with SetDelayed is not evaluated.  This is illustrated with the upwardly thrown ball expression where symbols appearing in it are assigned values before the implicit function is assigned.

Clear[h];
g = 9.8; v0 = 40; 
h  :=  v0 t  -  1/2 g (t^2)

No output appears because the right hand side was not evaluated by SetDelayed.  Here we ask for the transformation rule used to evaluate h.

?h

Note that := appears in the rule for h.  But now evaluate h.

h

So the current values of g and v0 are used to evaluate h, but these values were not used during the assignment of an expression to h.

Computational efficiency of Set and SetDelayed.

For most purposes Set is equivalent to SetDelayed if you take care to clear all the symbols used in an assignment with Set.  A disadvantage to using SetDelayed to assign an expression to a symbol is that every evaluation of an expression wherein it appears requires Mathematica to evaluate the expression assigned to it before it can use that expression to transform the symbol.

Example:  Average Density of the Earth

(Here we use the typesetting capabilities of Mathematica to show you what you can do if you read Section 1.1.7 of The Mathematica Book in the Browser.)

According to Newton's Universal Law of Gravitation,  the acceleration due to gravity at the surface of the earth g is given by
                              g = G M / (R^2)
where G is the Universal Constant of Gravitation.  It was first determined to an accuracy of about 20% by the British Astronomer Royal by estimating the attraction of Mt. Schehallion in Scotland  It was subsequently measured by Cavendish in the laboratory.  The current value for G is 6.67 x 10-11 N (m^2) (kg^(-2)).  We want to use this relation to find the average density of the earth as a first step in learning about its interior.

An expression for the mass M of the earth is then given in the following assignment.

Clear[M, R, g, G];
M  =  g ((R^2)/G);

The average density of the earth ρ (Esc r Esc) is found by using the formula for the volume of a sphere, 4/3 π (R^3).

ρ  =  (M/((4/3) π (R^3)));

We can check this expression at the same time that we evaluate it by including units in the values for the physical constants that enter it.

The value of g varies slightly over the surface of the earth but is approximately 9.8 m/s2.  The average radius of the earth R is approximately 6371 km. (The earth is not spherical; this is a the radius of a sphere with the same volume.)  Save the substitution rules for the constants needed in this calculation by assigning them to a symbol.

EarthConstants = {g -> 9.8 (m/(s^2)), 
          R -> 6.371 (10^6) m,  
          G -> 6.67 (10^(-11)) ((m^3)/(kg (s^2)))};

Now, compute the density of the earth using N as a postfactor to force approximation of π.

ρ //. EarthConstants // N

The density of water is  1000 kg/m3, so the specific gravity of the earth is 5.522.

Substitutions

Problems arising from the use of contaminated symbols can also be avoided by not assigning values even to symbols used to represent constants and parameters.  Instead,  evaluate an expression by substituting values for constants and parameters rather than assigning replacement rules to them.  This is done by applying substitution rules during the evaluating by using /.  (ReplaceAll) or //. (ReplaceRepeated) as explained in Section 2.4.1 .  The following examples illustrate evaluation by substitution.

Input					Result

(x^2) + x Sin[x] /. x -> 3			9 + 3 Sin[3]
(x^2) + y /. {x -> y,  y -> 3}		(y^2)  +  3
(x^2) + y //. {x -> y,  y -> 3}		6

The last two examples illustrates the need for RepeatedReplace.  With ReplaceAll x is replaced by y and y is replaced by 3;  but the y that resulted from replacing x is not replaced by 3.  This requires a second replacement operation, the function of RepeatedReplace.

The calculation in the last section could have been done without contaminating g and v0.

Clear[h, g, v0, t];
h  =  v0 t  -  1/2 g (t^2);

h /. {g -> 9.8,  v0 -> 40, t -> 2.1}

No assignments have been made to g, v0, or t.

Defining Functions

Explicit functions are symbols that accept input through arguments and produce output using the rules assigned to them.  As with variables, you can use either Set or SetDelayed to define an explicit function.  Remember that before the assignment with Set, you must clear all symbols that you want treated as variables. Here we take the precaution of clearing all user-created symbols before starting this section.

Clear["Global`*"]

Patterns

The unique feature of Mathematica that distinguishes it from other computer algebra programs is that it recognizes commands based on a Pattern as explained in Section 2.3.3 of The Mathematica Book. The underline _  is a symbol called Blank used to specify a Pattern. A pattern can be used to modify an expression by using ReplaceAll ( /. ).  This is the simplest way to gain understanding of the use of patterns.
	We first show that used by itself, the symbol Blank stands for any expression. Here the rule used with ReplaceAll states - "Replace any expression with the symbol z."

u Sin[u] /. _ ->  (w^2)

To be more specific in the use of a pattern, you must give it a "name" by attaching a symbol to it, as in x_.   Here you see the use of two named patterns.

u Sin[u] /. x_ Sin[y_] :> (x^2) Cos[2 y]

The symbol :> (RuleDelayed) avoids problems arising from a pattern written with contaminated symbols by not evaluating the pattern.  In this respect, :> has the same property as the symbol := used in assignments.

Function definitions

A function can only be defined by using a pattern.  The assignment can be made with SetDelayed ( := ) or Set ( = ).  Here we define of a function that returns the square of any argument.

Clear[f]; 
f[x_] := (x^2)

Display the transformation rule assigned to f.

?f

Here is how f transforms different arguments.

{f[3],f[Sin[y]], f["George"]}

If the Blank ( _  ) is omitted in the argument, the assignment applies only when the symbol x is used as an argument.

Clear[g];
g[x] := x^2

{g[x],g[2],g[y]}

This assignment has established a transformation rule for the expression "g[x]".  But g is not a function and no transformation rules apply to the expressions g[2] and g[y].

You can also define a function using Set ( = ) if you are careful to use a clear symbol for the name of the pattern. Otherwise you will have a serious problem because the right side will be evaluated before an the expression using the symbol is assigned.

Clear[h, t]; g = 9.8;
h[t_] = v0 t  -  (1/2) g (t^2)

The expression being assigned was first evaluated.  The rule assigned to h uses a pattern

?h

but the symbol g does not appear because it has been replaced by 9.8.

Exercises

Conditions on patterns

A function can be defined for a specified type of argument, for example, an integer.

Clear[f];
f[n_Integer] := (n^2)

{f[3], f[3.1], f[x]}

A numerical condition can be placed on the function by using the symbol /; (Condition).  (Note that the symbol following the slash is a semicolon.) Here is a step function.

Clear[f];
f[x_ /; x < 0] := 0;
f[x_ /; x ≥  0] := 1;

Plot[f[x], {x, -1, 1}];

The symbol f has two different rules for f.

?f

Symbols as arguments

An assignment that uses a symbol as an argument stores an expression into a named "bin".

Clear[f];
f[1] = 1; f[2] = 4; f[3] = 9;

These assignments have stored values in bins f[1], f[2], and f[3].

{f[1],f[2],f[3], f[4]}

Nothing was stored in a bin f[4] so Mathematica just returns "f[4]" as an unmodified expression.

A symbol can be used both to label a function and a set of bins.  Bin assignments can be used to create functions that remember values.  Here is an example.

Clear[f];
f[n_Integer] := f[n] = (Sqrt[n]);

Evaluation of f[n] for a set of values will store those values for instant recall when requested.  Display the rules attached to f before we start evaluating it.

?f

Now evaluate f for a set of integers and then display the rules attached to f.

Table[f[n], {n, 5}]

?f

The computed values for f are now stored in memory.  As explained in Section 2.5.12 , however, Mathematica places a limit called $IterationLimit on the number of values that can be stored.

A symbol can also be used to label different functions labelled with the same symbol.

Clear[a, b, h, area, square, rectangle];
area[a_, square] := (a^2);
area[b_, h_, rectangle] := b h;
area[b_, h_, triangle] := ((b h)/2);

{area[3, square], area[2, 3, rectangle], 
      area[2, 3, triangle]}

Multivalued Calculations

Modelling any physical system usually will involve calculating its behavior for a set of equally spaced time steps.  Or you will want to study it for a range of regularly spaced values for a physical parameter.   In computational science a set of regularly spaced values for an independent variable is called  a "grid".   If an expression with two independent variables is evaluated over a set of equally spaced values for each, one speaks of using a "mesh".  For an expression dependent upon three variables,  a set of equally space values for each variable will form a "lattice".  But multidimensional calculations use a different grid for each independent variable.
	In this section we shall show a number of ways to compute the trajectory of a projectile when drag is neglected.

Listing

Mathematica is really an array processing language whose built-in functions are Listable, meaning that they operate on a list element-by-element.  Evaluating an expression by using  lists of values is generally much faster than the programmed do-loops used in conventional programming languages.

Substituting a list

Subtitution of a list of values for a variable can be used for a multistep computation.
	The trajectory of a ball launched with speed v0 at an angle θ is given by these expressions:

Clear[x, y, v0, θ, g, t];
g = 9.8;
x = v0 Cos[θ] t; 
    y = v0  Sin[θ] t - ((g (t^2))/2);

The position can be found as a function of time by substituting values for v0, θ,  and then substituting a list of times.  If v0 is 40 m/s and  θ is 30 degrees, choose time intervals of 0.2 seconds over about 4 seconds.  Compute a list of {t , x , y} values for the trajectory.

Clear[Trajectory]; 
    Trajectory = {t, x, 
          y} /. {v0 -> 40, θ ->  
            30 Degree, t -> 
            Range[0, 4.2, 0.2]}

Substitution of a list of t values into {t , x , y } produces a list of three lists: one for t, one for x, and one for y.  But we want a list of triplets {(Subscript[t, i]) ,  (Subscript[x, i]) , (Subscript[y, i])} for each time instant.  We use Transpose to do this.

Trajectory = Transpose[Trajectory]

Now use TableForm to display the result.

TableForm[Trajectory,  
      TableHeadings ->  {None, {"t", "x", "y"}}]

If you would prefer not to have trailing zeros dropped, you can specify the column width and the number of digits using PaddedForm.

PaddedForm[
      TableForm[Trajectory,  
        TableHeadings ->  {None, {"     t", "     x", "    \
y"}}], {10, 5}]

You can use ListPlot to plot the trajectory, but you must pick out just the x, y values from each triplet in Trajectory.  You can use /. with patterns to do this.

ListPlot[Trajectory /. {a_, b_, c_} -> {b, c}];

Argumenting with a list

Functions that use Listable Mathematica operations are also Listable.  So define a function that computes the position of a projectile at a specified instant of time and use a list of times for the argument.

Trajectory[v0_, θ_, g_, t_] := {t, v0 Cos[θ] t, 
        v0 Sin[θ] t - (1/2) g (t^2)}

Trajectory[40, 30 Degree, 9.8, Range[0, 4.2,  .2]] // 
      Transpose

Again, we used Transpose because the list of t values was substituted for t and this produces a list of three long lists: one of the t values, one of the x values, and one of the y values.  But we want a list of triplets that give t, x, and y at each instant.

Mapping a function to a list

Clear["Global`*"]

The symbol Map can be used to apply a function to each element of a list and to return a list of the results.

Map[f, {a, b, c}]

Map applies a function of a single argument to a list.  But, there is a way to use Map by defining a functiion "on the fly".  This is called a pure function that might better be termed an "anonymous" function.  There is no need to give a name to the function or to its arguments.  For example, here is an anonymous function that computes Sin[x]-x Cos[x] when given x as an argument.

(Sin[#] - # Cos[#]) &[x]

The hash mark # (pound sign) represents the argument and the ampersand & denotes the expression before it as an anonymous function.  Application of this anonymous function to a list will give a list of values.

Map[(Sin[#] - # Cos[#]) &, Range[0, 1, 0.1]]

This concept can be used to "skeletonize" a function of several arguments in order to make a function that takes a single argument. In the last section we defined the function Trajectory.

Trajectory[v0_, θ_, g_, t_] := {t, v0 Cos[θ] t, 
        v0 Sin[θ] t - (1/2) g (t^2)}

Now trajectory has four arguments.  We want to apply it to a list of times in order to get a list of positions.  We can do this by using it to make an anonymous function with a single argument.

Map[Trajectory[40, 30 Degree, 9.8, #] &, 
      Range[0, 4.2, 0.2]]

Note that there was no need to transpose the result because Map evaluated the triplet {t,x,y}  for each instant of time instead of substituting a list of values for t.  Had we used a list of times as an argument for the anonymous function used in Map, the result would have been a list that contained a list of values for t, one for x, and one for y.

Trajectory[40, 30 Degree, 9.8, #] &[Range[0, 4.2, 0.2]]

Tabling

The symbol Table accepts two arguments: an expression and an iterator that specifies a variable and the values that it will be given.  If an expression depends upon two independent variables, Table accepts two iterators that specify the variables and the values that each is to be given.

Table[ exp , iter1]
	Table[ exp , iter1, iter2 ]

Making a table

A table of values for the sine and cosine functions is easily created using Table.

Table[{x, Sin[x Degree], Cos[x Degree]}, {x, 0, 180,  30}] // N // 
      TableForm

Tabling a trajectory

The symbol Table can be used to calculate the trajectory of the ball as a function of time in one step.  Here are expressions for the horizontal and vertical positions as functions of time.

Clear[x, y, v0, θ, g, t];
g = 9.8;
x = v0 Cos[θ] t; 
    y = v0  Sin[θ] t - ((g (t^2))/2);

Here Table directly creates a list of triplets {t,x,y}.

Trajectory = 
      Table[{t, x, 
            y} /. {v0 -> 40, θ ->  
              30 Degree}, {t, 0, 4.2, 0.2}]

Plotting a list of functions

A list of functions can be created for plotting.  Use the symbol Evaluate to force construction of the list as a whole before Plot starts evaluating the elements.

Plot[
        Evaluate[Table[BesselJ[n, x], {n, 0, 5}]], {x, 0, 10}];

Coloring a list of plots

Using Table a list of colors can be constructed to distinguish these functions.

Plot[Evaluate[Table[BesselJ[n, x], {n, 0, 5}]], {x, 0, 10}, 
        PlotStyle -> 
          Table[RGBColor[1 - c, 0, c], {c, 0, 1, 0.2}]];

Creating a list of plots

A list of plots can even be created by using Table.

ListOfPlots = 
        Table[Plot[BesselJ[n, x], {x, 0, 10}], {n, 0, 2}];

This is an array of graphs.

Looping

Mathematica provides the symbols Do, While, and For for multistep calculations.  Using them will seem more natural to you if you have programmed in a procedural language like C, C++, Pascal, or Fortran.   The reason is that you have learned to think of a multivalued computation as a multistep loop that processes input data element-by-element instead of thinking in terms of processing an entire list or array in one operation.  However, programs written this way in Mathematica generally run  slower than those written using lists and "functional operators" because Mathematica is written as an array processing language.  You should not think of this as a peculiarity of Mathematica because even procedural programming languages used for intensive numerical computations are evolving toward using array processing rather than element-by-element looping.   Computations written in terms of array processing can more easily be compiled to run in parallel on a supercomputer like the Cray or the a system of computers running in parallel.
	The use of each of these symbols is illustrated by applying them to the problem of computing the trajectory of a ball..  Note that none of these symbols store results so you must start with an empty list and AppendTo it the result of each step.

Each symbol for looping will use the following definitions:

Clear[x, y, v0, θ, g, t];
g = 9.8;
x = v0 Cos[θ] t; 
    y = v0  Sin[θ] t - ((g (t^2))/2);

Do

?Do

params = {v0 -> 40, θ ->  30 Degree};
Trajectory = {};
Do[
        AppendTo[Trajectory, {t, x, y} /. params /. t -> ti], {ti, 0, 
          4.2, 0.2}];
Trajectory

While

?While

params = {v0 -> 40, θ ->  
            30 Degree};
Trajectory = {};
ti = 0.0;
While[(y /. params /. {t -> ti }) >= 0, 
        AppendTo[Trajectory, {t, x, y} /. params /. t -> ti]; 
        ti += 0.2];
Trajectory

For

?For

Remember that commas separate arguments; semicolons separate commands.  While For accepts four arguments,  each can consist of several commands separated by semicolons. In the following use of For, count the number of arguments.

params = {v0 -> 40, θ ->  30 Degree}; 
    For[Trajectory = {}; ti = 0.0, (y /. params /. {t -> ti }) >= 0, 
      ti += 0.2, 
      AppendTo[Trajectory, {t, x, y} /. params /. 
          t -> ti]];
Trajectory

Modularizing

These trajectory calculations have assigned expressions to variables that you will later want to clear.  Each also required evaluation of more than one cell.  Using Module to program a calculation allows the use of "local" variables and the use of many commands.

?Module

Here we write a program that computes a trajectory in SI units using Module.

Clear["Global`*"]

\(Trajectory[v0_, θ_, tf_, dt_] := 
      Module[{t, x, y, g = 9.8}, 
\ \ \ \ \ \ \ \ x = v0\ Cos[θ] t; 
        y = v0\ \ Sin[θ] 
              t - \(g\ t\^2\)\/2; 
\ \ Table[{t, x, y}, {t, 
            0, tf, dt}]]\)

Trajectory[40, 30 Degree, 4.2, 0.2] // TableForm

Timing Tests

We said that Mathematica could perform a multivalued computation more rapidly using lists than using Do, While, or For.  We time the trajectory calculation but reduce the step size to 0.01 seconds to increase the computational time and make the relative speeds more obvious.  
	Here we time the computation that use substitution of a list of times.

Timing[Clear[Trajectory]; 
      Trajectory = {t, x, 
            y} /. {v0 -> 40, θ ->  
              30 Degree, t -> 
              Range[0, 4.2, 0.01]};]

Try mapping a function to a list.

\(Timing[Clear[Trajectory]; 
      Trajectory[v0_, θ_, g_, t_] := {t, v0\ Cos[θ]\ t, 
          v0\ Sin[θ] t - \(1\/2\) g\ t\^2}; 

      Map[Trajectory[40, 30\ Degree, 9.8, #] &, 
        Range[0, 4.2, 0.2]];]\)

Hre is the Do loop.

\(Timing[Clear[Trajectory]; 
      params = {v0 -> 40, θ -> \ 30\ Degree}; 

      Trajectory = {}; 

      Do[AppendTo[Trajectory, \({t, x, y} /. params\) /. t -> ti], {ti, 0, 
          4.2, 0.01}]; 
Trajectory;]\)

Here we time the While loop.

\(Timing[Clear[Trajectory]; 
      params = {v0 -> 40, θ -> \ 
            30\ Degree}; 
Trajectory = {}; 
ti = 0.0; 

      While[\((\(y /. params\) /. {t -> ti\ })\) >= 0, 
        AppendTo[Trajectory, \({t, x, y} /. params\) /. t -> ti]; 
        ti += 0.01]; 
Trajectory;]\)

And finally, we time the For loop.

\(Timing[Clear[Trajectory]; 
      params = {v0 -> 40, θ -> \ 30\ Degree}; 
      For[Trajectory = {}; 
        ti = 0.0, \((\(y /. params\) /. {t -> ti\ })\) >= 0, ti += 0.01, 
        AppendTo[Trajectory, \({t, x, y} /. params\) /. t -> ti]]; 

      Trajectory;]\)

Conclusion: Substituting a list takes 1/10 as much time as loops with Do, While, and For.  Mapping a function to a list takes even less time, probably because there is no need to transpose the result.

Working with Lists

Since data and the results of multivalued computations are stored in lists, tools are provided for extensive processing of lists.

Visualizing lists

Data will be stored in a list.  We can visualize it using ListPlot.

ListPlot[{y1,y2, ...}]         		plot y1,y2,.. at values 1,2,..
ListPlot[{{x1,y1},{x2,y2},..}]    	plot points {x1,y1}, ...
ListPlot[alist, PlotJoined->True]	 joins points with lines

A list of numbers is plotted against the indices.

ListPlot[Range[0,10]];

Pairs of x,y values are plotted as points.  You may set the point size to a decimal fraction of the size of the entire plot.

gp = 
        ListPlot[Table[{x, (x^2) Sin[x]}, {x, 0, π, 0.2}], 
          PlotStyle -> PointSize[0.02]];

We can superpose data points on the plot of a function by using Show.

gf=Plot[x^2 Sin[x],{x,0,Pi}];

Show[gp,gf];

Pulling out pieces

To illustrate the operations make a symbolic matrix.  Use MatrixForm to display it as a matrix.

(m = Table[f[i,j],{i,5},{j,3}])//MatrixForm

Length tells the number of rows and Dimensions gives the maximum value of each index.

{Length[m], Dimensions[m]}

Use of double-square brackets with a single number displays all the elements whose first index is equal to that number.

m[[3]]

Access more specific parts by giving more indices.

m[[3, 2]]

A list is interpreted as a list of first indices.

m[[{2, 5}]]

A block of elements can be extracted by giving two lists, the first specifying rows and the second specifying columns.

m[[{2, 5}, {1, 2}]]

Taking and Dropping

Take[ alist, n ]		take the first n elements
Take[ alist, - n ]	take  the last n elements
Drop[ alist, n ]		take all but the first n elements
Drop[ alist, - n ]	take all but the last n elements

The followiing output illustrates these rules, and shows that the list is not changed.

alist = Range[10];

{Take[alist, 3], Take[alist, -3], Drop[alist, 3], 
      Drop[alist, -3], alist}

Adding to a list

Append[ alist, symb ]		returns alist with symb at end
Prepend[ alist, symb ]		returns alist with symb at beginning
AppendTo[ alist, symb ]	adds symb to end
PrependTo[ alist, symb ]	adds symb to beginning

These commands are illustrated by the following output.

alist = Range[10];

{Append[alist, x], Prepend[alist, x], alist}

{AppendTo[alist, x], PrependTo[alist, x], alist}

Joining lists

Some functions expect input as a single list.  But suppose we have stored the information needed by the function in two distinct lists. We must be able to join them.

Join[{a,b,c,d},{e,f,g,h}]

If some of the information appears in both lists, simply joining them may cause trouble.  Use Union to join and eliminate repeated elements.

Union[{a,b,c,d},{b,d,e,f,g,h}]

Applying functions to a list

In Mathematica the evaluation of an expression is simply a rewriting or transformation using rules associated with the symbols that make it up.  Since the head of an expression is also a symbol, we can change it by applying a rule.  Let us try adding the elements of a list this way.
	Note that the sum of several elements is internally represented by 
		Plus[ a, b, c ]
while a list is represented this way.
		List[ a, b, c ]
Since the heads Plus and List are just symbols, one can replace the other.

{1,2,3,4,5}/.List->Plus

It worked!  Try multiplying the elements of a list.

{1,2,3,4,5}/.List->Times

From these two examples we can imagine that many computations can be carried out by using "functional operations" that apply transformations to either the head or the body of an expression.  These functional operations are the key to accessing the power of Mathematica through functional programming and there are a number of functions, or you may think of them as operators, to carry them out.

Apply, @@

This operator changes the head of any expression, as we did in the previous section using ReplaceAll.  However, Apply only changes the head of an expression, whereas ReplaceAll will change the head of every substructure of an expression that matches the one in the rule.  This is easy to verify.

{{a,b,c},{d,e,f}}/.List->Plus

This results because

FullForm[{{a,b,c},{d,e,f}}]

whereas

Apply[Plus,{{a,b,c},{d,e,f}}]

We can use Apply to feed any list to a function.

Apply[f,{a,b,c}]

Apply[Times,{x,y,z}]

Apply[Plus,{x,y,z}]

Apply[Sin,f[x+y]]

The operator notation @@ for Apply simplifies entry.

f @@ {a,b,c}

Example

Use Apply together with arithmetic operations on a list to compute the average and the standard deviation of a list.  Here are the periods of a pendulum measured with a watch that is only accurate to 0.1 second.

periods = { 2.3, 2.4, 2.4, 2.3, 2.2, 2.3, 2.4, 2.3};

Define a function to compute the mean and the standard deviation of the mean, defined by
                         X   = (x1 + x2 + ....) / N
                         sd  = (Sqrt[((((x1 - X))^2) + (x2 - ((X))^2) + ...) / N ])

mean[data_]:=Apply[Plus,data]/Length[data];
sd[data_]:= Sqrt[Apply[Plus,(data - mean[data])^2]/
                Length[data]];

mean[periods]

sd[periods]

Map, /@

The function Map applies a function that is not Listable to each element of a list.

Clear[f];
Map[f,{a,b,c}]

The function Map applies a function to the arguments of any function.

Map[Cos, g[a, b, c]]

The operator notation for Map makes such commands very succinct.

f /@ {a,b,c}

Example

The measured periods of a pendulum can be used to compute values for the acceleration due to gravity.

g[P_] := 4 (π^2) L/(P^2)

This is actually a listable function, but suppose that it were not.  Use Map to apply this function to each element of the list of measured periods to get a value for g.  The length of the pendulum was measured to be 1.34 meters so use substitution to get values for g.

gvalues = Map[g, periods] /. L -> 1.34

The mean value is not bad

mean[gvalues]

but the standard deviation is poor.

sd[gvalues]

Algebra
Algebraic operations
Expand
Factor
Together
Apart
Cancel
Simplify
Expand[(x + y)^2 + 7 (3 + x) (x + y)]
21 x + 8 (x^2) + 21 y + 9 x y + (y^2)
The symbol%refers the result from the immediately previous execution,notnecessarily the result from the precedingcell.
Factor[%]
(x + y) (21 + 8 x + y)
(This is theprefixform of a function.)
Expand[Sqrt[a^2 t^2]]
(Sqrt[(a^2) (t^2)])
\(No\ assumption\ is\ made\ about\ the\ sign\ of\ a\ or\ t\ so\ the\ root\ is\ not\ taken . 
PowerExpand[%]\)
a t
\(Note\ that\ if\ a < 0\ or\ t < 0\ \((but\ not\ both)\), 
          this\ answer\ may\ not\ be\ what\ we\ want . 

              Together[1/\((x + 1)\) - 2\ x/\((1 - x)\)^2]\)
((1 - 4 x - (x^2))/((((-1 + x))^2) (1 + x)))
\(Apart[%]
 - 2\/\((\(-1\) + x)\)\^2 - 2\/\(\(-1\) + x\) + 
            1\/\(1 + x\)\)
\(Simplify[%]
 - \(\(-1\) + 4\ x + x\^2\)\/\(\((\(-1\) + x)\)\^2\ \((1 + x)\)\)\)
\(Factor[%]
 - \(\(-1\) + 4\ x + x\^2\)\/\(\((\(-1\) + x)\)\^2\ \((1 + x)\)\)\)
Algebra with a Palette
These operations can be carried out by using a palette to apply transformations in an output cell . From the menu chooseFile/AlgebraicManipulation.Next,\(evaluate\ the\ cell\ below . 
\((x + y)\)^2\  + \ 
              7\ \((3\  + \ x)\)\ \((\ x\  + \ y)\)\)
7 (3 + x) (x + y) + (((x + y))^2)
Place the cursor somewhere in the output cell inside the last term and click the mouse repeatedly until this part of the output is highlighted . The chooseExpandfrom the palette . A new cell will appear but it will be anInputcell! In it you will see the last term expanded . Place the cursor somewhere in the first term in this same cell and click until it is highlighed.ChooseExpandagain.Note that the last output cell changes but a new one is not produced . Click anywhrere in this expression until it is all highlighted . Now chooseFactor.
7 (3 + x) (x + y)+(((x + y))^2)
(x + y) (21 + 8 x + y)
Vectors and Matrices
Vector
A vector can be represented as list. 
u={u1, u2, u3};
Matrix
\(A\ matrix\ is\ a\ list\ with\ two\ levels, \(the\ second\ level\ being\ lists\ of\ equal\ length . 
m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 
                  9}};\)\)
The function Dimensions gives the number of columns and rows of a matrix.
Dimensions[m]
{3, 3}
We can display a matrix in the usual way with MatrixForm.
MatrixForm[m]
(({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))
But never make an assignment of this form
n  =  MatrixForm[{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}];
because n will not be a matrix; the head will beFullForminstead ofList.
FullForm[n]
MatrixForm[
                List[List[1, 2, 3], List[4, 5, 6], List[7, 8, 9]]]
Assign the matrix to nbeforeyou applyMatrixFormto display \(it . 
\((n = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})\)\)//MatrixForm
(({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))
Tensor
\(A\ tensor\ is\ a\ list\ with\ three\ or\ more\ levels . 
\((t = {{{0.1, 0.2}, {0.3, 0.4}}, {{0.5, 0.6}, {0.7, 0.8}}, {{0.9, 
                          1. }, {1.1, 1.2}}, {{1.3, 1.4}, {1.5, 1.6}}})\) // 
            MatrixForm\)
(({{(({{0.1`}, {0.2`}})), (({{0.3`}, {0.4`}}))}, {(({{0.5`}, {0.6`}})), (({{0.7`}, {0.8`}}))}, {(({{0.9`}, {1.`}})), (({{1.10000000000000008`}, {1.19999999999999996`}}))}, {(({{1.30000000000000004`}, {1.39999999999999991`}})), (({{1.5`}, {1.60000000000000008`}}))}}))
Dimensions[t]
{4, 2, 2}
Vector and matrix operations
u . v dot product Dot[u, v]
Transpose[m] transpose of matrix m
Inverse[m] inverse of a matrix
Det[m] determinant of a matrix
The scalar or dot product of two lists is a contraction of the last index of the first list with first index of the second list . By "contraction of indices" is meant setting two indices with equal ranges equal to each other and then summing over the full range . The dot product of two multidimensional lists is defined as follows:u  .  v      ==          (∑_j) (Subscript[u, ij]) (Subscript[v, jklmn])TheDotproduct ofMathematicafollows this convention of tensor analysis and does not distinguish between row vectors and column vectors . Here is the dot product of two 3-\(vectors . 

                      Clear[a, b, c, d, e, f]\);
{a, b, c} . {d, e, f}
a d + b e + c f
m = {{a, b}, {c, d}};
m . {e, f}
{a e + b f, c e + d f}
{e, f} . m
{a e + c f, b e + d f}
Equations
   You have seen that  x = expr actually causes x to be replaced by expr in any expression that Mathematica evaluates; it is an assignment.  But in mathematics an equation  x = expr  is really a relation that  is sometimes used to replace the quantity on the left hand side, and sometimes solved for a symbol appearing on the right hand side .   In Mathematica we distinguish between an assignment and an equation very explicitly.
Expression for an equation
    In Mathematica the symbol used to express an equation is the logical symbol  (==). 
         l.h.s. == r . h . s . ,
If both sides of an equation can be evaluated, Mathematica will return the result  True or False.
2+2==5
False
Exercises
1.  Evaluate the following equation for n  =  
              1,  2,   ... ,  
            20 to determine the value of the machine epsilon on your computer .   (Hint :  Use a list.)
1 == 1 + 1.0 (10^(-n))
2. Evaluate $MachinePrecision to check your result.
Solving algebraic equations
Solve[eqn,  symb] list of rules for assignment of solution
Solve[{eq1,  eq2,  ... }, {var1,  var2,   ... }] list of rules for assignment of solution
Single equation
Many equations can be solved by using Solve.  Use a symbol to store the solution so that you can work with it.
Clear[eq, soln, x, a, b, c];
eq1 =  a (x^2) + b x  + c == 0; 
sol1 = Solve[eq1, x]
{{x -> ((-b - (Sqrt[(b^2) - 4 a c]))/(2 a))}, {x -> ((-b + (Sqrt[(b^2) - 4 a c]))/(2 a))}}
	Mathematica has returned two rules for assigning a solution of the equation to x.  But no value has been assigned to x.  In fact, as already explained you should avoid making assignments to symbols that are being used as variables .   Assign one of the solutions to a different symbol by choosing to use one of these rules with ReplaceAll.
xs=x /. sol1[[2]]
((-b + (Sqrt[(b^2) - 4 a c]))/(2 a))
You can always verify thatxssatisfies the equation by using \(substitution . 
eq1\)/.x -> xs
c + ((b (-b + (Sqrt[(b^2) - 4 a c])))/(2 a)) + ((((-b + (Sqrt[(b^2) - 4 a c])))^2)/(4 a)) == 0
It is necessary toSimplifythe left side before Mathematica can verify that xs is a solution . Use theAlgebraicManipulation palette by placing the cursor into this output cell on the left side and repeatedly clicking until it is completely highlighted . Then chooseSimplifyfrom the palette.AnInputcell will appear as you do this and the operations done with the palette will all be done in this same cell . You will see the following result,\(showing\ that\ xs\ is\ a\ solution\ to\ the\ equation . 

                  0 == 0\)
	Mathematicaalways returns a list of lists as the solution to an equation,\(even\ when\ there\ is\ only\ one\ solution . 
sol2 = 
              Solve[a\ x\  + \ b\  == c, x]\)
{{x -> -((b - c)/a)}}
\(So\ you\ must\ index\ into\ the\ list\ of\ rules, 
          even\ though\ there\ is\ only\ one . If\ you\ do\ not, 
          you\ assign\ a\ list\ to\ xs\ instead\ of\ an\ algebraic\ expression . 
xs = x /. sol2\)
{-((b - c)/a)}
In the case of one solution you can also useFirstto pull out the first,and only,\(rule . 
xs = x /. First[sol2]
 - \(b - c\)\/a\)
Multiple equations
\(If\ you\ have\ more\ than\ one\ equation\ to\ solve, \(you\ just\ include\ them\ in\ a\ list\ and\ specify\ the\ unknowns\ in\ a\ second\ list . 
Clear[x, y, a, b];\)\)
eq3 = {(x^2) - y == a,  x/y  ==  b}; 
sol3 = Solve[eq3, {x, y}]
{{x -> ((1 - (Sqrt[1 + 4 a (b^2)]))/(2 b)), 
              y -> ((1 - (Sqrt[1 + 4 a (b^2)]))/(2 (b^2)))}, {x -> ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 b)), 
              y -> ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 (b^2)))}}
There are two solutions for x and y . 
                If you want to use the second solution,you can define symbolsxsandysthat satisfy the equation in one \(step . 
{xs, ys}\)={x, y} /. sol3[[2]]
{((1 + (Sqrt[1 + 4 a (b^2)]))/(2 b)), ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 (b^2)))}
\(Verify\ the\ solution . 
eq3 /. {x -> xs, y -> ys} // 
            Simplify\)
{True, True}
Elimination
\(It\ is\ useful\ to\ be\ able\ to\ eliminate\ variables\ from\ simultaneous\ equations . 
              There\ are\ two\ operations\ for\ doing\ this . 

              Eliminate[{eq1,  ... }, {var1,  ... }]\ eliminates\ variables\)
Reduce[{eq1,  ... }, {var1,  ... }] logical expressions
\(Let' 
              s\ try\ this\ on\ the\ eq3\ that\ was\ solved\ in\ the\ last\ section . 
Clear[x, y, a, b];\)
eq4 = Eliminate[eq3, y]
a b == x (-1 + b x)
Verify that the solutions forxfound above come from solutions of this \(equation . 
Solve[eq4, x]\)
{{x -> ((1 - (Sqrt[1 + 4 a (b^2)]))/(2 b))}, {x -> ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 b))}}
 	Reduce eliminates symbols from a set of equations but returns the result as a rigorous set of logical equations .   Apply this symbol to eq3, but enter eq3 explicitly so that it an be compared with the solution.
Reduce[{(x^2) - y == a, (x/y) == b}, y]
a ≠ 0 && y == -a && b == 0 && x == 0 || 
            b ≠ 0 && x ≠ 0 && b x == 1 && y == (x^2) && 
              a == 0 || a ≠ 0 && b ≠ 0 && 
              x ≠ 0 && -1 + b x ≠ 0 && 
              a b == x (-1 + b x) && y == -a + (x^2)
Refer to the relational and logical operators to interpret this output.
Use the symbols in this table to read the result returned byReduce.The symbol&&stands forANDand the symbol||stands forOR.The different solutions are separated byOR.So,the first set of conditions for a solution are
a ≠ 0 && y == -a && 
            b == 0 && x == 0
which can be translated as
\("a not equal to zero AND y equal to -a AND b equal to zero AND x equal to zero" . 
Exercise\)
Use Eliminate to find the trajectory of a projectile in a vacuum by eliminating the time from the equations  (Remember to assign each equation to a symbol for ease in manipulation and to clear each symbol of any previous values.)
       Clear[x, x0,  v0, theta,  t,  y,  y0,  v0,  t,  
                g];
       xeq  =  x  ==  v0 Cos[theta] t ;
       yeq = y == v0 Sin[theta]  t  - (1/2) g (t^2);
\(Proceed\ as\ follows . 
\ \ \ \ \ \ \ \ \ \ 1. \ Eliminate\ the\ time\ from\ the\ equations\), calling the result eqxy
          2. Use soln =Solve[ eqxy ,  y ] to find a rule for defining y as a function of x
          3. Use ysol = y  /.   soln[[1]]  //  ExpandAll  //  
                Cancel 
               to get a reasonably simple expression for y
Calculus
D[expr, var] partial derivative
Dt[expr, var] total differential
Limit[expr,var-> limit] limit
Integrate[expr, var] indefinite integral
Integrate[expr,{var,  start,  end] definite integral
Sum[expr, iterator] sum over some variable
Product[expr, iterator] product over some variable
Exercises
1. Use this assignment.f = x^2  -  6 a x^3  +  8 b x^4  +  10;Then evaluate each of the following expressions.D [f, x]
 	Integrate[f, x]
 	Integrate[f, {x, 0, 1}]
 	Integrate[f, x, x]
 	Dt[f, x]
 	Dt[ x^2  -  6 a x^3  +  8 b x^4,  x,  
          Constants -> {a, b}]
 	Limit[Sin[x]/x,  x -> 0]
 	Sum[1/(x^3), {x ,  1,  10,  0.5}]
2. The period P of a pendulum of length L is repeatedly measured to determine a value for g . The expression for g isg = 4 (π^2) L/(P^2).Apply the total derivativeDtto g and use it to relate the uncertainty in g to the uncertainty in measured values for L and \(P . 
Differential\) \(equations
?DSolve\)
DSolve[eqn, y[x], 
        x] solves a differential equation for the
functions y[x], 
    with independent variable x . 
        DSolve[{eqn1, 
            eqn2,  ... }, {y1[
              x1,  ... ],  ... }, {x1,  ... }] solves a list of
\(differential\ equations . 

          Use\ a\ symbol\ to\ store\ the\ solution . 

          Clear[y, x, sol];\)
sol = 
      DSolve[y'[x] == -y[x], y[x], 
        x]
{{y[x] -> (E^(-x)) C[1]}}
The result is a rule for replacing y . 
          Use this rule to define the solution to the equation . 
          We do not want the result presented as a list with one element . So index into when assigning the solution to a function . 
          Also,the symbol C[1] is built intoMathematica.Substitution is needed to set it . Here is t is a good idea to useSetfor the assignment so that the right side need only be evaluated this \(time . 
ys[x_]\)=y[x] /. sol[[1]] /. 
          C[1] -> y0
(E^(-x)) y0
\(Here\ is\ a\ second\ order\ ODE . 
Clear[x, t];\)
sol = 
      DSolve[x''[t] == -x[t], x[t], 
        t]
{{x[t] -> C[2] Cos[t] - C[1] Sin[t]}}
When initial conditions are given,Mathematicauses them to determine the \(constants . 
sol\)=DSolve[{x''[t] == -x[t], 
            x[0] == 2, x'[0] == 0}, x[t], 
          t]
{{x[t] -> 2 Cos[t]}}

Algebra
Algebraic operations
Expand
Factor
Together
Apart
Cancel
Simplify
Expand[(x + y)^2 + 7 (3 + x) (x + y)]
21 x + 8 (x^2) + 21 y + 9 x y + (y^2)
The symbol%refers the result from the immediately previous execution,notnecessarily the result from the precedingcell.
Factor[%]
(x + y) (21 + 8 x + y)
(This is theprefixform of a function.)
Expand[Sqrt[a^2 t^2]]
(Sqrt[(a^2) (t^2)])
\(No\ assumption\ is\ made\ about\ the\ sign\ of\ a\ or\ t\ so\ the\ root\ is\ not\ taken . 
PowerExpand[%]\)
a t
\(Note\ that\ if\ a < 0\ or\ t < 0\ \((but\ not\ both)\), 
          this\ answer\ may\ not\ be\ what\ we\ want . 

              Together[1/\((x + 1)\) - 2\ x/\((1 - x)\)^2]\)
((1 - 4 x - (x^2))/((((-1 + x))^2) (1 + x)))
\(Apart[%]
 - 2\/\((\(-1\) + x)\)\^2 - 2\/\(\(-1\) + x\) + 
            1\/\(1 + x\)\)
\(Simplify[%]
 - \(\(-1\) + 4\ x + x\^2\)\/\(\((\(-1\) + x)\)\^2\ \((1 + x)\)\)\)
\(Factor[%]
 - \(\(-1\) + 4\ x + x\^2\)\/\(\((\(-1\) + x)\)\^2\ \((1 + x)\)\)\)
Algebra with a Palette
These operations can be carried out by using a palette to apply transformations in an output cell . From the menu chooseFile/AlgebraicManipulation.Next,\(evaluate\ the\ cell\ below . 
\((x + y)\)^2\  + \ 
              7\ \((3\  + \ x)\)\ \((\ x\  + \ y)\)\)
7 (3 + x) (x + y) + (((x + y))^2)
Place the cursor somewhere in the output cell inside the last term and click the mouse repeatedly until this part of the output is highlighted . The chooseExpandfrom the palette . A new cell will appear but it will be anInputcell! In it you will see the last term expanded . Place the cursor somewhere in the first term in this same cell and click until it is highlighed.ChooseExpandagain.Note that the last output cell changes but a new one is not produced . Click anywhrere in this expression until it is all highlighted . Now chooseFactor.
7 (3 + x) (x + y)+(((x + y))^2)
(x + y) (21 + 8 x + y)
Vectors and Matrices
Vector
A vector can be represented as list. 
u={u1, u2, u3};
Matrix
\(A\ matrix\ is\ a\ list\ with\ two\ levels, \(the\ second\ level\ being\ lists\ of\ equal\ length . 
m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 
                  9}};\)\)
The function Dimensions gives the number of columns and rows of a matrix.
Dimensions[m]
{3, 3}
We can display a matrix in the usual way with MatrixForm.
MatrixForm[m]
(({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))
But never make an assignment of this form
n  =  MatrixForm[{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}];
because n will not be a matrix; the head will beFullForminstead ofList.
FullForm[n]
MatrixForm[
                List[List[1, 2, 3], List[4, 5, 6], List[7, 8, 9]]]
Assign the matrix to nbeforeyou applyMatrixFormto display \(it . 
\((n = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})\)\)//MatrixForm
(({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))
Tensor
\(A\ tensor\ is\ a\ list\ with\ three\ or\ more\ levels . 
\((t = {{{0.1, 0.2}, {0.3, 0.4}}, {{0.5, 0.6}, {0.7, 0.8}}, {{0.9, 
                          1. }, {1.1, 1.2}}, {{1.3, 1.4}, {1.5, 1.6}}})\) // 
            MatrixForm\)
(({{(({{0.1`}, {0.2`}})), (({{0.3`}, {0.4`}}))}, {(({{0.5`}, {0.6`}})), (({{0.7`}, {0.8`}}))}, {(({{0.9`}, {1.`}})), (({{1.10000000000000008`}, {1.19999999999999996`}}))}, {(({{1.30000000000000004`}, {1.39999999999999991`}})), (({{1.5`}, {1.60000000000000008`}}))}}))
Dimensions[t]
{4, 2, 2}
Vector and matrix operations
u . v dot product Dot[u, v]
Transpose[m] transpose of matrix m
Inverse[m] inverse of a matrix
Det[m] determinant of a matrix
The scalar or dot product of two lists is a contraction of the last index of the first list with first index of the second list . By "contraction of indices" is meant setting two indices with equal ranges equal to each other and then summing over the full range . The dot product of two multidimensional lists is defined as follows:u  .  v      ==          (∑_j) (Subscript[u, ij]) (Subscript[v, jklmn])TheDotproduct ofMathematicafollows this convention of tensor analysis and does not distinguish between row vectors and column vectors . Here is the dot product of two 3-\(vectors . 

                      Clear[a, b, c, d, e, f]\);
{a, b, c} . {d, e, f}
a d + b e + c f
m = {{a, b}, {c, d}};
m . {e, f}
{a e + b f, c e + d f}
{e, f} . m
{a e + c f, b e + d f}
Equations
   You have seen that  x = expr actually causes x to be replaced by expr in any expression that Mathematica evaluates; it is an assignment.  But in mathematics an equation  x = expr  is really a relation that  is sometimes used to replace the quantity on the left hand side, and sometimes solved for a symbol appearing on the right hand side .   In Mathematica we distinguish between an assignment and an equation very explicitly.
Expression for an equation
    In Mathematica the symbol used to express an equation is the logical symbol  (==). 
         l.h.s. == r . h . s . ,
If both sides of an equation can be evaluated, Mathematica will return the result  True or False.
2+2==5
False
Exercises
1.  Evaluate the following equation for n  =  
              1,  2,   ... ,  
            20 to determine the value of the machine epsilon on your computer .   (Hint :  Use a list.)
1 == 1 + 1.0 (10^(-n))
2. Evaluate $MachinePrecision to check your result.
Solving algebraic equations
Solve[eqn,  symb] list of rules for assignment of solution
Solve[{eq1,  eq2,  ... }, {var1,  var2,   ... }] list of rules for assignment of solution
Single equation
Many equations can be solved by using Solve.  Use a symbol to store the solution so that you can work with it.
Clear[eq, soln, x, a, b, c];
eq1 =  a (x^2) + b x  + c == 0; 
sol1 = Solve[eq1, x]
{{x -> ((-b - (Sqrt[(b^2) - 4 a c]))/(2 a))}, {x -> ((-b + (Sqrt[(b^2) - 4 a c]))/(2 a))}}
	Mathematica has returned two rules for assigning a solution of the equation to x.  But no value has been assigned to x.  In fact, as already explained you should avoid making assignments to symbols that are being used as variables .   Assign one of the solutions to a different symbol by choosing to use one of these rules with ReplaceAll.
xs=x /. sol1[[2]]
((-b + (Sqrt[(b^2) - 4 a c]))/(2 a))
You can always verify thatxssatisfies the equation by using \(substitution . 
eq1\)/.x -> xs
c + ((b (-b + (Sqrt[(b^2) - 4 a c])))/(2 a)) + ((((-b + (Sqrt[(b^2) - 4 a c])))^2)/(4 a)) == 0
It is necessary toSimplifythe left side before Mathematica can verify that xs is a solution . Use theAlgebraicManipulation palette by placing the cursor into this output cell on the left side and repeatedly clicking until it is completely highlighted . Then chooseSimplifyfrom the palette.AnInputcell will appear as you do this and the operations done with the palette will all be done in this same cell . You will see the following result,\(showing\ that\ xs\ is\ a\ solution\ to\ the\ equation . 

                  0 == 0\)
	Mathematicaalways returns a list of lists as the solution to an equation,\(even\ when\ there\ is\ only\ one\ solution . 
sol2 = 
              Solve[a\ x\  + \ b\  == c, x]\)
{{x -> -((b - c)/a)}}
\(So\ you\ must\ index\ into\ the\ list\ of\ rules, 
          even\ though\ there\ is\ only\ one . If\ you\ do\ not, 
          you\ assign\ a\ list\ to\ xs\ instead\ of\ an\ algebraic\ expression . 
xs = x /. sol2\)
{-((b - c)/a)}
In the case of one solution you can also useFirstto pull out the first,and only,\(rule . 
xs = x /. First[sol2]
 - \(b - c\)\/a\)
Multiple equations
\(If\ you\ have\ more\ than\ one\ equation\ to\ solve, \(you\ just\ include\ them\ in\ a\ list\ and\ specify\ the\ unknowns\ in\ a\ second\ list . 
Clear[x, y, a, b];\)\)
eq3 = {(x^2) - y == a,  x/y  ==  b}; 
sol3 = Solve[eq3, {x, y}]
{{x -> ((1 - (Sqrt[1 + 4 a (b^2)]))/(2 b)), 
              y -> ((1 - (Sqrt[1 + 4 a (b^2)]))/(2 (b^2)))}, {x -> ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 b)), 
              y -> ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 (b^2)))}}
There are two solutions for x and y . 
                If you want to use the second solution,you can define symbolsxsandysthat satisfy the equation in one \(step . 
{xs, ys}\)={x, y} /. sol3[[2]]
{((1 + (Sqrt[1 + 4 a (b^2)]))/(2 b)), ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 (b^2)))}
\(Verify\ the\ solution . 
eq3 /. {x -> xs, y -> ys} // 
            Simplify\)
{True, True}
Elimination
\(It\ is\ useful\ to\ be\ able\ to\ eliminate\ variables\ from\ simultaneous\ equations . 
              There\ are\ two\ operations\ for\ doing\ this . 

              Eliminate[{eq1,  ... }, {var1,  ... }]\ eliminates\ variables\)
Reduce[{eq1,  ... }, {var1,  ... }] logical expressions
\(Let' 
              s\ try\ this\ on\ the\ eq3\ that\ was\ solved\ in\ the\ last\ section . 
Clear[x, y, a, b];\)
eq4 = Eliminate[eq3, y]
a b == x (-1 + b x)
Verify that the solutions forxfound above come from solutions of this \(equation . 
Solve[eq4, x]\)
{{x -> ((1 - (Sqrt[1 + 4 a (b^2)]))/(2 b))}, {x -> ((1 + (Sqrt[1 + 4 a (b^2)]))/(2 b))}}
 	Reduce eliminates symbols from a set of equations but returns the result as a rigorous set of logical equations .   Apply this symbol to eq3, but enter eq3 explicitly so that it an be compared with the solution.
Reduce[{(x^2) - y == a, (x/y) == b}, y]
a ≠ 0 && y == -a && b == 0 && x == 0 || 
            b ≠ 0 && x ≠ 0 && b x == 1 && y == (x^2) && 
              a == 0 || a ≠ 0 && b ≠ 0 && 
              x ≠ 0 && -1 + b x ≠ 0 && 
              a b == x (-1 + b x) && y == -a + (x^2)
Refer to the relational and logical operators to interpret this output.
Use the symbols in this table to read the result returned byReduce.The symbol&&stands forANDand the symbol||stands forOR.The different solutions are separated byOR.So,the first set of conditions for a solution are
a ≠ 0 && y == -a && 
            b == 0 && x == 0
which can be translated as
\("a not equal to zero AND y equal to -a AND b equal to zero AND x equal to zero" . 
Exercise\)
Use Eliminate to find the trajectory of a projectile in a vacuum by eliminating the time from the equations  (Remember to assign each equation to a symbol for ease in manipulation and to clear each symbol of any previous values.)
       Clear[x, x0,  v0, theta,  t,  y,  y0,  v0,  t,  
                g];
       xeq  =  x  ==  v0 Cos[theta] t ;
       yeq = y == v0 Sin[theta]  t  - (1/2) g (t^2);
\(Proceed\ as\ follows . 
\ \ \ \ \ \ \ \ \ \ 1. \ Eliminate\ the\ time\ from\ the\ equations\), calling the result eqxy
          2. Use soln =Solve[ eqxy ,  y ] to find a rule for defining y as a function of x
          3. Use ysol = y  /.   soln[[1]]  //  ExpandAll  //  
                Cancel 
               to get a reasonably simple expression for y
Calculus
D[expr, var] partial derivative
Dt[expr, var] total differential
Limit[expr,var-> limit] limit
Integrate[expr, var] indefinite integral
Integrate[expr,{var,  start,  end] definite integral
Sum[expr, iterator] sum over some variable
Product[expr, iterator] product over some variable
Exercises
1. Use this assignment.f = x^2  -  6 a x^3  +  8 b x^4  +  10;Then evaluate each of the following expressions.D [f, x]
 	Integrate[f, x]
 	Integrate[f, {x, 0, 1}]
 	Integrate[f, x, x]
 	Dt[f, x]
 	Dt[ x^2  -  6 a x^3  +  8 b x^4,  x,  
          Constants -> {a, b}]
 	Limit[Sin[x]/x,  x -> 0]
 	Sum[1/(x^3), {x ,  1,  10,  0.5}]
2. The period P of a pendulum of length L is repeatedly measured to determine a value for g . The expression for g isg = 4 (π^2) L/(P^2).Apply the total derivativeDtto g and use it to relate the uncertainty in g to the uncertainty in measured values for L and \(P . 
Differential\) \(equations
?DSolve\)
DSolve[eqn, y[x], 
        x] solves a differential equation for the
functions y[x], 
    with independent variable x . 
        DSolve[{eqn1, 
            eqn2,  ... }, {y1[
              x1,  ... ],  ... }, {x1,  ... }] solves a list of
\(differential\ equations . 

          Use\ a\ symbol\ to\ store\ the\ solution . 

          Clear[y, x, sol];\)
sol = 
      DSolve[y'[x] == -y[x], y[x], 
        x]
{{y[x] -> (E^(-x)) C[1]}}
The result is a rule for replacing y . 
          Use this rule to define the solution to the equation . 
          We do not want the result presented as a list with one element . So index into when assigning the solution to a function . 
          Also,the symbol C[1] is built intoMathematica.Substitution is needed to set it . Here is t is a good idea to useSetfor the assignment so that the right side need only be evaluated this \(time . 
ys[x_]\)=y[x] /. sol[[1]] /. 
          C[1] -> y0
(E^(-x)) y0
\(Here\ is\ a\ second\ order\ ODE . 
Clear[x, t];\)
sol = 
      DSolve[x''[t] == -x[t], x[t], 
        t]
{{x[t] -> C[2] Cos[t] - C[1] Sin[t]}}
When initial conditions are given,Mathematicauses them to determine the \(constants . 
sol\)=DSolve[{x''[t] == -x[t], 
            x[0] == 2, x'[0] == 0}, x[t], 
          t]
{{x[t] -> 2 Cos[t]}}