PHY 110      Mathematica Introduction         R. Martin

Mathematica is a powerful and flexible tool for doing math, modeling, graphics and visualziation, and much more.  We can't hope to cover  all its features here, so I'll concentrate on some basic functions, those of a calculator and plotter, algebra, and calculus.  Even though it's beyond this class, I'll also show some differential equation solutions.  This should give you a taste of what else you might do with the software in future courses and research projects..

Some Basics:

Notebooks, components, and handles

Mathematica understands a large vocabulary of math and graphics commands.  In addition it contains a powerful programming language and user-interface commands.  We'll concentrate on the basic math and graphics here.

This document is a Mathematica notebook, a collection of commands, text, graphics, etc. that is designed for a specific purpose (in this case, to introduce you to the program).  Notebooks are made up component parts,each of which usually has a "handle" on the right side of the page ->

For example this text has a handle which looks like a right-bracket with a small extra line near the top.  So does the handle associated with the heading "Notebooks, components, and handles" just above this region.  

Those handles are grouped inside of another handle that looks like a plain right-bracket.  Try double-clicking on this "group" handle right now: put the cursor near it and double-click.  What happens?  Hopefully, you figured out that you could double-click on the resulting "reduced" handle (with a little triangle at the bottom) and re-expand the text regions.  

Now you know what to do if you see a notebook with reduced handles in it, like you might see below...

By the way, to create new text or commands, just position the cursor outside of any handle and begin typing.

Mathematica Commands

All Mathematica commands begin with an upper case Letter and use square brackets for arguments. To run a command, put the cursor anywhere within the command or its handle and press the "enter" key (not return!)  Here are some examples of basic commands.  As you progress through this section, run each command to see how it works.

Calculator:

For simple number calculations, you can ask for as many significant figures as you want, as in the second argument to the "Number" command below.  Try running it (click on it once and press the "enter" key) and see what you get:

N[(Sqrt[π]),200]

Try editing the above command by changing the number 200 to some other integer and see what happens.  Mathematica allows you to change previous commands at any time (so you need to be careful to re-run anything that depends on the changed results.)

If you don't give numbers, Mathematica will keep its answer in variable form:

p = Cos[x1] Log[y1]

then you can evaluate the function p for for specific x1 and y1 values with the slash-dot "/." command, which I read as "evaluated at":

p /. x1->π/3

% /. y1->16

%% /. y1->16.

Note in the above examples the use of "%" for "previous output" and "%%" for "previous output 2 commands before".  Also note that setting y1 to "16." (with the decimal point) tells Mathematica to give an approximate decimal numerical answer, while "16" (without the decimal point) yields an exact answer.

If you put a number after the % sign it means "the output labeled with that number", so "%3" means "output labeled 3":,

%3 /. y1->17.

This is equivaqlent to using the full "Out[3]":

Out[3] /. y1->17.

