$Line=0;

Scientific Arts

Learning Mathematica

This notebook is Copyright © 2014 Scientific Arts, LLC,  all rights reserved.  It may be redistributed only in full and in its original form without modification; and it may not be used for any commercial purpose without permission from Scientific Arts.  A non-exclusive royalty-free license is given to reproduce and use all the of the Mathematica code in this notebook for any purpose whatsoever, as well as any of the ideas.  No guarantee whatsoever is given as to the  accuracy or functionality of anything presented in this document.  Use at your own risk. 

Enjoy!I hope that it's useful. For further information on Scientific Arts Consulting and Training, please click on the following Link: Scientific Arts.

To email, use the following address info@scientificarts.com.

Functions

In Mathematica there are many things that you can do.  Huge numbers of things.  And the things that do these are called functions.  So, I will use this word in what follows, but I will explain more of what it means a bit later on.  For now though, just assume that a function is like a machine that takes things—numbers, sets of things, pictures, sounds,...—and does things to them and then often gives you an answer.

Brackets

There are three kinds of brackets.

Parentheses: ( )

Parentheses are used to group things, just as they are used in arithmetic and algebra.  Here is an example:

4(12+7)

Here is another example

a(1+x)

In the last case Mathematica does not do anything to the expression because you haven't asked it to.  But you could if you wanted to using the Mathematica function called Expand (this uses another kind of brackets, square brackets) that we will describe in a little while):

Expand[a(1+x)]

And this is what you would expect if you did the algebra as an exercise.

Curly brackets: { }

Curly brackets are used in Mathematica to create lists of things—almost any sorts of things. You can then use these lists in many ways.

Here is an example of a list of integers:

{1,2,3,4,5}

Notice that each of the separate things (in this case the 5 integers from 1 to 5) is separated by a comma.

There are many functions in Mathematica that can create interesting lists, and there are many functions in Mathematica that do interesting things with lists.

Here is a function, called Range, that creates a list of integers

Range[10]

that's the first 10 integers.  Notice that they are contained in curly brackets. Here are the first 50 integers:

Range[50]

Square brackets: [ ]

Functions in Mathematica generally have "arguments": they are the information that you need to give the function so that it can do what it is designed to do.  That information is given to the function within its square brackets.  So, for example the Mathematica function PrimeQ tells us whether an integer is a prime or not.  You give PrimeQ that integer inside of the square brackets—this integer is PrimeQs single argument:

PrimeQ[12131993]

So, 12131993  is not a prime.

But we can factor it into its prime factors

FactorInteger[12131993]

Ok, so this is a product of a big prime and a little prime.

Some functions only allow a particular sort of information to go within the square brackets.  For example, it doesn't make sense to ask Mathematica to factor a number that is not an integer:

FactorInteger[1.234]

When Mathematica doesn't know what to do with the arguments that you give a function it just answers with what you typed.  And often it will give you a sensible error message that can help you figure out what is going on.

A function can have more than one argument, and each argument might need to be a particular type.

For example, the function Range can take one or two arguments, which each need to be integers

Range[10]

for one argument and

Range[10,20]

for two arguments.  Actually there is a three argument version as well.  Can you guess what it's doing?

Range[5,30,5]

Using your own symbols

Mathematica has a number of things that are symbols, that have a value.  For example the number π is represented by either Pi or π.  And those symbols have values.  You can compute those values numerically using the N function:

N[Pi]

(Even though most Mathematica functions are written out as whole words, some very common ones are written in a shorthand.  The N function is one of these.)

For more information about N, click here:  "N Documentation"

And you can use the N function with a second argument to tell Mathematica to compute the numerical value of a number to however many decimal places you want to.  Here it is where we compute the decimal value of the rational number (123/456) to 100 places and see that, as you expect, it is a repeating decimal. Can you see the pattern?

N[(123/456),100]

In Mathematica you can make your own symbols and give them values.  The way that you give a value to a symbol is using the assignment function.  This is just an = sign.  But its meaning is different than it is in the mathematics that you learn in school.  Here it means that you should make a symbol "own" a value.  For example

myValue=9

This assigned the value 9 to myValue, and Mathematica remembers this through the Mathematica session that you are in.  Here it is again:

