Mathematica Basics for Chemistry

Andy Anderson — Academic Technology Services

Part I: Calculation Basics

Part II: Symbols

Part III: Plotting Functions

Part IV: Defining Your Own Functions

Part V: Calculus

Calculation Basics

Basic Arithmetic

At its most basic, Mathematica provides the features of a scientific calculator.
Mathematical expressions are typed into the Mathematica “Front End”, and you can see them in full and edit them before you evaluate them:

1+2

A math expression such as the above is evaluated by pressing one of:
    • Windows Keyboard: <NumericKeypadEnter> or <Shift> <KeyboardEnter>
    • Mac Keyboard:  <Enter> or <Shift> <Return>
Note that, if you have moved the flashing cursor away from an expression, you must first click on it to select it for evaluation.
You can therefore re-evaluate any expression at any time; there is no requirement to evaluate your expressions in any kind of order.

Multiple expressions can be written together as a group, using the ordinary Windows <Enter> or Mac <Return> to put them on separate lines, and then evaluated once to display their results all at once:

7 - 3
4.3*5
-12/2

Input and Output Cells

The group of input expressions above, as well as the output expressions that appeared on evaluation, are called cells, indicated on the right side by blue brackets.
You can use the arrow keys to move around within a cell as well as between cells.
	• A flashing vertical bar indicates the insertion point within a cell.
	• A horizontal line indicates “not in a cell”, so a new one will appear when you type.
Cells can be selected as a whole by clicking on their brackets, and then deleted, cut, copied, and pasted in their entirety.

So that you can understand at a later time what you were thinking when you write complex expressions, it’s a good idea to comment them, by including a description between (* and *):

3*4        (* This is an example of multiplication. *)

Comments are ignored during evaluation of a cell. They’ll be used below to help explain certain expressions — you don’t have to type them in yourself!

Notebook Files

Unlike a scientific calculator, you can easily save the expressions you write for later review and re-evaluation, in a Mathematica notebook, a file with a file extension .nb:
	◇ Menu: File -> Save .

Other Common Operations

In addition to the addition, subtraction, multiplication and division you saw above, you can use the circumflex character ^ to represent the Power operation (exponentiation):

2^3

You can represent numbers with scientific notation, using the character sequence *^ to introduce multiplication by a power-of-ten:

7*^2  (* Same as 7*10^2 *)

As in written mathematics, scientific calculators, and most programming languages, when you mix multiple operations together, they aren’t handled purely on a left-to-right basis. Rather, some of them have higher precedence than others, and so occur first.
The precedences of these operators are, from highest to lowest:
    • Power
    • Negation
    • Multiplication/Division
    • Addition/Subtraction
Also as usual, parenthesis () can be used to alter the order of evaluation:

2+3*4
(2+3)*4

When the same type of operation is used multiple times, evaluations generally occur from left to right, except for Power, which proceeds from right to left:

2^3^2 
(2^3)^2

Traditional Mathematical Formats

Mathematica simulates a number of traditional mathematical formats that you are used to writing on paper, and these can sometimes be helpful ways to display expressions.
For example, formulae such as nπr which have implied multiplication can be written with just a space between quantities to represent multiplication:

n π r
6 5

However, it can often be hard to distinguish if a space is present or not, and in the case of numbers Mathematica displays a grayed-out Times character to help visualize the presence of multiplication. Nevertheless, an explicit * is generally recommended.

Another common format when writing on paper is to represent a power using a superscripted exponent, e.g. (2^3).
You can write such expressions in Mathematica as follows:
 	1) Menu Palettes and select Basic Math Assistant (if it’s not already displayed); 
	2) Look through the palette and click on an appropriate form, such as (□^□) .
		These are usually located in either its Calculator section or its Basic Commands section.
	3) What you just typed, or have selected, will be inserted into one of the form fields.
		Press the keys <Tab>  and  <Shift>-<Tab> to move between different parts of the form.

(\[Placeholder]^\[Placeholder])
(2^3)