Mathematica can calculate virtually any function known to mathematics.  Here are a few more examples (look them up in the online help if you aren't familiar with these functions...)

Log[23.5]ArcTan[76.0]

Exp[0.3]/BesselJ[12.5,1]

BesselK[7/2,n]

% /. n->4

N[%,23]

LegendreP[2,x] SphericalHarmonicY[1,1,θ,ϕ]

2-D plotter:

The basic 2-D plot command takes 2 arguments: the function to be plotted and the domain to plot over. Mathematica chooses the default scaling of axes:

Plot[(((2 (x^2)+ 3 x)Cos[x]Log[x+1])/(((x^3)- 1))),{x,0,10}]

You can add a variety of options to the Plot command to make it fit your needs and esthetics:

Plot[(((2 (x^2)+ 3 x)Cos[x]Log[x+1])/(((x^3)- 1))),{x,0.001,10}, PlotRange->{-2,2},PlotPoints->50,Frame->True,FrameLabel->{"x","f(x)"},RotateLabel->False]

To find out what options are available, use the Options command, which lists them and their default values.  Again, the Mathematica online help utility is pretty good, and usually gives some examples (but never enough...).

Options[Plot]

If you want to know what any of these options actually do to a plot, select one of them (e.g. PlotPoints) with the mouse and choose "Find Slected Function" in the Help pulldown menu (select Help from menu bar).

You can plot multiple curves and give each curve a different line style or color using the PlotStyle option, although it may take some experimentation to tweak your plot so it looks 'perfect'.  Here's a plot of the curve above and two square root functions:

Plot[{(((2 (x^2)+ 3 x)Cos[x]Log[x+1])/(((x^3)- 1))),(Sqrt[(x/2.2)]),-(Sqrt[(x/2.2)])},{x,0.001,10}, PlotRange->{-2,2},PlotPoints->50,Frame->True,FrameLabel->{"x","f(x)"},RotateLabel->False,PlotStyle->{{Hue[0.05],Thickness[0.011]},{Hue[0.6],Dashing[{0.05,0.05}]},{Hue[0.8]}}]

In the above example, there are 3 curves plotted (the three functions in braces after the Plot command) and 3 styles defined in braces after the PlotStyle command - one for each curve in the same order as the curves are listed.  Thus the first curve has its color and thickness changed, the second has a different color and is dashed, and the third curve just has its color changed.  Learn more from the online help, or just experiment yourself.

Mathematica also knows all the "special functions" that crop in advanced physics and engineering, such as elliptic functions, Bessel functions, spherical harmonics, hermite polynomials, etc.   You can plot these as well.  Let's compare the sine function with the elliptic function analogous to the sine function, the Jacobi "sn" function (this function describes the motion of a pendulum with large amplitude):

Plot[{JacobiSN[x,0.9],Sin[x/1.645]},{x,0,12},PlotStyle->{{Hue[0.6],Thickness[0.008]},{Dashing[{0.02,0.02}],Thickness[0.006],{Hue[1]}}},Frame->True]

Algebra:

Mathematica can solve equations, like the good old quadratic equation:

soln = Solve[A (x^2) + B x + C == 0, x]

Or, try a simple trig equation:

soln = Solve[Sin[x] == π/5,x]

soln2=Normal[soln]

Note that the answer it gives is, on the one hand, exact (i.e. it's left in terms of the irrational number π rather than approximating a numerical answer, and two “groups” of answers are given, since two angles around the circle have a sine value of π/5) while on the other hand, Mathematica gives a very general answer in terms of integer additions of 2π.  Of course, you can ask for a numerical approximation, but note that you have to choose a value for the arbitrary integer C[1]:

N[x /. (soln2 /. C[1]->0),12]

Mathematica will also do calculations algebraically, for example it can factor and cancel:

Simplify[((((x + 1))^2)/(((x^2) - 1)))]

You can also tell Mathematica that it should use its knowledge of trigonometric identities, for example:.

2  ((Cos[θ])^2)-((Sin[θ])^2)

Simplify[2  ((Cos[θ])^2)-((Sin[θ])^2),Trig->True]

There are, of course, some equations that Mathematica can't solve - i.e. those no one can solve.  For example, consider the transcendental equation x = cosx:

Solve[ x==Cos[x],x]

Mathematica tells us that it thinks this equation cannot be solved.  For equations like this with no closed-form solution, you can ask Mathematica to solve numerically for an approximate solution using its root finder:

FindRoot[ x==Cos[x],{x,0}]

These examples barely scratch the surface of what Mathematica can do algebraically.  You'll be amazed how proficient it is at tedious derivations that would drive a human crazy - but you must understand how it works and have some mathematical knowledge to take advantage of it!

Calculus:

Whether you're currently taking claculus or not, you probaby won't be surprised to learn that Mathematica can do calculus, too.  Derivatives (the (∂_x)notation means the same in this case as d/dx):

gx = (∂_x) (A (x^2) Sin[x])

indefinite integrals:

gxi = ∫gx\[DifferentialD]x

Sometimes Mathematica seems stupid - we can easily see that there are two terms that cancel in the above expression - but we have to ask Mathematica (politely) to simplify in order to see that:

gxi = Simplify[gxi]

limits:

lm = Limit[((2 (x^2) + 1)/(5(x^2) -3)),x->Infinity]

and definite integrals:

rms = (1/(2 π))(∫_0^(2 π))((Cos[x])^2)\[DifferentialD]x

You can also do calculus with special functions:

(∂_x) BesselJ[1,x]

∫HermiteH[n,z]\[DifferentialD]z

If you need numerical values for complictaed integrals, or those involving special functions, you can either evaluate with the N[...] command or do a numerical integrals.  For example, this integral comes up in statistical analysis:

(∫_0^2)(E^(-(x^2)))\[DifferentialD]x

The result is called the "Error function", which is just another name for this integral.  If you want to know its value:

N[%,10]

Differential Equations:

Why stop there?  While the topic of differential equations is a little beyond the level of our course, it's still worth knowing that Mathematica can do them.  If you apply Newton's second law to a mass on a spring you get the differential equation for a harmonic oscillator (the prime stands for derivative):

soln = DSolve[x''[t] + (ω^2)x[t] == 0,x[t],t]

The solution tells us that the mass oscillates with a sinusiodal time dependence.  In the above example, since we didn't supply the initial conditions for the mass, Mathematica gives the answer in terms of two arbitrary constants, C[1] and C[2], but we can also give it explicit initial conditions:  initial position x(t=0) and initial velocity x'(t=0)

soln = DSolve[{x''[t] + (ω^2)x[t] == 0, x[0] == 1, x'[0] == 4/5},x[t],t]

Here's a slightly more complicated problem - a damped harmonic oscillator:

soln = DSolve[{x''[t] +  γ x'[t] + (ω^2)x[t] == 0, x[0] == 1, x'[0] == 0},x[t],t]

You can plot these solutions if you give values to the constant parameters.  For example, plot the damped oscillator position for frequency ω=1 and damping coefficient γ=0.1:

damped = x[t] /. soln /. {ω->1,γ->0.1};
Plot[damped,{t,0,40}]

Sometimes neither you nor Mathematica can solve an equation analytically, for example systems that have chaotic motion have no analytic solution.  In this case you can ask Mathemtaica for a numerical solution.  Here's a pendulum with a driving torque, making angle θ with the vertical and having angular velocity w:

pend=NDSolve[{θ'[t]==w[t],w'[t]==-((w[t])/5)-Sin[θ[t]]+10 Cos[3 t],θ[0]==2,w[0]==0},{θ,w},{t,0,100}]

The output looks incomprehensible, but the information is all there.  Here's one way to see it, by plotting θ vs. w:

ParametricPlot[Evaluate[{θ[t],w[t]}/.pend],{t,0,100},Frame->True,FrameLabel->{"θ (radians)","w ((s^(-1)))"},RotateLabel->False,AspectRatio->0.5]

Try to imagine the motion of that pendulum!  Actually, you don't have to imagine -- you can see it:

ParametricPlot3D[Evaluate[{t,Sin[θ[t]],Cos[θ[t]]}/.pend],{t,0,50},BoxRatios->{2,1,1},AxesLabel->{"time","x","y"},ViewPoint->{-5,-4,2}]

Here the x and y coordinates of the pendulum bob are plotted with time as the third dimension (this plots what Einstein called the world line of the pendulum).  So the pendulum starts swinging but soon gets pushed into partial rotation, followed by an erratic upside down oscillation!  Note that you can use the mouse to rotate this plot and view the pendulum trajectory from any viewpoint.

Perhaps you can begin to see how useful Mathematica can be in exploring physical systems.  We could also animate a picture of moving pendulum bob, but we’ll leave that for another day...