Amherst College						February 3, 2004

Introduction to Mathematica

Andy Anderson
Curricular Computing Services

Part I: Numerical Manipulation

Part II: Symbolic Manipulation

Symbols and Algebra

Symbolic Calculations

Mathematica was first and foremost a "symbolic manipulation" program, so symbols or variables can be used anywhere a number might be in expressions:

(4 + 2 x + 3 (x^2)) + (1 + x + 7 (x^2))

There are many algebraic functions available for expressions such as the above:

Factor[1 - (x^2)]

Expand[%]

Together[((1 - x)/(1 + x)) +  ((-4 + 3  x)/(x + 2))]

Apart[%]

Roots of polynomial equations can also be determined using the Solve function,  which provides a list of answers:

Solve[5 + 3 x + 10 (x^2) ==  0,  x]
%[[1, 1]]

The operator "->" is a "rule" that can be used to map its left- to its right-hand side.
The operator "/." applies a rule to an expression:

5 + 3 x + 10 (x^2) /. %
Simplify[%]

Trignometry

Circular and hyperbolic trignometric algebra is also possible:

TrigReduce[2Sin[θ]Cos[θ]]

TrigExpand[Tanh[θ + φ]]

TrigToExp[Cos[θ]]
TrigToExp[Sinh[θ]]

Assignments and Functions

Assignments

As we have already seen, mathematical expressions can be assigned to symbols or variables in the usual way with the "=" operator:

a  =  2 + 3;
a

Note that, when an assignment is evaluated, the expression on the right-hand side is also evaluated and the result output.

Evaluation can be prevented by using a delayed evaluation assignment
 (which also suppresses output):

d =  5;
\(c = \(\(2\)\(+\)\(d\)\(	\)\( (*\ not\ delayed, \ 
          c\  = \ 7\ immediately\ *) \)\)\)

\(\(\(\(d = \ 3;\)

    c\)\(			\)\( (*\ c\  = \ 7\ still\ *) \)\)\)

\(\(\(c\  := \ \(\(2\)\(+\)\(d\)\(	\)\( (*\ delayed, \ 
          c\  = \ 2 + d\ still\ *) \)\)

    c\)\(\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \)\( (*\ 
      c\ evaluated\ with\ d\  = \ 3\ *) \)\)\)

d  =  9;

    c

If a math expression depends on an earlier expression that is unevaluated, they can be evaluated in order if their common cell group is selected and evaluated:

r =  1

b  =  r + 2

Functions

A more general type of assignment is a function definition:

maxwellBoltzmann[v_, vm_, n_] := ((4 n)/((Sqrt[π]) (vm^3))) 
        (v^2) (E^(-(v^2)/(vm^2)))
maxwellBoltzmann[5, 30. , 100. ]

Note that the independent variables in the function definition (the "arguments") must be distinguished by an appended "_" (which indicates that they are patterns or placeholders).
  
Any value or variable can be used in place of these arguments:

v  =  (7/2); vm = (Sqrt[30]); n = 200;
maxwellBoltzmann[v, vm, n]
n = 200. ;    
maxwellBoltzmann[v, 
      vm, n]

To recall a function definition, use the "?" operator:

?maxwellBoltzmann

To delete an assignment or function definition, use the Remove function:

Remove[a,  b,  c,  v,  vm,  n,  
      maxwellBoltzmann]
{a,  b,  c, v, vm, n}
maxwellBoltzmann[1,  2, 3]

It is advisable to avoid using capital letters to begin the names of symbols (variables or functions), to avoid collision with Mathematica's symbols.

Calculus

Mathematica can perform many basic and advanced calculus tasks.

Total Derivatives

The total derivative of a function is a straightforward application, using the chain rule if necessary:

f[x_] = (Sqrt[1 + (x^2)]);
f'[x]

Higher-order derivatives are also possible:

f''[x]

A total derivative can also be represented by:

Dt[f[x], x]

and for higher orders by:

Dt[f[x], {x, 2}]

This form can be used with expressions, too:

Dt[(x^2), x]

Note that any unspecified symbols in a function are assumed by a total derivative to be dependent, unless otherwise specified:

maxwellBoltzmann[v_, vm_, n_] := ((4 n)/((Sqrt[π]) (vm^3))) 
        (v^2) (E^(-(v^2)/(vm^2)))
Dt[maxwellBoltzmann[v, vm, n], v]

Dt[maxwellBoltzmann[v, vm, n], v, 
      Constants -> {vm,  n}]

We could then use the Solve function to calculate the maximum velocity of this distribution:

Solve[% == 0, v]

Partial Derivatives

Partial derivatives can be specified, as well:

D[maxwellBoltzmann[v, vm, n], v]

D[maxwellBoltzmann[v, vm, n], n]

Note that for a partial derivative, unspecified symbols are assumed to be independent,
  unless otherwise specified:

D[maxwellBoltzmann[v, vm, n], n, NonConstants -> {vm}]

The palette provides another way to represent a partial derivative:

(∂_v) maxwellBoltzmann[v, vm, n]

Integrals

Integrals are also built-in, and Mathematica provides just about every evaluation known to mathematicians, as efficiently as currently possible:

Integrate[(1/x), x]

Integrate[(1/x), {x,  1,  2}]

The palette provides a represention of an integral in the standard mathematical format:

$Assumptions = vm ∈ Reals && vm > 0;   

(1/n) (∫_0^∞) 
          v maxwellBoltzmann[v, vm, 
            n] \[DifferentialD]v

Plotting Functions

In addition to plotting data, Mathematica can directly graph functions in both two and three dimensions.

2-D Direct Plots

A one-dimensional function, i.e. the points {x, f(x)}, can be plotted using the function Plot:

Plot[maxwellBoltzmann[v, 30, 100], {v, 0, 100}, 
      AxesLabel -> {"v", "ΔN"}, 
      PlotStyle -> Hue[0]]

Note that this is also a ⁃ Graphics ⁃ object, and so the same options are available as for ListPlot.

Functions such as these are plotted by evaluating them at a number of sample points and plotting those points with a connecting line.
The precision of this plotting is determined by a function-only option, PlotPoints, which has a default value of 25:

Plot[maxwellBoltzmann[v, 30, 100], {v, 0, 100}, 
        AxesLabel -> {"v", "ΔN"}, 
        PlotStyle -> Hue[0], PlotPoints -> 8, 
        PlotDivision -> 1];

(Plot also uses an intelligent procedure to choose sample points which is turned off with the PlotPoints option above.)

3-D Direct Plots

To graph a two-dimensional function directly, i.e. as {x, y, f(x, y)}, use Plot3D:

pvdw[v_, 
          t_]  :=  (((8314.3 t)/(v - 0.0234)) - 3440/(v^2)) 
          (10^(-5))  

Plot3D[
pvdw[v, t],   
{v, 0.03, 0.6},   (* range of x variable *)
{t, 0, 20},            (* range of y variable *)
PlotRange -> {{0.03, 0.6}, {0, 20}, {0, 
              20}},
\(AxesLabel -> {\*""Specific Volume ((m^3)/Kmol)"", "Temperature (K)", \*""Pressure (\!\(10\^\(\(5\)\(\\ \)\)\)N/(m^2))""}\),
PlotPoints -> 40,
ViewPoint -> {0.5, -5, 5},
BoxRatios -> {1, 1, 1}
]

Note that this an object of type ⁃ SurfaceGraphics ⁃.

Density and Contour Plots

Density and contour plots can be another useful way to visualize distributions:

DensityPlot[maxwellBoltzmann[v, vm, 100], {v, 0, 100}, {vm, 10, 50}, 
      Axes -> True, AxesLabel -> {"v", "vm"}, 
      PlotPoints -> 60]
ContourPlot[maxwellBoltzmann[v, vm, 100], {v, 0, 100}, {vm, 10, 50}, 
      Axes -> True, AxesLabel -> {"v", "vm"}, 
      PlotPoints -> 60]