You can also use the arrow keys to move through the form, but they don’t automatically select the form fields.

As another example, fractions are often written on paper with a horizontal line, e.g. (3/2), and this option also appears in the palette Basic Math Assistant:

(\[Placeholder]/\[Placeholder])
(3/2)

The palette Basic Math Assistant also provides a number of special mathematical values:

∞
π
E

These characters and many more can be found in the section Typesetting, and in the separate palette Special Characters.

Many of the forms and symbols have keyboard-entry equivalents, which you can learn by hovering over them in the palette rather than clicking on them. They will use either the <Control> key (which is always held down, like the <Shift> key) or the <Escape> key. For example:
	• Ctrl ^ introduces an exponent
	• Ctrl / introduces a fraction
	• Esc letter(s) Esc introduces a special character such as π or e (the exponential constant):
Try it! For example, type:
             2 Ctrl ^ 3 
and
             3 Ctrl / 4 
and
             Esc p Esc
and
             Esc ee EscCtrl ^ x

(2^3)
(3/4)
π
(E^x)

Exact and Approximate Results

Unlike a calculator, Mathematica will write an expression in its “exact” form rather than always providing a numerical result:

3/4

To force the evaluation to provide a numeric, usually approximate, result, specify at least one of the input values with a decimal point:

3./4

Another way to get an evaluation is to use the Numerical Value Function N[] :

π
N[π]

The six digits of precision above is the default; a different precision can be specified as a second argument, separated by a comma:

N[π,100]
N[π,1]

Traditional Functions

Mathematica provides an incredibly large number of mathematical functions.
Note that all of its built-in functions begin with a capital Roman letter, e.g. Sin[].
Unlike other languages, Mathematica functions use square brackets to encase their arguments, which are comma-separated:

Cos[π/4]

Log[E]
Log[10,100]

Many traditional functions are displayed in the Basic Math Assistant palette, but all of them are searchable in Mathematica’s help system:
	◇ Menu: Help -> Documentation Center

Lists of Values; Matrices

A very useful device is a list of values, comma-separated and enclosed in curly braces:

{1,1,2,3,5,8,13,21,34}

Many operators and functions will work intelligently with lists, working through them item-by-item (don’t retype the above list, copy and paste it into a new cell for the following):

{1,1,2,3,5,8,13,21,34}* 2

Sin[{1,1,2,3,5,8,13,21,34}]

Multidimensional arrays, aka matrices and tensors, can be produced by nesting lists, perhaps more clearly if you put returns after each row:

{
{1,1,2},
{3,5,8},
{13,21,34}
}

The single-line output above is Mathematica’s standard format for lists. To display such arrays with the traditional vertical format, you can use the function MatrixForm:

MatrixForm[{{1,1,2},{3,5,8},{13,21,34}}]

To produce this display in general, you can change your preferences:
	1. On Windows menu Edit, and on the Mac menu Mathematica.
	2. Select the menu item Preferences… 
	3. In the dialog Preferences, click on the tab Evaluation.
	4. In the section Input and Output, menu Format type of New Output Cells, 
	    and select TraditionalForm.

Extracting List Elements

An item in a list can be referenced using the Part operator [[ ]], which surrounds the index of the list item you want:

{1,1,2,3,5,8,13,21,34}[[6]]
{{1,1,2},{3,5,8},{13,21,34}}[[2]]

Items in nested lists can be referenced by indices separated by commas:

{{1,1,2},{3,5,8},{13,21,34}}[[2,1]]

An index can also be the keyword All, to select out an entire column or row:

{{1,1,2},{3,5,8},{13,21,34}}[[All,2]]

Symbols

Defining Symbols

Mathematica lets you define your own symbols or variables, and assign values to them for later use, with the Set operator  =  :

a=2+7
b=4
diff =a-b

As with the symbol diff, symbols can use any number of characters, but they must start with a letter.
Generally speaking you should also avoid beginning symbols with capital Roman letters, since Mathematica always uses them for its built-in functions and constants.
There are also a number of special symbols that you must avoid, e.g. π and *, which either have special values or are interpreted as operators.
Generally you can use most alphanumeric characters, including other Greek letters, which are entered in the same way as for π, for example Esc a Esc for α and Esc q Esc for θ:

α=47.8 
θ=π/4

Lists can be used to assign multiple values to multiple variables:

{x,y}={1, 2}
x
y

Suppressing Evaluation Results

Just as with numeric expressions, the value of an assignment is printed out after its evaluation.
You can suppress this value display by ending the expression with a semicolon:

c=5;
c*2

Semicolons also allow you to string together several expressions on the same line:

c=5; c*2

Clearing Assignments

To clear an assignment, use the Unset operator =. or the Clear[] function:

θ=.
Clear[α]
θ
α

Symbolic Algebra

Mathematica was first and foremost a “symbolic manipulation” program, so symbols or variables do not have to have values assigned to them to be used in expressions:

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

Mathematica will perform many simplifications of symbolic expressions, such as the grouping of different powers in the previous expression.
Important: if x has already been assigned a value with =, that will be substituted into symbolic expressions, possibly preventing you from seeing its algebraic structure! Hence it’s a good idea to preface symbolic expressions by unsetting their variables with =., as above. (In any kind of mathematics, plugging in the numbers is always the last step you should perform!)

In some cases the possible simplifications cannot be distinguished, as in the case of:

Sqrt[x^2]

Simplify[] can be used to declare assumptions about the parameters in the first argument:

Simplify[Sqrt[x^2],x∈Reals]

Every assumption is a logical statement, whose value is assumed to be true. In this case, the symbol ∈ means “is an element of”, i.e. x is a Real number. Can you find ∈ in the Basic Math Assistant palette? (Hint: it’s an operator like × .)
In the following, an inequality implies a Real value, producing an even more specific result:

Simplify[Sqrt[x^2],x<0]

Rules (Temporary or Potential Assignments)

Mathematics textbooks will often indicate that a symbolic expression should be evaluated by temporarily assigning a symbol a particular value, using a notation such as the following:
                 (2/(1+ x))|(Underscript[ , (Subscript[, x=0])])
Mathematica allows you to do the same thing with a similar notation using the ReplaceAll operator /. and the Rule operator -> :

x=.
(2/(1+x))/.x->0

Note: if x has already been assigned a value with =, that will be substituted before a rule can be applied.
Neither the expression itself nor the value of x are changed outside of this particular evaluation, so you can also try another value:

(2/(1+x))/.x->1
x

Rules will often be used to describe possible solutions to equations, which use the double-equal == to distinguish them from assignments:

zeros=Solve[1-2x-3(x^2)==0]

Since this result is structured as a three-level list (including the rules, which behind the scenes have the format Rule[x,-1]), particular values can be extracted using a [[ ]]expression and assigned to a list of destination variables:

zeros[[All]]    (* This will always produce its own list *)
zeros[[All,1]]
{x1,x2}=zeros[[All,1,2]]

Symbols as Templates

Symbols are often used in function arguments as templates for values that can change.
For example, the Table[] function generates lists according to an expression you define over a range that you specify:

Table[(x^2),{x,0,6,2}]  (* This is the same as: {0,2,4,6}^2 *)

The first argument is the expression (x^2) .
The second argument is a structured list that provides an iteration specification over a range of values assigned to the symbol:
	{symbol, initial, final, step}
So here the symbol x is sequentially assigned the values 0, 2, 4, 6.
The parameter step can be omitted, in which case it is assigned the value 1. In some functions, if step is omitted the range is taken to be continous.
The Table[] function has the property HoldAll that prevents its arguments from being evaluated if there is a prior definition of x.

Manipulating Symbols

Any symbol can be changed interactively using the Manipulate[] function, providing a powerful visualization tool.
For example, we could change the argument of a function and watch its output change:

Manipulate[Sin[θ],{θ,0,π}]

