Chem 3111 Eric R. Bittner
Univ. of Houston
Thanks to Hannes Jónsson and Gisli Johannesson , U. Washington
Mathematica (registered trademark of Wolfram Research Inc.) is a very powerful tool for solving mathematical problems and for using graphics to gain more insight into mathematical results. Mathematica can, for example, provide exact or approximate solutions to equations involving polynomial, exponential, trigonometric, and logarithmic functions; solve differential equations and evaluate integrals either numerically or sometimes analytically. It can symbolically factor polynomials, graph functions of one, two or three variables, and perform operations on matrices. The evaluation of special functions such as Bessel functions becomes almost as easy as the evaluation of sines and cosines on an ordinary calculator. Mathematica can, furthermore, be used as a programming language, a level above C, Pascal, Fortran, and other such programming languages.
In this and other exercises based on Mathematica you load in a notebook, the working document in Mathematica. Read the text carefully, carry out all the calculations that are set up (i.e. make Mathematica execute the commands) one by one. You should think carefuly about what the commands mean and how they are constructed so as to learn to use Mathematica from these examples. Several questions are raised in the notebooks. Those are labeled with a "Q:" at the left margin. You should type in your answer after each question. Identify your answer in some way, for example with an "A:" in the left margin, or by using a different color.
Remember to save your work frequently. This can be done by pressing the "CTRL" and "s" keys simultaneously. Make a habit of saving your notebook every couple of minutes at least. Mathematica can crash and you will then loose the work you have done since the last time you saved the notbook.
Below are section headings. To open each sections, double click on the blue bar farthest to the right. You can close it again by double clicking on the blue bar.
The graphical interface to Mathematica is called a notebook. All notebook names get the suffix .nb automatically when you save them. The building blocks of notebooks are `cells'. The lines that are grouped together in a cell are identified by a blue square bracket on the right hand side of the cell. This paragraph is in one cell.
There are many kinds of cell styles. You need to become familiar with two of them, `text' and `input' style. This cell is a text cell and is used for comments (introduction, questions and answers, for example). You should create new text cells for your answers to questions raised in the notebooks later on. You can create a new cell by placing the cursor at the end of a cell and then hitting the `enter' key. The new cell is by default an `input' cell, not a text cell, and the contents of such cells get sent to the Mathematica's processing engine (the `kernel'). An input cell can be changed to a text cell, as explained below.
When you have mathematical expressions you wish to evaluate, you type them into an input cell and then press enter on the keypad (the enter button on the keypad on the far right of the keyboard is the only key you should use on the number keypad when working with Mathematica, type in numbers from the upper row on the main keyboard). You can also execute a Mathematica command by pressing Shift and Return simultaneously on the main keyboard, after placing the cursor in the relevant input cell. This causes Mathematica to evaluate the expressions and print the results in an ouput cell.
Q: Open a new cell by placing the cursor in between this cell and the following one (the cursor should become a horizontal line) and hit enter. Type in 2+2 and then hit enter on the keypad. You should get the result of the calculation from Mathematica (the first command often takes a while to execute because Mathematica has to initialize various things). This notebook is written with the `classroom stylesheet', so the background of input and output cells gets highlighted with different colors.
To change the style of a cell, you must first highlight the cell. by clicking on the blue square bracket on the right hand side of the cell (that is, place the cursor over the square bracket and press the left mouse button). Next you click on "Format" on the tool bar. A pop-up window appears. Place the cursor over "Style" in the pop-up menu, and a second pop-up window shows the available styles. Cilck on the desired style.
Q: Open another cell and change the style to "text" style. Again type in 2+2 and hit enter. How does Mathematica respond now?
You can change the color of the text by selecting the text or the cell and choosing "Text Color" from the "Format" menu.
It is a good idea to divide your notebook into many cells. This way you can keep track of intermediate results and limit the source of possible errors, if any problems arise.
You can divide a cell in two by placing the cursor where you want the second cell to begin and then select "Cell" from the menu bar, and then divide cell. This can be done by keystrokes only, as written to the right in the pop-up window ( Shift-Ctrl-D). If you wish to combine two or more adjacent cells into one, you must select both cells (hold down the shift key when selecting the second one) and then select "Merge Cells" from the "Cell" menu. You can also select more than one cell by clicking the square bracket on the right hand side of the top or bottom cells, and then draggin the cursor over the rest of the cells while holding down the left mouse butto
You can delete a cell by selecting it and then selecting "Clear" or "Delete" from the "Edit" menu (or pressing Ctrl-X on the keyboard)
Q: Create some new cells and practice dividing, merging and deleting cells.
Mathematica has a very useful help directory built into the program. Click on "Help " on the tool bar and select "Help..." on the pop-up menu. Then the Help Browser window appears. As shown in the pop-up menu at the right margin, you can alternatively press Shift and F1 simultaneously on the keyboard to get the help browser. You can, for example, type the word you need information about in the narrow horizontal window. As you type, the help browser will try to complete the rest of the word. When you have finished typing (or the browser has found the word for you) select "Go To". Then you get some information about the word and links (highlighted in blue, which you can access by clicking on them) to additional information. The help browser has six categories: Built-in Functions, Add-ons, The Mathematica Book, Getting Started/Demos, Other Information, and the Master Index. You should experiment with each of these, to get an idea of how to get the desired information as fast as possible. An essential part of learning to use Mathematica is to be able to use the help browser efficiently.
Execute the following cell
![]()
by clicking anywhere in the cell and then pressing the enter key (remember to use the keypad). Mathematica will respond with the results of the calculation in an output cell.
A space between numbers and/or variables represents multiplication, as does the * symbol (the star). For example, compare the two expressions (execute both cells
![]()
![]()
It is recommended that you always write a * for multiplication, it is clearer and thus reduces the probability of undetected errors in your Mathematica commands.
The symbol, /, represents division. For example:
![]()
The output is a rational number (evaluate the cell to verify this). In Mathematica 3.0 and later versions, an alternative (fancy) way of writing mathemtacal expressions was introduced. By using the BasicInput palette which you find under "Palettes" in the "File" menu, you can write the expression above in the following manner

Verify that this gives the same answer as above.
As you can see from this, Mathematica tries to keep the answer analytical, rather than a number with limited significant figures as we would get from a typical computer program.
The caret, ^, indicates raising to a power. For example:
![]()
gives 2 raised to the power of 64. By using the palettes (a filled square with a smaller open square in the upper right corner) this can also be written as:
![]()
Neither of these two numbers need to be integers. Try for example
![]()
Variables in Mathematica do not need to be declared as integers, real numbers, arrays, etc. (as in Fortran or C). When a value is assigned to a variable, it automatically assumes the attribute of the assigned value. For example, the statements

automatically declare the variable a as an integer, b as a real number, and c as a 2x2 matrix with integer entries. You may choose any name you wish for a variable, but try to make the names as descriptive as possible. Most likely, the names of the above variables are too general. This is not very important in short programs. Predefined variables in Mathematica always have names that start with a capital letter. For example, the number π is given by
![]()
The exponential function is Exp[argument], for example
![]()
Note that Mathematica does not give a numerical answer, it tries to keep the result exact as far as possible (there is a way to force Mathematica to give a numerical answer, see below). It is good practice to choose variables that start with a lower case letter so as to prevent accidental conflict with variables that are predefined in Mathematica.
There are three types of brackets used in Mathematica. They have very different meaning and it is extremely important to learn which type of bracket to use in various circumstances. The round brackets are used to group parts of an arithmetical expression together. For example, when a fraction is raised to a power
![]()
When a list of something is created, such as a list of numbers in an array or a matrix, the items in the list are separated by a comma and the list starts and ends with a curly bracket
![]()
A variable called "mylist" has been created in the cell above. It contains three real numbers. The entries in a list can also be lists. For example the matrix "c" defined above could equally well have been defined by the expression
![]()
The square brackets envelope the argument(s) of functions in Mathematica. See, for example, the exponential function discussed above. A function f(x) = x may be defined by the command
![]()
We will later deal with functions in detail.
One nice aspect of lists is that a they can be arguments for functions. For example, the exponential of all the numbers in the list mylist can be calculated by simply typing
![]()
Square brackets are also used when a selected element of a list is needed. For example, the second element in the list mylist is
![]()
If a semicolon is placed at the end of a line in an input cell, Mathematica will not print the output from the command. For example, compare
![]()
![]()
The square root of -1 is represented as I (or rather, I is defined in such a way that
). For example, try
![]()
You can divide one complex number into another using Mathematica, such as
![]()
Q: What is the value of
? (Calculate this using Mathematica. You don't need to use the palettes). Richard Feynman, one of the greatest physicists of the 20th century, called this result "the most remarkable formula in math" (See the book: 'Surely You Must be Joking Mr. Feynman').
There are hundreds of intrinsic functions, commands and object types at your disposal in Mathematica. Their names begin with a capital letter (if the name is constructed by combining two words the second part of the name also begins with a capital letter), and their arguments are enclosed within square brackets. Since there are so many of these, only a small fraction can be shown here. You can find them all in the Help Browser.
You have already seen the exponential function. Some other examples of
intrinsic functions are
![]()
![]()
![]()
The first function is the Cos[] function, which evaluates the cosine of an angle (given in radians). The second function is the square root function. Then we have an example of a function within another function. The Sqrt[] gives the square root of the argument and IntegerPart[] returns the integer part of the square root.
Here we look at four commands, Clear[], Expand[], Factor[], and N[].
The command, Clear[var1,var2,...], clears the values assigned (if any) to the variables var1, var2,.... It is very important to clear variables at the beginning of each program you write in Mathematica. Many mistakes result from variables having different values than assumed (sometimes the variable should not have a value assigned, but Mathematica remembers an assignment that was made earlier. Computers have in some sense too good a memory!). It is good practice to include all the variables you use in a Clear command at the beginning, adding to the list as you go on writing the Mathematica program. This includes the names of functions (not the intrinsic ones, though, only the ones you define). For example, compare
![a = 1 ; b = 5 ; Factor[9 * a^2 + 15 * a * b - 6 * b^2]](HTMLFiles/index_27.gif)
and
![Clear[a, b] Factor[9 * a^2 + 15 * a * b - 6 * b^2]](HTMLFiles/index_28.gif)
The command Expand[expr] expands the expression that appears in the argument and Factor[expr] does the opposite, it factors the argument. For example
![]()
![]()
Q: Try combining Factor and Expand, for example in Factor[Expand[(1+x+x^2)^3]]. What is the net result?
The N[] command gives a numerical approximation to the expression in the argument to a given number of significant figures. N[expr, n] gives the expression expr to n significant digits. For example
![]()
gives the constant π to 10-digits. The default for N[expr] is to give the 6-digit approximation to expr. You can attach //N to an expression to force matematica to evaluate it to 6-digits.
![]()
Q: What is the value of Eulers constant, e, to 20 digits? (Note, the symbol for the Euler constant is E, since all intrinsic variable have a name that starts with a capital letter)
A list of data points (x,y) can be graphed and fitted easily using Mathematica. First the data is stored in a matrix (it is a good idea to clear the variable first, just in case)
![Clear[data] data = { { 2, 1 }, { 3, 7 }, { 5, 8 }, { 6, 11 } }](HTMLFiles/index_40.gif)
Now the data can easily be manipulated by referring to the variable called data. The ListPlot function can be used to graph the points
![]()
Mathematica chooses the range of the horizontal and vertical axis automatically if it is not specified. The first data point then lands right on the vertical axis and may not be noticed. It is often better to specify the range explicitly by using the
PlotRange -> {{xmin,xmax},{ymin,ymax}}
option in the plotting function. Also, for future reference it is convenient to give this graph a name, say 'dataplot'. The plotting command then becomes
![dataplot = ListPlot[data, PlotRange -> {{0, 8}, {0, 12}}] <br />](HTMLFiles/index_42.gif)
The points appear as dots on the screen. It is possible to connect the points by straight line segments by adding the PlotJoined -> True option. There are many options that can be added to the plotting command. The various options need to be separated by a comma in the argument list of the plotting function.
Q: Modify the plot to include straight line segments between the data points.
In many cases one would like to obtain a fit of a smooth curve to data points. Linear least squares fits are obtained in Mathematica by using the Fit function. For example, the data can be fitted with a straight line with the following command
![]()
The expression {1,x} here specifies that the form of the function that is to be fitted to the data is a constant plus a linear term in x (i.e. straight line). The results are given the name 'f' for future reference. For example, the straight line can be plotted with
![]()
The composite plot of the original data points and the fit can be superimposed by
![]()
If the data is given as a list of x values and a separate list of y values, the matrix of (x,y) pairs can be created with the Table command. For example, if the list of x values is
![]()
and the list of y values is
![]()
then the matrix of (x,y) pairs can be generated by (the argument {i,4} says that the dummy variable i should run from 1 up to 4)
![]()
Q: Below is data on the equilibrium constant for the formation of ammonium from hydrogen and nitrogen,
+ 3
-> 2![]()
![]()
as a function of temperature. The task is to extract ΔH and ΔS from the data assuming these quantities are independent of temperature. Recall that the Gibbs free energy is related to the equilibrium constant through
ΔG = ΔH - TΔS = -RT ln(Keq)
Assuming ΔH and ΔS are independent of T, a plot of ln(Keq) vs. 1/T should give a straight line with a slope of - ΔH/RT and an intercept of ΔS/R. An estimate of ΔH and ΔS can therefore be obtained by fitting a straight line to the data points.
Measurements of the equilibrium constant were made at the following temperature values
T = 300, 400, 450, 500, 550, 600
and the observed value of the equilibrium constant (in the right order) was
Keq = 0.00434, 0.000163, 0.0000449, 0.0000145, 0.0000054, 0.0000023
The goal is now to fit a straight line through the points ln(Keq) vs. 1/T. Create a variable that is a list of all the temperature values (use copy and paste from the edit menu to enter the data into an input cell). Then calculate the inverse temperature (you can take the inverse of the list). Similarly, create a variable with all the values of the equilibrium constant and calculate the natural logarithm of the values. Then use the Table command to create the matrix of (1/T, ln(Keq)) pairs. Then make a plot of the data and the least squares line on the same graph . What is the slope of the line (the slope is related to the enthalpy change in the reaction)? Does this correspond to a positive or negative enthalpy change as ammonia is formed?
The equality sign, =, is an assignment operator. It is used to assign a value to a variable. The symbol := is also an assignment operator, but the expression is not evaluated until the results are requested. It is called delayed assignment. Double equality sign, = =, is a logical operator and the result is True or False. To see the difference between assignment (=) and delayed assignment (:=), go through the following example
![]()
First x is assigned a value
![]()
Then the operation of squaring x is defined in two different ways
![]()
![]()
Q: What is the value of z and p at this point (you can check by simply typing z and then enter, and similarly for p)?
Now, change the value of x to, for example, 5
![]()
Q: What is the value of z and p now?
Q: Describe in words the difference between how the = and := operators function in Mathematica.
A function, such as f(x,y)=
Sin(y) can be defined in the following way:
![Clear[f, x, y] f[x_, y_] = x^2 * Sin[y]](HTMLFiles/index_59.gif)
Note the underscores that appear after the variables in the function definition. Underscores are only used on the left hand side and they are only used in the definition of a function, not when it is used later on. It is very important to remember this. You can evaluate the function at x=1, y=π /2 by simply typing
![]()
Q: When the acid-base equilibrium of a buffer solution is treated exactly (see the text book by Oxtoby, section 10.8), the hydronium ion concentration ends up being expressed as a root of a third order polynomial
f(x) = x^3 + (cb+ka)*x^2 - (kw+ca*ka)*x - ka*kw
where ca is the initial concentration of the acid and cb is the initial concentration of the base. Define a function f[x] which gives the hydronium concentration according to the expression above. First evaluate the function for a couple of values of x (to make sure the definition statement worked) and then plot it for a solution of HCN with the values: ca=1.00*
, cb=0.0, ka=6.17*
(remember to also assign the autodissociation constant of water, kw, its value). Plot the function and read of roughly where the three roots are (it is important to specify a reasonable range for x (while leaving the range on the vertical axis automatic) in this plot. Realize that x has a magnitude much less than one).
FindRoot: to find the root(s) of a function.
Mathematica has a numerical procedure for finding roots of functions using a modified Newton-Raphson method. It is necessary to give an initial guess to get the procedure started. The following example illustrates how FindRoot is used.
![]()
![]()
Here the value 1.2 is an initial guess for the root. It is used as a starting value in an iterative procedure.
Q: Find the positive root of the third order polynomial for the hydronium ion concentration in a HCN solution discussed in the previous section. Use the approximate estimate of the root from your graph as an initial guess for FindRoot. Mathematica routines work best when the numbers it works with are on the order of unity. Here the numbers are very small, so it is necessary to increase the number of significant figures that Mathematica works with and reduce the tolerance used to determine when convergence is reached. This can be accomplished by adding
AccuracyGoal->30, WorkingPrecision->35
to the list of arguments in the FindRoot statement (within the square brackets).
D: to calculate the derivative of a function.
Mathematica can evaluate derivatives analytically. For example, the derivative of the function g[x] defined above is
![]()
Q: Derive the derivative of the third degree polynomial for the hydronium ion concentration in a buffer, defined in the section above. Clear all constants first to obtain an analytical expression.
Indefinite integration is performed symbolically when possible. For example, to integrate
with respect to the variable x
![Clear[x] Integrate[x^2, x]](HTMLFiles/index_67.gif)
A definite integral can also be evaluated. When the integration range is from b to c, the command should be
![Clear[x, b, c] Integrate[x^2, {x, b, c}]](HTMLFiles/index_68.gif)
Mathematica can also carry out the integration numerically. This is particularly important when analytical results of the integral cannot be obtained. The name of commands that carry out numerical calculations often start with N, for example NIntegrate[].
![]()
Q: Practice doing integration and differentiation by solving the following definite integrals and sums using Mathematica; Do the definite integrals first analytically then numerically and compare results. Under what conditions are the definite integrals defined.
1. ![]()
2. ![]()
3. ![]()
4.![]()
5.![]()
6.) ![]()
7.) ![]()
8.)
Also evaluate the sum numerically by making a table of length N and summing the elements of the table. How big must N be to get the series to converge to the 10th decimal place.
Converted by Mathematica (August 29, 2002)