Note that these are, again, different types of graphics, ⁃ DensityGraphics ⁃ and ⁃ ContourGraphics ⁃.

Combining Plots

In Mathematica, plots are objects that can be manipulated by other functions.
So, for example, you can create a plot in advance and display it later:

d  =  {{0, 0}, {5, 0.19}, {10, 0.77}, {15, 1.56}, {20, 
            2.14}, {25, 2.67}, {30, 2.70}, {35, 2.61}, {40, 2.30}, {45, 
            1.73}, {50, 1.29}, {55, 0.82}, {60, 0.58}, {65, 0.32}, {70, 
            0.16}, {75, 0.10}, {80, 0.03}, {85, 0.01}, {90, 0.01}, {95, 
            0.00}, {100, 0.00}};

    dPlot = 
        ListPlot[d, AxesLabel -> {"v", "N"}, 
          DisplayFunction -> Identity];

           

    mbPlot  =  
        Plot[maxwellBoltzmann[v, 30, 100], {v, 0, 100}, 
          AxesLabel -> {"v", "N"}, PlotStyle -> Hue[0], 
          DisplayFunction -> Identity];

The plot output is controlled with the option DisplayFunction, which by default is set to $DisplayFunction (usually meaning the computer screen); setting it to Identity prevents display.
The Show command is similar to the Print command for text; it displays any type of previously defined graphics object.
If two graphics objects of the same kind are listed, they will be combined together into a single plot:

Show[dPlot, mbPlot,DisplayFunction -> $DisplayFunction];

Fitting Data to Functions

Mathematica has a number of tools to compare data to functions.

Fitting Data to a Linear Combination of Functions

The Fit function can be used to match data to a linear combination of functions, such as a polynomial (including lines).
Fit uses a least-squares fit by default:

f1[v_]  =  Fit[d, {1, v}, v]

      

    f2[v_]  =  Fit[d, {1, v, (v^2)}, v]   

    f3[v_]  =  Fit[d, {1, v, (v^2), (v^3)}, v]

f1Plot  =  
        Plot[f1[v], {v, 0, 100}, AxesLabel -> {"v", "N"}, 
          PlotStyle -> Hue[0], 
          DisplayFunction -> 
            Identity];
f2Plot  =  
        Plot[f2[v], {v, 0, 100}, AxesLabel -> {"v", "N"}, 
          PlotStyle -> Hue[1/3], 
          DisplayFunction -> 
            Identity];
f3Plot  =  
        Plot[f3[v], {v, 0, 100}, AxesLabel -> {"v", "N"}, 
          PlotStyle -> Hue[2/3], 
          DisplayFunction -> Identity];
Show[dPlot, f1Plot, f2Plot, f3Plot,DisplayFunction -> $DisplayFunction];

If you want the statistical characteristics of these fits, you can load the Statistics`LinearRegression` package and use Regress with the same arguments as Fit:

<< Statistics`LinearRegression`

Regress[d, {1, v, (v^2), (v^3)}, v]

Fitting Data to a Nonlinear Function

The NonlinearFit function can be used to match data to a particular functional form, using a least-squares fit to some or all of its parameters (other fits can be specified, though).
To use NonlinearFit, you must first load the Statistics`LinearRegression` package.
It generally helps to include a starting point for the parameters to be determined (vm and n here):

<< Statistics`NonlinearFit`

nlf  =  
      NonlinearFit[d, maxwellBoltzmann[v, vm, n], 
        v, {{vm, 30}, {n, 100}}]

mbPlot  =  
        Plot[nlf, {v, 0, 100}, AxesLabel -> {"v", "N"}, 
          PlotStyle -> Hue[0], 
          DisplayFunction -> Identity];
Show[dPlot, mbPlot,DisplayFunction -> $DisplayFunction];

If you want the statistical characteristics of these fits, you can use NonlinearRegress with the same arguments as NonlinearFit:

NonlinearRegress[d, maxwellBoltzmann[v, vm, n], 
      v, {{vm, 30}, {n, 100}}]