Here there is an iteration specification for the symbol θ, which is allowed to vary between 0 and π in a visually continuous way.
If you click on the  +  to the right of the slider, the specific value of θ will be displayed, along with some controls:
	⇒ Play (all values)		→ ← ↔ Play Direction
	+ Step Forward			⇑ Play Faster
	– Step Backward		⇓ Play Slower

Syntax Coloring

Mathematica uses different colors for its symbols depending on their use. Assigned symbols are black, unassigned symbols are blue, template symbols are blue-green, and (as we will see later) pattern symbols are green and italic:

c
c2
Table[c3,{c3,0,100}]
f[x_]:=x*5

Syntax coloring provides you with really important clues about the expressions you write — if you expect a variable to have a value but it’s blue, there’s a problem you should track down.
Note: most of this notebook has syntax-coloring turned off.

Plotting Functions

Mathematica provides the capability to plot functions fairly easily.

Linear Plots of Functions

A one-dimensional function, i.e. the points { x,  f(x) }, can be quickly plotted on a linear scale using the function Plot[]:

Plot[Sin[θ],{θ,0,2 π}]

Here the first argument is the function to be plotted.
The second argument is an interation specification {symbol, initial, final}. It doesn’t allow for a fourth step parameter, as it tries to provide a visually continuous graph using its own internal algorithm.

If you want to plot two functions on the same graph, make the first argument a list of the functions:

Plot[{Sin[θ],Cos[θ]},{θ,0,2 π}]

You may have noticed above that Mathematica chose some default colors for these graphs to help distinguish them.
These and other characteristics are controlled by various options to the Plot[] function.
Options are specified by their name and a rule; for example, to explicitly choose the color of the line, use PlotStyle → color (or a list of colors if there is more than one function):

Plot[{Sin[θ],Cos[θ]},{θ,0,2 π},PlotStyle->{Green,Orange}]

As another example, let’s manipulate both the frequency of the Sin[] function and also a colored “filling” between the curve and the x axis:

Manipulate[
Plot[Sin[m*x],{x,0,2 π},Filling->Axis,FillingStyle->Hue[m/3]],
{{m,1},0,2}  (* {m,1} defines an initial value *)
]

Note that in the range specification {{m,1},0,2}, the first item is the initial value of m.
Notice the use of the function Hue[], which takes arguments between 0 and 1, representing colors around the color wheel Red-Yellow-Green-Cyan-Blue-Magenta-Red.
Question: Can you think of a physical interpretation of this choice of colors?

Range and Axes Plotting Options

In the plots above, the axes’ ranges are determined “automatically”, are unlabeled, have a default tic mark spacing, etc. Automatic ranges are a particular problem for a manipulated plot. Not surprisingly there are options to adjust these details. 
For example, to fix the range of a plot so it doesn’t change when the function changes, include the option PlotRange in a rule using either one or two pairs of numbers, {ymin,ymax} or {{xmin,xmax},{ymin,ymax}}:

Manipulate[
Plot[Sin[m*x],{x,0,2 π},PlotRange->{-1,1},
Filling->Axis,FillingStyle->Hue[m/3]],
{{m,1},0,3}
]

To add an axis label, include the option AxesLabel in a rule assigning it a pair of character strings, any text between double quotes, e.g. {”xlabel”,”ylabel”}:

Manipulate[
Plot[Sin[m*x],{x,0,2 π},AxesLabel->{"kλ","Amplitude"},PlotRange->{-1,1},Filling->Axis,FillingStyle->Hue[m/3]],
{{m,1},0,3}
]

Other plotting options include PlotLabel, AspectRatio, Axes (their presence or absence), AxesOrigin, AxesStyle, Ticks, and GridLines.

Defining Your Own Functions

Function Definitions

You can define your own functions with a more general type of assignment:

f[x_,y_]:=(Sqrt[(x^2)+(y^2)])
f[p,q]
f[3,4]

