Mathematica for Calculating Pi

The first part of this notebook (with fancy colors if you view it on your computer) is copied from one of the excellent Math 21a tutorials.

Introduction to Mathematica

Mathematica Cells

Mathematica notebooks are subdivided into cells, each of which is marked by a blue bracket at the right of the window.  These cells come in several different types.  For instance, the text you are currently reading is in a "text" cell, while the expression below is in an "input" cell.

76-23

You can tell the different types of cells apart by the font they use: text cells use a normal weight proportional width font (Times), while input cells use a boldface typewriter-style font (Courier).  Text cells are just for show, containing instructions, descriptions, or explanations.  If you want Mathematica to evaluate a mathematical expression, you must put it in an input cell.  To create a new cell, position the cursor between two existing cells or after the last cell.  The cursor will then change from a vertical I-beam to a horizontal I-beam.  If you click there, Mathematica will draw a horizontal line across the window.  If you then start typing, Mathematica will create a new input cell for you.  Any new cell you create will automatically be an input cell.  (Creating a text cell takes an additional step, but you won't be needing to create any text cells in these labs.)

Try creating a few input cells and entering a few expressions in the space below.

Evaluating Expressions

All commands are entered into Mathematica as text.  To evalute an expression, click anywhere in the expression and press the <Enter> key on the keypad (not the one on the main keyboard) or hold down the <Shift> key and press <Enter>.  Mathematica will then think for a moment and write the answer below the expression.  Your input and Mathematica's output are labeled "In[#]:" and "Out[#]:" respectively, and Mathematica draws the input in boldface to distinguish it from the plain text output.  For example, to add the following two numbers, click the sum below and press <Shift-Enter>.

3+8

Basic Operators

The basic operations are + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation).  Mathematica obeys the usual operator precedence, first performing exponentiation, then multiplication and division, and finally addition and subtraction.  If you want to group your operations differently, use parentheses ().  Try evaluating the following expressions:

12-3*5

(12-3)*5

6/2*3

6/(2*3)

-5^2

(-5)^2

If you put two expressions next to each other separated only by a space, Mathematica multiplies them, just like in normal mathematical notation.  This can be confusing if you just put two numbers next to each other, but it comes in handy with more complicated expressions.  Here are some examples:

5 2

3(8-4)

Functions and Constants

Mathematica comes preprogrammed with lots of functions and constants.  Some of the functions we will be using are Sin[x], Cos[x], Exp[x] (the exponential (e^x)), Log[x] (the natural logarithm ln x), Sqrt[x] (square root (Sqrt[x])), and Abs[x] (the absolute value |x|).  Note that the first letter of all built-in functions are capitalized, and you use square brackets [] to apply them, as opposed to regular parentheses ().  Some useful constants that Mathematica knows are Pi (or π) and E (or e ≈ 2.71828, the base for natural logarithms).  Again, be sure to capitalize the first letter.  Alternatively, you can use the palette of templates and symbols on the right of your screen to type in some of these operators and constants.  (If you do not see the palette, select from the menu File - Palettes - BasicInput.)  Here are some examples.

Sin[0.123]

Just like in standard math notation, if you write two things next to each other with only a space between them, Mathematica multiplies them.

Cos[2 Pi]

When you evaluated this next expression, note that Mathematica is clever enough to give you the exact answer, rather than a decimal approximation.

Sin[π/4]

If you prefer a numeric approximation, add //N to the end of your expression.

Sin[π/4]//N

Defining Variables and Functions

Mathematica is more than just a fancy calculator.  It lets you do both symbolic and numerical calculations using variables and functions.  You can use any string of letters for a variable name.  In addition to the usual variable names x, y, t, you can also use more descriptive names like theta or radius.  You can assign variables a value and then use that value in further computations.  Here are some examples:

a=5

a^2 - 3a + 4

b=-3

a b

Notice that if you write two variable names next to each other separated only by a space, Mathematica multiplies them, just like in normal mathematical notation.  However, you must take care to put in the space between your variable names.  Otherwise, Mathematica will think that you are talking about a single variable with a long name!  For instance, in the following cell, instead of multiplying a by b, Mathematica assumes you are using a new variable ab:

ab

To define a function for Mathematica, we write f[x_] := value, where f is the name of the function, x is the variable, and value is the expression for the function.  Note that when defining a function, you again use square brackets [] instead of parentheses. In Mathematica, this distinction is very important; parentheses () are used to group expressions, while square brackets [] are used when applying a function.  When defining a function, you use colon-equal := instead of a normal equal sign, and you put an underscore _ immediately after the variable name.  This tells Mathematica to evaluate the right side only after plugging in the value of the variable.  Note that Mathematica does not give you an output when you define a function, but once a function is defined, you can apply it to any number you want, or even to a variable or expression.  When you are finished typing out
your function definition in the input cell, you must type 'enter' on the keypad or hold down
'shift' and press 'enter' on the regular key board to tell Mathematica that your definition is ready.
(This tells Mathematica to read the input cell). Give the following functions a try:

f[x_]:=x^2-3x + 4

f[5]

f[t+1]

Here we define a function of two variables.  Note that your variable and function names can be as long or as descriptive as you like.

DistanceFromOrigin[x_,y_] := Sqrt[x^2+y^2]

DistanceFromOrigin[3,5]

Mathematica attempts to keep everything that it calculates exact, and it only grudgingly makes numerical approximations.  The approximation function is named "N." It comes in two flavors.  With one argument it calculates a predefined number of digits:

N[Pi]

This version lends itself nicely to the convention that 
F[i] can also be written as i//F.

Pi//N

If you want more precision, there is a version of N[] with two arguments.  The second is the number of digits.

N[Pi,20]

If you want to change the default minimum number of digits for the function N[], you can do it with

$MinPrecision = 20

Pi//N

One way to calculate pi is with the sort of "operational" programming done in C++.  To support this, Mathematica has functions named If[], For[], and While[]. Here are some trivial examples.
If[] evaluates its first argument.  If the result is "true" it returns the second argument, otherwise the last argument.

IfFunc[n_] := If[Mod[n,3] == 1,1000, n]

Remainder on division by 3 is not 1

IfFunc[5]

Remainder on division by 3 is 1

IfFunc[4]

Here is the documentation for For[], obtained by choosing Help...Master Index... from the main menu, then selecting For

◼ For[start, test, incr, body] executes start, then repeatedly evaluates body and incr until test fails to give True. 
◼ For evaluates its arguments in a non\[Hyphen]standard way. 
◼ For[start, test, incr] does the loop with a null body. 
◼ The sequence of evaluation is test, body, incr. The For exits as soon as test fails. 
◼ If Break[ ] is generated in the evaluation of body, the For loop exits. 
◼ Continue[ ] exits the evaluation of body, and continues the loop by evaluating incr. 
◼ Unless Return[expr] or Throw[expr] is generated, the final value returned by For is Null. 
◼ Example: For[tot=0; i=0, i < 3, i++, tot += f[i]]. Note that the roles of semicolon and comma are reversed relative to the C programming language.

This will sum the first 100 terms of Gregory's series

For[i=0; sumGreg = 0, i < 100, i++, sumGreg += 4*(-1)^i/(2 i +1)]

sumGreg

Notice that the result is kept as a rational number, but we can get a decimal approximation if we want one.

sumGreg//N

To keep executing a statement as long as a given condition remains true, use While[].  Here are excerpts from the on-line documentation.

◼ While[test, body] evaluates test, then body, repetitively, until test first fails to give True.

◼ While[test] does the loop with a null body. 
◼ If Break[ ] is generated in the evaluation of body, the While loop exits. 
◼ Continue[ ] exits the evaluation of body, and continues the loop. 
◼ Unless Return[ ] or Throw[ ] are generated, the final value returned by While is Null. 
◼ Example: i=0; While[i < 0, tot += f[i]; i++]. Note that the roles of ; and , are reversed relative to the C programming language.

Here is an example that uses Newton's method to calculate the square root of 2 to 20 decimal places of precision, starting with 1 as an initial estimate.  By using semicolons, it is easy to make a statement look like a C or C++ program.

sqrt2 = 1; 
sqSave = 0;
While[Abs[sqSave-sqrt2] > .0000000000000000000001,
sqSave = sqrt2;
sqrt2 -= (sqrt2^2-2)/(2*sqrt2);
Print[N[sqrt2,20]]
]

sqrt2*sqrt2//N

Another way to do this sort of calculation is to use the function FixedPoint[]
FixedPoint[f, expr] starts with expr, then applies f repeatedly until the result no longer changes.

In this case, f must be a Mathematica function, so we define

SqRootIterate[x_] := N[x - (x^2-2)/(2*x),20];

FixedPoint[SqRootIterate, 1]

If you forget to use N[] in the definition of SqRootIterate[], Mathematica will try to get the square root of 2 to infinite precision, and the calculation will never stop (until you select Kernel...Abort Evaluation)

As another example, here is a calculation of pi to 20 digits using Archimedes' recursion.  It is a good idea to replace one of the numbers used in the calculation (in this case 3) by an approximate value.  Otherwise Mathematica will keep computing exact expressions with nested square roots, which takes forever!

Inscribed = N[3,20];
Circumscribed = 2 * Sqrt[3];
While[Abs[Inscribed- Circumscribed] > 10^(-20),
Circumscribed = (2*Inscribed*Circumscribed/(Inscribed+ Circumscribed));
Inscribed = Sqrt[Inscribed*Circumscribed];
Print[N[Inscribed,20]]
]

For comparison purposes

N[Pi,20]

Mathematica also has functions that directly compute sums and products.  These allow direct input of mathematical formulas, without the need to devise an algorithm for computing the sum.  Here is part of the relevant documentation.

◼ Sum[f, {i, imax}] evaluates the sum (∑_(i = 1)^("imax")) f. 
◼ Sum[f, {i, imax}] can be entered as (∑_i^imax)f. 
◼ ∑ can be entered as sum or ∖[Sum]. 
◼ Sum[f, {i, imin, imax}] can be entered as (∑_(i=imin)^imax)f. 
◼ Product[f, {i, imax}] evaluates the product (∏_(i = 1)^("imax")) f. 
◼ Product[f, {i, imax}] can be entered as (∏_i^imax)f. 
◼ ∏ can be entered as prod or ∖[Product]. 
◼ Product[f, {i, imin, imax}] can be entered as (∏_(i=imin)^imax)f. 
To bring up the special sum and product symbols, choose File...Palettes...Basic Input from the main menu.

Example: the first 1000 terms of Gregory's series

Sum[4*(-1)^(i-1) / (2*i-1),{i, 1000}]//N

Another example: the first 2000 factors of Wallis's product

2*Product[(4i^2)/(4i^2-1),{i, 1000}]//N