myValue

If you want Mathematica to forget the value that you have assigned to your symbol, you can Clear it with the—you guessed it—the function Clear.

Clear[myValue]

Now myValue no longer has a value

myValue

For more information about Clear, click here:  "Clear Documentation"

Doing things with the symbols that you give values to

If you give a symbol a value then you can do things with it: simple things or very complex things.

Let's give x a value

x=12

Now we can do whatever we want to with x. For example, the symbol can be in an expression.  And when that expression is evaluated Mathematica will use the symbol's value to compute with it.

(x^3)+12x+19

Notice that there is a space between the 12 and the x to indicate multiplication.

Here's another example

a (x^2)+b x+c

Just for cleanliness, and so we don't make a mistake later on, let's clear the value of x:

Clear[x]

Often when you give a value to a symbol you don't need to see it's value get printed out.  You can keep it from getting printed out by ending the Mathematica statement with a semicolon like this example.

x=1.23456;

Even though nothing printed out when you executed that, x still has the new value

x

Let's get rid of that value

Clear[x]

You do not have to have all of the things that you are doing in separate cells.  For example two or more expressions can follow one another in the same cell with each one ending in a semicolon.  Here is a simple example

x=19;
(x^2)+12

The last result without a semicolon is what is printed out.

Since I am using x a lot I will clear it after each time I do something with it.

Clear[x]

Here is an example that is a bit more complicated, using two symbols.  Each of the expressions is evaluated by Mathematica on after the other.  And each subsequent one uses the things that were done in the ones before it.

x=3a;
y=(x^2);
(y^2)+12

This clears both x and y:

Clear[x,y]

Making your own functions that you can reuse

Each time up to now that we have done something, we do it once.  And if we want to change it we'd need to edit it and change some of the values that are assigned.  But we'd like to be able to do what Mathematica does: to have functions of our own that take arguments in their square brackets and which we can reuse over and over by changing the values that we put in the square brackets.

We do this using "patterns" and "delayed assignments."

Patterns are, in a way, the shapes of the things we want to put into a function.  Lets make our own function that squares a number.  We will call it mySquare.

Here is one way to do it:

mySquare[z_]:=(z^2)

The z_ in this is really just a name or a tag to show that the thing that you will put in the square brackets on the left hand side should be placed in the places where a z appears in the right hand side.  Then, after this is done (which is why the := is called a delayed assignment) Mathematica evaluates the right hand side.

The way you write a pattern uses the underscore character right after the pattern's name.  The pattern is on the left hand side of the expression (the side to the left of the :=), and the name of the pattern is what it used on the right hand side (with out the underscore).

When you use mySquare it does do what you expect:

mySquare[3]

And it does it with whatever you put in it

mySquare[a]

Here is a peculiar example:

mySquare[]

If you use a variable that has a value in it's argument then it will substitute that value first and then do its work

m=7;

mySquare[m]

Clean things up a bit:

Clear[m]

The cool thing is that now you can use mySquare whenever you want to without having to write out the expression that it uses (i.e, the (z^2)).

Of course squaring a number is pretty simple, but here is a more complicated example.

messyThing[x_]:=-17297280+242161920 (x^2)-484323840 (x^4)+322882560 (x^6)-92252160 (x^8)+12300288 (x^10)-745472 (x^12)+16384 (x^14);

You wouldn't want to have to write that out each time!  But you can reuse this complicated thing over and over.

messyThing[0]

That does what you would expect, since all of the terms of the expression have an x in them except the first (the constant part of the polynomial).

Here is another example: it wouild take you a while to compute this by hand:

messyThing[10]

That's a large number....

And, for fun, here is another example where we compute the value of messyThing when its argument is π, and we compute it to 100 decimal places.

N[messyThing[π],100]

Now let's make a new function called pairDifference that takes the first item in a list of two things and subtracts it from the second item in that list.

pairDifference[{x_, y_}] := y - x

And here is how it works:

pairDifference[{3,10}]

But notice that since the way we defined pairDifference for Mathematica tells Mathematica only how to use a list of two things, then pairDifference doesn't know how to compute something like this (with no list brackets inside it):

pairDifference[3,10]

That's ok, since we didn' invent pairDifference to handle this.