There are three things to notice in such a function definition:
1. The independent variable(s) in the function definition (the arguments x and y here) must be distinguished by an appended underscore _ , which indicates a pattern or placeholder for the same symbol on the right side of the assignment.
2. The function definition uses the delayed evaluation assignment operator := , which prevents the right side of the definition from being evaluated until function arguments have been supplied.
3. When using := , the display of results is also suppressed (after all, no evaluation occurs!).

As with simple variables, you should always begin function names with lower-case letters, since Mathematica uses capital letters to distinguish its built-in functions and constants.
Note: It is possible to use an ordinary assignment operator = in function definitions, but then anything that can be evaluated on the right side, including value substitutions, will occur before the assignment, which is not usually what you want (see below for one example, though).

Recalling and Clearing Function Definitions

To recall a function definition, use the ? operator:

?f

To clear a function definition it’s best to use the Clear[] function to reference all variations:

Clear[f]
f[1]

It’s a good practice to always clear a function name immediately before you define it, keeping them together in the same cell. This will help ensure that, as you build complicated expressions, previous versions don’t accidently hang around and get used instead:

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

The function above is the Maxwell-Boltzmann Distribution, defined using the exponential constant e.

Using Functions

The functions you define can be used anywhere you would use a built-in function, e.g. they can be plotted and manipulated:

Manipulate[
Plot[mb[v,vm,100],{v,0,100},PlotRange->{0,10}],
{{vm,20},0,60}
]       (* vm initially set to 20 *)

Calculus

Mathematica can perform many basic and advanced calculus tasks.

Partial Derivatives

Partial derivatives (derivatives with respect to one variable in a function) can be specified with the D[] function, which automatically applies the calculus chain rule, if necessary:

(* Recall: mb[v_,vm_,n_]:=((4*n)/((Sqrt[π])*(vm^3)))*(v^2)*(E^(-(v^2)/(vm^2)))     *)
derivative=D[mb[v,vm,n],v]

Solve[derivative==0,v]

Question: what does this tell you about the meaning of vm?

Higher-order derivatives are also possible, by repeating the independent variable(s) to be used:

D[mb[v,vm,n],v,v]
D[mb[v,vm,n],v,n]

The Basic Math Assistant palette provides another way to represent partial derivatives:

(∂_v)mb[v,vm,n]
(∂_(v,v))mb[v,vm,n]

Integrals

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

Integrate[(1/x),x]      (* An indefinite integral *)

Integrate[(1/x),{x, 1, 2}]       (* A definite integral *)

The Basic Math Assistant palette provides a represention of both types of integral in the standard mathematical format:

∫x*Cos[x]\[DifferentialD]x
(∫_0^π)(x^2)*((Sin[x])^2)\[DifferentialD]x

Assumptions

Recall that integrations are often dependent on particular values of the parameters in the integrand:

(1/n)Integrate[mb[v,vm,n],{v,0,∞}]

The parameter v is implicitly limited to nonnegative Real values by the integration range, but nothing is said about vm, which could potentially be a Complex value with Real and Imaginary parts.
Mathematica therefore lists the possible solutions using the ConditionalExpression[] function, whose second argument can be True or False,  returning the first argument or Undefined, respectively.

As with the function Simplify[], we can restrict the possible integration results in advance using the option Assumptions, assigning it an expression that will be assumed to be True:

(1/n)Integrate[mb[v,vm,n],{v,0,∞},Assumptions->Re[(vm^2)]>0]

Since vm is intended to represent one possible value of the speed v, it’s possible to make an even more restrictive assumption:

(1/n)Integrate[mb[v,vm,n],{v,0,∞},Assumptions->vm>0]

(From this it’s clear that the Maxwell-Boltzmann distribution meets one criteria of a probability distribution; the factor 1/n makes it the probability per molecule.)

You can also define the characteristics of variables for all possible later uses using the global parameter $Assumptions, which is used as the default value for the option Assumptions. This allows one to, for example, use the integral form (which can’t accept options):

$Assumptions=vm>0; (* Real, Positive *)

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

Question: what does this quantity represent?
Multiple assumptions can be put into a list, e.g. $Assumptions = {vm > 0, n > 0}.