An Introduction to Mathematica

An Introduction to Mathematica
Welcome to the world of computational physics! This lab will give you the tools you need to
start exploring this discipline. Computational physics has developed into an effective method of
doing physics. It can be compared and contrasted with experimental and theoretical physics.
Essentially, it makes the claim that computer modeling and computer generated numerical
solutions are as informative as closed form solutions. What does this mean? If I solve the
differential equation y’(t) =y(t), most second-year physics students could rattle off the closed
form solution, that is, y = cet, a function expressed in a finite space. However, a simple computer
language, such as TrueBasic, would list off values of t and values of y, like so:
{(t,y)}={(0,1), (1, 2.718), (2, 7.389)…}
While this isn't very helpful when we know the closed form solution, it is very helpful when the
equation is impossible to solve! Situations like this arise in complex and/or nonlinear systems,
and in many problems of advanced theoretical physics. This makes values of functions
accessible, as well as their visualization, because to produce a graph you don't need a generating
function, just some values! This is very much “experimental” mathematics.
To get a start on this, we need a programming language. Mathematica is one that you may have
used previously in Multivariable Calculus and if you decide to remain a scientist, you'll probably
continue to use it throughout your career. It's THAT good. You can do almost anything in
Mathematica, you can make numerical calculations (as you would on a calculator), solve
algebraic equations, solve differential equations, do matrix algebra, integrate, create graphs and
animations...the list goes on and on. One wonderful thing about Mathematica, as opposed to
simpler languages, is that it recognizes common functions (such as ex), and thus can give you
closed form solutions in many, many cases. When it can't do that, it can generally give you a
numerical solution. It even handles imaginary numbers with ease. The only thing is doesn't do
for you is your homework (though it can help...). This lab will walk you through the basics,
helping you get comfortable with Mathematica as a tool you can use to help you do physics.
PART I: Getting Started
1. The Basics
The simplest way to get started is to open Mathematica. (Who would have thought?) When you
open the program you will be confronted with several windows. One will say "Welcome to
Mathematica" and offer to give you a tour. Close it. You can show yourself around. You will
also be confronted with a palette, a nice array of symbols so you don't have to enter the text
commands. Close the palette. You should first learn the hard way.
The big blank window is what is called the notebook. In this notebook, you will type in
commands and then hit "Shift-Return" or just "Enter" on the keyboard. Then Mathematica's
kernel (essentially, its brain) will evaluate the cell (as it is called) you have just entered. The
output will then be displayed in the notebook. Now you are ready to try a simple example. Try
the binary operation command "+". (What is a binary operation? It is a technical way of saying
you input two things and output one. Can you think of an example?) Try entering "2+2". What
happens? Surprising? Arithmetic really is just a system of binary operations. Can you guess what
the commands are for subtraction, multiplication, and division? How about exponents? Try some
things that are way too big for your TI-83. How about 3 to the 200th power? How about things
that are way too small? Divide 7 by 10 to the 100th power (1 followed by 100 zeros). You should
note two things here. What do calculators give you as an answer? Is the Mathematica answer
useful?
Department of Physics, Bryn Mawr College
9/3/09
The Mathematica answer probably isn't useful because in an effort to retain a closed form
solution (to make it exact) it has kept the quotient of these two numbers as a fraction. To get the
decimal solution, it is easy. You can enter a "prefix" operation "N[%]" on a new line. The "N"
command tells it to produce a numerical expression. "N" operates on "%", which means the "last
output". Try it. You can also use a "postfix" operation. It is the same operator "N" but you can
type in the operation at the end of the output line. The syntax is "...//N" where "..." is the output
you had. Why are these operations called prefix and postfix? For every command there is at least
a prefix and postfix form. There is another form, called "infix". What would that be? Infix is
really only useful for binary operations (in fact, you used it just a few minutes ago!). Try
"Plus[2,5]". (The prefix version of the infix operation "+".)
Another powerful aspect of Mathematica is that is can also do symbolic algebra, not just
numerical evaluation. Try entering "x+x". Try "(x3 + 3x2 y + 3x y2 + y3)/(x+y)". Hmmm... what
about "Simplify[%]"? Enter in the expression "x2+2x +1". Now try "Factor[%]". Can you guess
the command to expand this output to its original form? Play around with some other symbolic
examples.
Okay, now we have to go through some more syntax and definitions before we can really get
cranking. You might need to refer back to this section to reorient yourself later on, when error
messages start popping up.
1. Mathematica is case-sensitive. Try entering "sin[pi]". Did you get an error message? To
Mathematica "sin" is just a string of letters, but "Sin" is a command. Now try "Sin[pi]".
Hmm...can it not evaluate the sine of pi? Now try "Sin[Pi]". That's more like the sine of pi we
know and love. The same idea applies all over: In general, commands are capitalized.
2. Mathematica is sensitive to poor syntax. The most important time to remember your syntax is
when using brackets. Each bracket must have a partner of the same type facing the other way.
Enter "N[4/3". Note the error message. Now close the brackets and run it again. Much better.
There are three types of brackets. The first and most familiar are the parenthetical brackets, ( ).
Use these as "separators" in algebraic expressions. So (3)(4)=12, just like in old times. (Check it
out to make sure.) The next beasts are the square brackets, [ ]. These signify an operation is
being done on the stuff inside the brackets. So f[x] means that the function f operates on the
variable x. The curly brackets, { }, you may remember if you've done any set theory in math.
They essentially do the same thing here, they act to group information together.
3. There are three "equals" commands. What is the difference between "=", "==" and ":="? Enter
some expressions and see what happens. This may get tricky. So get creative! Spend some time
figuring out a way to confirm three distinct meanings. When you think you've got it, check out
the entries for the Equals commands in the Master Index which you can search via the Help
Browser.
4. Each operation needs a specific number of arguments. An example of an operation needing
only one argument is the "Expand" operation. Its form is simply "Expand[x]". An example of an
operation needing two is the "D" operation for differentiation. You must specify the function and
the variable you want to differentiate with respect to. So these are in the form D[f,x]. An
operation needing three arguments is "DSolve". This command solves a differential equation (or
system of them or a partial differential equation, if you are comfortable with curly brackets). The
arguments for "DSolve" would be the differential equation itself, then the function to solve for,
then the independent variable of the function. So the form is "DSolve[Eqn, f , x] for a differential
equation of just f[x]. (Things get a little more exciting when we add more variables to make it a
partial differential equation or put in boundary conditions.)
Department of Physics, Bryn Mawr College
9/3/09
If you want to play with more examples before you get started on your own, a good place to go is
under the "Help" heading and scroll down to the "Help Browser". The help browser is wonderful
as its pages are all Mathematica notebooks. You can change the input and reevaluate the cells.
The help browser also has a search tool and connects to the Mathematica website. However,
don't rely on it too much. It provides many examples but little non-technical explanation.
2. Differentiation and Integration
Now that you have the tools to work Mathematica, let's use it to do some basic operations. In the
previous section you were told what the differentiation operator was. So take the derivatives of
some functions, and see what you get. Take derivatives of functions of several variables.
Hmm...helps with multivariable homework. There is also an infix operation that is a little easier
to deal with. First define a function f[x]. For function definitions you need to input "f[x_]:="
followed by what you want f to be. Make it a polynomial in x. This makes things easier. Now
enter f[x]. It should spit out the expression. (Try evaluating f at a few values. Here is where
Mathematica is a great timesaver, as it can evaluate a function at arbitrary values, without having
to reinput the function every time, as you would with a calculator.) Now enter "f'[x]". The " ' "
tells it to take the derivative of f with respect to x. Now enter f''[x]. And you see where we are
going. Typing x =. will clear the value of x.
Another powerful aspect of Mathematica is its visualization capabilities. Graph f[x] vs. x using
the "Plot" command. The Plot command requires two arguments: The function, and the
independent variable. The range of the independent variable must be specified, too. Decide how
far you want x to extend. The form ends up looking like Plot[f[x],{x, xmin ,xmax}]. Run it and
look at the picture. How would you plot both f[x] and its derivative on the same plot? Can you
get it to work? (How can curly brackets help?) When you’ve gotten it to work, take a look at a
value of f’[x]. Does it correspond to the slope of f[x]? Oooo. Try plotting a more exciting
function. You can also change the style of the plot. Check out section 1.9.3 of The Mathematica
Book via the Help Browser window for these options and some examples. (Don’t spend much
time on this though; it’s not important yet.)
An Aside- How would you plot a function of two variables? The first step is defining the
function. This is very similar to defining a function of one variable. Use your intuition and see if
it works. Try a boring polynomial first. You can try substituting values for x and y. Can you take
the partial derivative with respect to y? Now that the function is defined, we can plot it. How
many specifications (arguments) would you need for a 3-D plot? How many did you need for a
2-D plot? See if you can get something to work. What kind of error message did you get? Why?
The reason why this didn’t work is that Mathematica likes to be told when its going to plot in 3D. Now substitute the command “Plot” with the command “Plot3D”. Your picture, while 3-D,
may look a little boring. You can change the shading and colors to make it less boring, but we
won’t get into that here. A foolproof way of making it exciting is to add a sine or a cosine. If this
doesn’t impress you, try a product of sines and/or cosines.
The next step is integration. As you hopefully know, we can take derivatives of many continuous
functions with our eyes closed, as long as we remember the chain rule. However, integrals are
little harder to obtain and usually require a bunch of guesswork. Mathematica can help you a lot,
at least in getting the answer. Another nice feature is that it will evaluate both definite and
indefinite integrals. Let’s try indefinite integrals first. The command is “Integrate” and requires
two arguments, the function and the variable of integration. Integrate something boring as a
check. Now integrate something exciting, that you could only attempt by parts, like x2Cos[x].
What about something you couldn’t even attempt, like Cos[x2]. Whoa. It can do it! Look up
something in the CRC and evaluate it in Mathematica. Now try a favorite: Sin[x]/x. Hmm…it
can’t do it. Never fear, there are ways to get around this. We’ll get there very soon. First,
however, practice a few definite integrals. Instead of just specifying the independent variable,
Department of Physics, Bryn Mawr College
9/3/09
what else will you have to specify? Try it!
Now let’s attempt to find a value for the elusive Sin[x]/x. First, plot the function. Why doesn’t it
like it? It doesn’t seem too bad. The truth is, it’s not, except at one particular point. The graph
doesn’t show it but it is apparent just looking at the equation. It is hopeless for us to get an
indefinite integral out of this. But let’s try a definite integral. Definite integrals are easier to
obtain as they can be obtained just by counting the pixels under a curve. Try evaluating it in the
domain [-1,1]. It still hates it, as the problem is still in there. However, we can push the limits of
how close we go to zero and break the integral up into pieces. Devise a method for evaluating
this integral. How accurate can you get it? How can you tell if it’s accurate?
An interesting thing is that in this case, Mathematica likes the improper integral a whole lot
more. Go to File, then Palettes and open the “Basic Input” palette. This will make your life
somewhat easier. Click on the icon that looks like a definite integral. Evaluate the integral of
Sin[x]/x from (-∞, ∞). For infinity, you can write “Infinity” or just use the handy palette button.
What is your answer? Does it surprise you that it can do the integral? As an aside, now take the
integral of Sin[3x]/x over the same limits. Now replace 3 with a larger integer. Keep going. Plot
some of these functions. What happens to the shape and the area under the curve as the integer
gets larger? As the integer approaches infinity, you might recognize this as the delta function.
What might a delta function describe in the real world?
When you were checking the accuracy before you probably devised a “recursive” method of
doing this (what does this mean?). The computer does the same thing when it performs the
operation “NIntegrate”. This gives an approximation of the area under the curve. You can
specify how precise you want it, but we won’t do that now. Integrate Sin[x]/x over [-5,5]. It still
doesn’t like it. What about over [-10,5], or even [0,5]? -- interesting. Any ideas why the
computer would do this?
3. Solving Differential Equations
Algebraic systems of equations are pesky, and need solving, but differential equations are
interesting and really where physics happens. A wise professor once said, “All of physics is
second-order differential equations.” While this is an incredible generalization, there is a grain of
truth to it. Let’s take a closer look at a very familiar second order differential equation that you
spent a lot of time on in Introductory Physics, F = ma: the sum of the forces on an object is equal
to its mass times it’s acceleration. Let’s look at the simple harmonic oscillator (i.e. mass on a
spring) as an example. In this case the total force on the mass is the restoring force of the spring
(F = -kx ). Setting this force equal to ma and rearranging, we get
ma + kx = 0
for the equation of motion. Rewriting acceleration as the second time derivative of position, we
get the equation of motion in the form of a second order differential equation.
m(d2x/dt2) + kx = 0.
Dividing by m gives
d2x/dt2 + (k/m)x = 0.
It is not difficult to solve this by ourselves, but let’s see what Mathematica can do for us. Using
the DSolve command, see if you can solve the differential equation, specifying the function and
its independent variable. You should get a solution with two arbitrary constants, C(1) and C(2).
Does your solution make sense? You can determine these constants by adding boundary
Department of Physics, Bryn Mawr College
9/3/09
conditions in the first argument (curly brackets and commas). Let the initial position be equal to
1 and the initial velocity be zero. What does this mean physically is happening at t=0? Does the
solution make sense? Why? This is a simple example, but the point is that more complicated
differential equations whose solutions we do not know can be solved in the same manner.
Okay, let’s move on to the visualization of our solutions. To visualize differential equations, we
work in what is called “phase space”. For a system such as g[t]=f’[t] and f[t]=g[t]+4, the most
useful phase space would be to plot f versus g. In the oscillator problem, we are working with
coupled equations as well, we just have to define y’[x]=v[x], and then we plot v vs y (velocity
versus position). How can we plot one function against another? Well, they both depend on the
same independent variable, so we have a set of parametric equations. To plot them, we use the
“ParametricPlot” command. One argument will be the pair of functions, and the other argument
will be the range of x. What should the range be? You should get an ellipse (in this specific case,
the unit circle). What is the equation for an ellipse? What should the length of the axes
represent? (Hint: What are the equations for kinetic and potential energy for this system?)
So…what does the curve represent?
As an extra challenge, plot the system in a 3-D phase space, with axes v, y, and x. The command
is “ParametricPlot3D”. See if you can work this out. What would the projection of this onto the
xy plane look like? The vy plane? The vx plane? Are these trick questions? As an even further
challenge, try some funky stuff. Plot two functions with two parameters. How can you make this
3-D? Consult the Help Browser if need be.
For a more complex example of solving differential equations, let’s try the “equidimensional”
differential equation:
x2(d2y/dx2) + 2x(dy/dx) + 4y = 1.
Why is it called equidimensional? This is usually solved by a change of variables, but one need
not be so fancy here. Simply use DSolve. As a check, take the first and second derivative of the
solution, and plug it into the original formula. You may have to copy and paste a bunch to
perform this check, but Mathematica makes it easy in comparison to writing it out.
PART II: Other Applications
Let’s go over some other exciting things Mathematica can do for us.
1. Systems of Algebraic Equations
All right, let’s change gears and do some physics. In Multivariable Calculus, you may have heard
of Lagrange multipliers. Lets apply this to a physical situation. (Problem taken from Boas).
Given the shape below, with a given perimeter (4s+2l) we want to maximize the area.
l
s
t
Department of Physics, Bryn Mawr College
9/3/09
Find a formula for the area. Now define a new function. This is the formula for the area, plus a
constant (call it L, for Lagrange multiplier) times the “constraint”, the formula for the perimeter.
To maximize the area, we must take all three partial derivatives of our new function. After you
have done this, make sure these derivatives are defined as something abbreviated. A good way to
do this is to input Y1=…then Y2=…. Then you should enter in the constraint formula, and call it
something like Y4. Now the fun stuff begins. We won’t get into the theory, but to maximize the
area all three partials must be set equal to zero, and the constraint must be set equal to a constant
(“C” is always a good choice). So now we have four equations and four unknowns! We could
solve this ourselves, but wow, that could take a while. An easier thing to do is to use the “Solve”
command. This requires two arguments: the equations and the variables to solve for. Use curly
brackets and make sure you are using the correct equal sign. And then…voila! If your input was
correct, Mathematica will rattle off ten solutions. Which ones are physically relevant? Why? In
five minutes you can solve a system of equations that could easily take an hour!
2. Approximations by expansion
When dealing with small angles, you may recall we make the approximation sin(ϑ) ~ ϑ. Why is
this valid? Because in the Taylor expansion, when is small, all other terms become negligible.
The command for series expansion is “Series”. You specify the function you want expanded, and
the order of the expansion. Try a few examples with sine. Check Euler’s Formula: eiϑ = cos ϑ +
isin ϑ. Expand eiϑ, cosϑ and isinϑ. Add the expansions of cosϑ and isinϑ. How does the sum
compare to the expansion of eiϑ? Try to expand the generic “f[x]”. What does the formula look
like?
As a visual check plot Sin[ϑ] and the first few expansions of Sin[ϑ] on the same plot. Make sure
your domain is small. Do the expansions approximate the function to greater and greater
accuracy? What happens as you move to the right on the x-axis? Why?
3. Matrix manipulation
You can also manipulate matrices in Mathematica. If you are curious, look at section 1.8.3 in
The Mathematica Book. Evaluate some eigenvalues and eigenvectors. Take the determinant.
4. Schrodinger’s equation in spherical coordinates
Electron orbitals are a direct result of the Schrodinger equation in spherical coordinates. The
orbitals represent where an electron is likely to be found. The Schrodinger equation for a oneelectron atom can be separated Ψ(r, θ, φ) = R(r)Y(θ,φ). (Note the different definitions of φ and θ
from what you may be used to.) The eigenfunctions for the angular equation are the spherical
harmonics (closely associated with the Legendre polynomials). Search for “spherical harmonic”
in the master index. You will see they are a built-in function. Enter the following:
Table[SphericalHarmonicY[L, m, θ, φ], {L, 0, 2}, {m, -L, L}]
This tells it to produce a list of the spherical harmonics over the given values of the quantum
numbers L (from the total angular momentum) and m (from the z-component of the angular
momentum). The angular electron density for a pair (L,m) is thus given by multiplying the
associated spherical harmonic by its complex conjugate. Define the function:
f[L_, m_, θ_] :=
SphericalHarmonicY[L, m, θ, φ]*Conjugate[SphericalHarmonicY[L, m, θ, φ]]
Department of Physics, Bryn Mawr College
9/3/09
Evaluate the function at specific L and m values. First try L = 3 and m = 1. Keep θ arbitrary.
Now you have to tell it that theta and phi are real. Enter the following:
ComplexExpand[%]
And then:
Simplify[%]
Now you are ready to visualize an f-orbital. Enter the following:
<< Graphics`
This loads a special graphics package. Now you will plot the f-orbital! This is done with the
following:
SphericalPlot3D[function, {θ, 0, π}, {φ, -π, π}]
Try other orbitals. Use different combinations of L and m to see what you get. Can you name the
orbitals? For a more detailed discussion of orbitals, look at Rohlf or a physical chemistry
textbook.
5. Numerical Solutions of Differential Equations: The Lorenz Strange Attractor
Chaos is something you may or may not be familiar with. It is usually brought about by a system
of coupled, nonlinear differential equations. The characterization is called “sensitive dependence
on initial conditions”. This means that slightly different initial conditions can create drastically
different trajectories in phase space. This means that predictability is limited, as we cannot ever
know initial conditions precisely. You can explore some of this behavior here.
Edward Lorenz, first “discovered” chaos through a system of equations describing fluid motion.
He was a meteorologist, and was attempting to figure out the weather. In a vast simplification of
actual weather behavior, he came up with these three equations*:
x’ = 10(y-x)
y’ = -xz + 28x – y
z’ = xy - (8/3)z
Note the “xz” and “xy” in the equations. These are the nonlinear aspects.
Mathematica can give closed form solutions to many differential equations, but where it really
can help is with finding numerical solutions. Nonlinear systems are impossible to solve with
traditional methods, so we must look to numerical methods. As a simplification, what
Mathematica does to solve these equations is to start with the initial conditions, and use the
differential equation to make a slope vector there. Then it moves ahead one “time step”, and
draws a line through the initial point and the point at the first time step. It then calculates the
slope at the first time step, then moves another times step, repeating the process. If the time steps
are very small, then the error can become very small. (For a more precise explanation look up
Euler’s method in a differential equations textbook.)
So, now you can plot the solution, given some initial conditions. Enter the following:
Lorenz =
NDSolve[{x'[t] == 10 (y[t] - x[t]), y'[t] == -x[t]z[t] + 28 x[t] - y[t],
z'[t] == x[t]y[t] - 8 z[t]/3, x[0] == z[0] == 7, y[0] == 5},
{x, y, z}, {t, 0, 50}, MaxSteps -> 5000]
What does each argument do? The usual maximum number of steps is 1000. Why change this?
How many steps per unit of time are there? Notice the output. It can’t give you a closed form
solution. It’s just waiting to be plotted. So plot it! Enter the following:
Department of Physics, Bryn Mawr College
9/3/09
ParametricPlot3D[Evaluate[{x[t], y[t], z[t]} /. Lorenz], {t, 0, 50}, PlotPoints -> 5000]
This is the Lorenz strange attractor. Generally an attractor is what any trajectory in phase space
is. For chaotic systems they are dubbed “strange”. One characteristic feature of a strange
attractor is that this curve, unlike the ellipse for our harmonic oscillator, will never repeat itself,
yet it still remains in a finite volume. Now try some different initial conditions. Important: each
time before you try a new set of boundary conditions you must quit the kernel. What happens
with different initial conditions? Try different conditions that are numerically close. What
happens?
6. Further Challenges
Come up with a plan to attack a physical problem of your choice. Suggestions include:
-Creating an accurate animation of a physical system, i.e. a spring, a planetary orbit, etc.
-Modeling radioactive decay
-Fourier Series
-Solving the Klein-Gordon equation (Relativistic Schrodinger)
-The Heat Equation (Bessel Functions, Legendre Polynomials)
Prepared by Kerstin Nordstrom, 5/03
Modified for Physics 308
by E. McCormack, 9/03