Now, here's a little question.  Does the expression  pairDifference[{3,10}] have one argument or two?

It has only one, and that argument is a list of two things.

The number of arguments of a function is the number of things that are separated by commas that are between the square brackets.  So  pairDifference[{3,10}] only has one thing between its square brackets and that thing is a list.

Keeping symbols "private" (local)

One thing that  we've had to keep on doing is to Clear our symbols so that we wouldn't accidentally use one that has a value that we don't remember.  Often one makes mistakes this way when one has given a symbol a value and then forgotten that fact.  Then one uses the symbol again thinking that it doesn't have a value, or thinking that it has a different value from what it actually has.  Then surprising things can happen!

The protective box that you can put symbols into to keep them from "leaking out" with their values is called a Module.  A Module has two parts: a list of the symbols that you want to keep private, and then the expressions that you want Mathematica to evaluate with those private values of the symbols.

Here is an example:

Module[{x},
x=7;
(x^2)]

But notice that if we evaluate x "outside" of the Module it doesn't have the value 7 that it was assigned withing the Module.

x

In fact it has no value because we Cleared it earlier on.

Here is another way to write the same thing that might make it clearer

Module[{x},
(x=7;
(x^2))
]

I put the two statements that have to be evaluated by the Module in parentheses so you can see that they, together, are one thing: the second argument of the Module. Noteice that there is no semicolon after the final statement—the (x^2), because if there was a semicolon there then nothing would get printed out at the end.

