Programming in Mathematica

Math 242: Modern Computational Math

Basics of Mathematica

All Mathematica commands and built-in functions begin with capital letter. For example: Simplify, Cos, Sqrt, Pi

Function arguments are enclosed in square brackets and separated by commas. For example: Sin[x], Log[10,x]

Lists are enclosed in { and }, like this: {x, y, z}. Elements of a list are selected with double square brackets, like this: mylist[[1]].

Press ⇧-⌤ to evaluate a cell. A semicolon at the end of a command hides the  output from that command.

Help information can be accessed by typing a question mark before a command, like this: ?Cos.

Variable Assignments

Variable Names

You can define variables with almost any name. However, variable names cannot start with a number or contain an underscore (_). Since built-in objects have names starting with capital letters, it is conventional for user-defined variables to start with lowercase letters — this helps avoid errors.

For example, the following are valid variable definitions:

a = 5
myVar = 0.1010010001
θ = π/2

As you can see above, variables names may include Greek letters (and other special symbols). You can access these symbols by going to Insert → Special Character, or by using an alias. For example, type EscaEsc on the following line, and observe what character appears:

Clearing Variables

Mathematica remembers values you assign to variables until you remove them. Be careful: forgetting about definitions you made earlier is a common cause of errors when using Mathematica! To remove a value assigned to a  variable, use the Clear command:

Clear[a]
Clear[myVar, θ]

To clear all variables, use the following command:

ClearAll["Global`*"]

Immediate vs. Delayed Assignment

One important thing to note is the difference between immediate assignment ( = ) versus delayed assignment ( := ). Consider the following lines of code, and note the assignment operators used.

x=2
y=x
z:=x

Evaluate the lines above. Now evaluate the following line to see the values of x, y, and z (written as a list to put every thing on the same line, for convenience).

{x,y,z}

Evaluate the next line to change the value of x. The value of y will stay the same, but z changes.

x=10

Evaluate the next line to see all three values. Are they what you expected?

{x,y,z}

If you don’t want to see the output, use a semi-colon at the end of a command, like this:

x=3;
y=5;

Numbers in Mathematica

Mathematica tries to give results in an exact form, whenever possible. For example:

Sin[Pi/10]

If you want a decimal number, you can use the N function to convert the previous result to a decimal.

N[Sin[Pi/10]]

You can provide a second argument to the N function to control the precision of the output — that is, the number of decimal digits that are printed.

N[Sin[Pi/10],20]

Question: What does the word argument mean in the previous sentence?

Another way to make Mathematica return decimal results is to give it decimal input:

Sin[Pi/10.0]

Why is this? Mathematica regards Pi and 10 as exact values (with arbitrary precision), and it will try to give you an exact value for your computation. However, Mathematica regards 10.0 as a “floating-point” number (with limited precision). If you use a floating point-number in your computation, then Mathematica will give you limited-precision output, even if you ask for a lot of digits. Try this:

N[Sin[Pi/10.0],20]

You might think that we should always use exact values, but exact arithmetic is much slower for computers than floating-point arithmetic. This will be an important consideration for some programs that we will write in this course!

Control Structures

The main control structures are if-then-else statements and looping constructs.

If Statements

Here is a basic If statement, which evaluates to “A” if x is greater than 1, and “B” otherwise.

x=0
myVal=If[x>1,"A","B"]

Check the value of myVal:

myVal

Notice what happens if we change to delayed assignment:

myVal1:=If[x>1,"A","B"]

x

myVal1

Now a change to x can change the value of myVal1:

x=12

myVal1

Note that because we put quotation marks around A and B, Mathematica interprets them as strings of text, rather than variables to which we might assign a numerical value.

Exercise: Write an if statement that evaluates to “Happy New Year” if x is equal to 2019, and to “meh” otherwise. Run your loop for various values of x to make sure it works.

Do Loops

Looping is fun and easy. There are many ways to write loops, but the Do loop is probably the simplest. Let’s print the squares of the first ten positive integers:

Do[Print[{i,i^2}],{i,1,10}]

In the code above, the list {i, 1, 10} tells Mathematica that we want to use a counter variable i that counts from 1 to 10. That is, Mathematica runs the statement Print[{i, i^2}] for each (integer) value of i from 1 to 10.

Exercise: Modify this loop to print the squares of the integers from 5 to 20.

Tables

In Mathematica, the Table function produces output similar to loops. The Table function constructs a list of elements constructed according to some expression. For example, the following command produces a list containing the squares of the first ten positive integers.

Table[i^2,{i,1,10}]

The Table function will be very useful for us in upcoming assignments!

Exercise: Use the Table function to produce the list {(a^2)+ (b^2), (a^3)+ (b^3),…, (a^12)+(b^12)}

Accumulators

Often, we need loops that modify some variable at each iteration. A common construct is to initialize a variable outside of the loop, update it with each iteration of the loop, and then do something with the result. A variable used in this way is called an accumulator.

For example, the following code computes the sum of the first ten positive integers. The variable sum is the accumulator.

sum=0;
Do[sum += i,{i,1,10}]

When you run the code above, does anything happen? We don’t see any output because a loop doesn’t print any output unless we tell it to. Now check the value of the variable sum:

Print[sum]

Is this the correct sum?

Exercise: Use a loop with an accumulator to compute partial sums of:   4(1-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)+…). Experiment by computing sums with more and more terms, following the same pattern. What number results? (Convert your result to a decimal.)

Functions

Let’s write some simple functions. You will probably always want to use delayed assignment for functions. Notice the use of the underscore to indicate a variable (a rule, in Mathematica parlance) on the left side of the assignment operator.

Clear[f]
f[x_]:=x^2

Evaluate our function on x = 3...20:

lotofSquares=Table[f[xyz],{xyz,3,20}]

Plot our function on the domain x=-1 to x = 1:

Plot[f[x],{x,-1,1}]

Here’s a function of two variables:

g[x_,n_]:=x^n

Plot a bunch of these functions and specify some plot parameters to get a nice-looking plot.

Plot[Table[g[z,k],{k,0,40}],{z,0,1},
PlotStyle->Black,
PlotRange->{{0,1},{0,1}}]

Getting Help

Mathematica makes it really easy to get help on everything. You will see information icons, completions suggestions, etc as you work. Take advantage of these!

You can also use the question mark to get help for any Mathematica function. For example, run the following:

?Do

?PrimeQ

Google can also answer many questions that you may have about how to do specific things in Mathematica.

Assignment

Complete the following three exercises before class on Monday. You can do the work in this notebook, below each numbered item. Upload your solutions to the Assignment 1 item on the Moodle site for Math 242.

Use a loop with an accumulator to compute partial sums of the following:

s=1+(1/4)+(1/9)+(1/16)+(1/25)+…

Then take your sum s and compute (Sqrt[6s]). Experiment by doing this for sums with more and more terms. What number results? (Convert your result to a decimal.)

Use a loop with an accumulator to compute the following product:

2((4/3))((16/15))((36/35))((64/63))…

Experiment by computing products with more and more factors, following the same pattern. What number results? (Convert your result to a decimal, if necessary.)

Define the function p(n)=(n^2)+n+41. Evaluate this function for n∈{1,2,3,…}. What is the first n for which this function does not produce a prime number?