Notice that the list of private variables (actually they are generally called "local" variables and we will use term "local' from now on) is separated from the expressions that you will execute by a comma.  Then those expressions are separated from each other with semicolons.

Here is a funny example that gives you a hint of what is going on inside of a Module that helps keep the local symbols "private".

Module[{x},
x]

Each time you evaluate that you get a result that is not x.  And each time you evaluate it you get a different one. And this is how the Module works.  For each of the symbols in the list of local variables, Mathematica actually renames them to have a unique new name each time the Module is executed.  You don't see this, but that is what is going one behind the scenes to make sure that the symbols do not get confused with ones that have values outside of the Module. Inside of a Module you can use symbols from outside the Module as long as they are not made local by being put in the Module's list.

Here is an example.

p=12;

Module[{x},

x=9;
p x
]

Notice that I wrote each seperate expression on a separate line so that I could see more clearly what is going on.

For more information about Module, click here:  "Module Documentation"

Interlude: Some Mathematica functions that you will be using

We have already used some Mathematica functions to show some things in these notes.  Here are some of these functions along with some others for you.

Range

The Mathematica function called Range can be used to make easily list of integers.  Range can be used in several different forms.

The simplest form makes a list of integers starting at 1 and going to the final integer that you tell Range to use.  In this form Range has one argument. Here is an example of this:

Range[20]

The next way you can use Range is to give a list of the integers between two integers that you give to range.  In this form Range has two arguments, the starting integer and the ending integer.  Here is an example of this:

Range[23,37]

The third form for Range had three arguments: the starting integer, the ending integer, and the distance between the integers in the result.  So here is an example that gives the integers, starting at 30 and going to 60, separated by 4:

Range[30,60,4]

Notice that the last integer in the list is not 60.  This is because you can get to 60 from 30 by going in steps of 4.

For more information about Range, click here:  "Range Documentation"

PrimeQ, and Factor Integer

PrimeQ is a Mathematica function that tries to tell you whether an integer is a prime number.  For numbers that are not enormously big, it will give you an answer.  PrimeQ uses very advanced mathematics to do what is does. But you don't need to know how it does its work to use it.

FactorInteger does exactly what you'd expect it to do: it takes an integer and gives you its prime factors.  It takes only one argument: the number that you want to factor.

PrimeQ only takes one argument, the number that you are checking to see if ti is prime. Here is an example.

PrimeQ[123456789]

Well, since PrimeQ tells us that 123456789 is not prime, we can use FactorInteger to see what its prime factors are.

FactorInteger[123456789]

For more information about PrimeQ, click here:  "PrimeQ Documentation"

For more information about FactorInteger, click here:  "FactorInteger Documentation"

Select

The Mathematica function Select helps you select things from a list that have a particular property that you are interested in.  Select takes two arguments.  The first it the list you are selecting from.  The second argument  that you give Select is the test you are going to give each of the elements of the list to see if it is one you want to select.

That second argument needs to be a function that gives True or False, so that Select knows—when the answer is True—to select an element from the list.

So here is an example. First lets make a list of integers from 100 to 200 using Range.  And let's make sure to give it a name—a symbol—and we'll call that symbol someIntegers.  We use the = sign to assign the result of using Range to the symbol, and we end the statement with a semicolon so it won't print everything out, since we don't need to see those integers right now.

someIntegers=Range[100,200];

Now we can use Select with PrimeQ as the test to choose the prime numbers from this list:

Select[someIntegers,PrimeQ]

And those are all of the prime numbers between 100 and 200.

The sort of slightly confusing things about how PrimeQ appears in the second argument of Select is that it doesn't have any square brackets.  But the way Select works is that you give it the name of the function that you want to use to test each of the elements in the list, and then Select takes that function's name and wraps square brackets around each of the elements of the list and puts the function name in front of the square brackets.  Then it executes each of these and chooses the items in the list that answer True.

For more information about Select, click here:  "Select Documentation"

Partition

The Mathematica function Partition is another function that does helpful things to lists. It takes a list and lets you regroup the elements in the list in useful ways—and it can do this in all sorts of ways.

The first argument of the Partition function is always the list that you want to do stuff to.  The other arguments of Partition tell it how to regroup the list.  There are all sorts of ways to give Partition these other arguments, but we'll just explore a few of them.

So, just to prepare a list for us to work with let's assign a simple list to a symbol:

testList=Range[10]

I let it print out so we can use it to look at to compare things with.

Here is one way to use Partition with one extra argument.  This argument—which should be an integer—tells Partition to take the list that you give it and make it into a list of lists/

So here is an example.  In this we are telling Partition to break the original list into lists of 5 items for each, and not to let them overlap:

Partition[testList,5]

Here's a small but important point.  If you ask Partition to do this, but if there are not enough items in the original list to fill out the last group then Partition will just leave that last group out.

So, since 10 is not divisible by 3, then Partition will leave out the last  couple of items in our original list if we ask it to break things into groups of 3 like this:

Partition[testList,3]

Here's one other example of using Partition this way to get pairs of things out of a list:

Partition[Range[10],2]

Notice that I put Range[10]inside of the  Partition for the first argument just for this example.  This makes sense because first Mathematica computes Range[10] and this is a list as it needs to be, and then Mathematica computes the Partition of the result.

This actually is generally how Mathematica works: Mathematica computes things from the inside out: it first computes the things inside of a function that it will need for that outside function to do its work.

There is one other way to use Partition (out of many others) that is very helpful for some problems.  This is to make the lists that you create with Partition overlap the each other.  You do this by giving Partition a third argument that tells it how far to go before starting a new list group.

Here is an example where we make lists of length 3 that  shift by  1 from group to group (we are using testList again here):

Partition[testList,3,1]

And here we make it shift by 2 each time

Partition[testList,3,2]

Can you guess what happens if we ask it to shift by 3 each time?

Partition[testList,3,3]

Well, this is what you'd expect since 3 is also the length of the group. So this is the same as the shorter way of using Partition without the third argument like the was we did it originally:

Partition[testList,3]

So, now that we now how to use Partition to group the items in a list in different ways, we can use it to make all of the pairs of items that are adjacent to each other like this:

Partition[testList,2,1]

For more information about Partition, click here:  "Partition Documentation"

Map

One more Mathematica function that is very useful for us is called Map.

Map is useful you have a list of things, and you have a function that you want to act on each of the things in the list individually—not on the whole list itself  but on each element of the list in turn and give back a list of the results.

Map has two arguments—very much the way that Select does, but with them in opposite order.  The first argument is the function that you want to use on the items in the list, and the second argument is the list whose items want to use that function on.

One of the easiest ways to see what Map can do is to pretend that we have a function—call it emily—that Mathematica does not know about.  So whenever you use   Mathematica will just give you back what you wrote.

emily[7]

So let's use this to see what Map does.

Map[emily,Range[5]]

So Map, goes into the list and wraps square brackets around each of the items in the list and puts the function in front of each of those pairs of square brackets.

Here is an example using PrimeQ as the function and using testList from before:

Map[PrimeQ,testList]

So, corresponding to each of the integers from 1 to 10 we see the True/False value that tells us whether that number is a prime.

Here is another example using Map along with emily and Partition to see how things work. First lets invent another symbol for pairs of numbers

pairList=Partition[testList,2,1]

Map[emily,pairList]

So you see that Map still wraps emily around the items in the list even though those items are in fact lists themselves.

For more information about Map, click here:  "Map Documentation"

Max and Min

Sometimes when you have a list of numbers you want to find the largest one or the smallest one—the maximum or the minimum.  The Mathematica functions Max and Min do this for you.

So, remember testList? It had the numbers from 1 to 10 in it

testList

Obviously the maximum number here is 10 and the minimum one is, well, 1.  But at least this shows clearly how Max and Min work.

Max[testList]

Min[testList]

For more information about Max, click here:  "Max Documentation"

For more information about Miin, click here:  "Min Documentation"

Using Modules to help create your own functions.

Now you can use Modules to make your own functions.  You will often want to do this because you will want to use local symbols to store things that you will be using later in your calculation.

Here is an example that finds the prime numbers between two integers.  It is a function with two arguments.  The Mathematica functions that it uses, Range, Select, and PrimeQ are ones that we have discussed earlier here.  But to remind yourself of what they mean you can look them up in the Mathematica Documentation Center by clicking here: "Click here" or in the places earlier in this document where they are described.

myPrimes[m_,n_]:= 
Module[{data,primes},
data=Range[m,n];
primes=Select[data,PrimeQ];
primes
]

And we can now use it to find the primes between two integers without worrying whether the symbols data and primes will leak out and have values.  Their values stay within the Module.

Here are the primes between 1950 and 2010:

myPrimes[1950,2010]

Yay! You were born in a prime year!  I always know you were a prime person....

Now here is a function that we already worked on together.  It uses all of the things we have learned so far.  Here it is, it uses the Mathematica function called Partition that we talked about earlier. Also, inside of it it uses—as a local functoin inside the Module—the function called pairDifference that we invented earlier:

primeDifferences[m_,n_]:=
Module[{pairDifference,data,primes,primePairs},

pairDifference[{x_,y_}]:=y-x;

data=Range[m,n];

primes=Select[data,PrimeQ];

primePairs=Partition[primes,2,1];

Map[pairDifference,primePairs]

]

And here is how it works.

primeDifferences[10,20]

Of course you have to be careful about what you put in for its arguments since this can compute a lot of primes!  Here are the results for the first primes in the first 1000 integers.  So be careful!  If you asked for the primes in the first million integers then it would take up a lot of space....

primeDifferences[1, 10000]

But remember that you can always assign a result to a symbol with a semicolon so that it doesn't get printed out.  Then you can use that symbol to reuse the result in a variety of other places (for example, to plot it in some way) without having to ever print it out.

So, for example, we can call this something else like primeDifferenceData and end it with a semicolon so it doesn't get printed out:

primeDifferenceData=primeDifferences[1, 10000];

Then we can ask for the biggest one amongst all of them:

Max[primeDifferenceData]

Lets do this for the first 2 million numbers. But let's put both commands in the same cell so that we don't have to execute two cells.

primeDifferenceData=primeDifferences[1, 2000000]; 
Max[primeDifferenceData]

Well, this is something that perhaps we might want to turn into a function.  So let's use what we just did here as the starting point for making that function. To do this we will need to use patterns and a Module (because we want to make the symbol primeDifferenceData a local one so it doesn't get confused with the version of it that we just used).  And we should make it a bit more general than the example above so that it can take a starting integer and an ending integer. Remember all of the commas, underscores, and semicolons that you need here. Also remember to use the := rather than a regular =.

abyss[m_,n_]:=
Module[{primeDifferenceData},
primeDifferenceData=primeDifferences[m, n]; 
Max[primeDifferenceData]
]

Now we can use it

abyss[1,2000000]

Here is an example for the the biggest prime difference that exists between 10×(10^6) and 20×(10^6):

abyss[10 (10^6),20 (10^6)]

Pretty cool....