Scientific Arts

| Scientific Arts | Discovery | Finding Things Out | GettingStarted | Policies | Billing | Classroom | Resources |

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:discover@scientificarts.com.

A Mathematica notebook version of this page is located here.

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:

learningmathematica_1.png

learningmathematica_2.png

Here is another example:

learningmathematica_3.png

learningmathematica_4.png

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 calledExpand(this uses another kind of brackets, square brackets) that we will describe in a little while):

learningmathematica_5.png

learningmathematica_6.png

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:

learningmathematica_7.png

learningmathematica_8.png

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, calledRange,that creates a list of integers

learningmathematica_9.png

learningmathematica_10.png

that's the first10integers.  Notice that they are contained in curly brackets. Here are the first50integers:

learningmathematica_11.png

learningmathematica_12.png

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 functioPrimeQtells us whether an integer is a prime or not. You givePrimeQthat integer inside of the square brackets—this integer isPrimeQ'ssingle argument:

learningmathematica_13.png

learningmathematica_14.png

So, 12131993 is not a prime.

But we can factor it into its prime factors

learningmathematica_15.png

learningmathematica_16.png

Ok, so 12131993 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:

learningmathematica_17.png

learningmathematica_18.png

learningmathematica_19.png

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 functionRangecan take one or two arguments, which each need to be integers

learningmathematica_20.png

learningmathematica_21.png

for one argument and

learningmathematica_22.png

learningmathematica_23.png

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

learningmathematica_24.png

learningmathematica_25.png

Using your own symbols

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

learningmathematica_26.png

learningmathematica_27.png

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

For more information aboutN,click here: learningmathematica_28.png

And you can use theNfunction 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 learningmathematica_29.png to10 places and see that, as you expect, it is arepeating decimal.Can you see the pattern?

learningmathematica_30.png

learningmathematica_31.png

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

learningmathematica_32.png

learningmathematica_33.png

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

learningmathematica_34.png

learningmathematica_35.png

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 functionClear.

learningmathematica_36.png

NowmyValueno longer has a value

learningmathematica_37.png

learningmathematica_38.png

For more information about Clear, click here: learningmathematica_39.png

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 givexa value

learningmathematica_40.png

learningmathematica_41.png

Now we can do whatever we want to withx.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.

learningmathematica_42.png

learningmathematica_43.png

Notice that there is a space between the12and thexto indicate multiplication.

Here's another example:

learningmathematica_44.png

learningmathematica_45.png

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

learningmathematica_46.png

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

learningmathematica_47.png

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

learningmathematica_48.png

learningmathematica_49.png

Let's get rid of that value

learningmathematica_50.png

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:

learningmathematica_51.gif

learningmathematica_52.png

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

Since I am usingxa lot I will clear it after each time I do something with it.

learningmathematica_53.png

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.

learningmathematica_54.gif

learningmathematica_55.png

This clears bothxandy:

learningmathematica_56.png

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 itmySquare.

Here is one way to do it:

learningmathematica_57.png

Thez_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 azappears 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 (without the underscore).

When you usemySquareit does do what you expect:

learningmathematica_58.png

learningmathematica_59.png

And it does it with whatever you put in it

learningmathematica_60.png

learningmathematica_61.png

Here is a peculiar example:

learningmathematica_62.gif

learningmathematica_63.gif

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

learningmathematica_64.png

learningmathematica_65.png

learningmathematica_66.png

Clean things up a bit:

learningmathematica_67.png

The cool thing is that now you can usemySquarewhenever you want to without having to write out the expression that it uses (i.e, thelearningmathematica_68.png).

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

learningmathematica_69.png

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

learningmathematica_70.png

learningmathematica_71.png

That does what you would expect, since all of the terms of the expression have anxin 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:

learningmathematica_72.png

learningmathematica_73.png

That's a large number....

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

learningmathematica_74.png

learningmathematica_75.png

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

learningmathematica_76.png

And here is how it works:

learningmathematica_77.png

learningmathematica_78.png

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

learningmathematica_79.png

learningmathematica_80.png

That's ok, since we didn't inventpairDifferenceto handle this.

Now, here's a little question.  Does the expressionpairDifference[{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.  SopairDifference[{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 aModule. 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:

learningmathematica_81.png

learningmathematica_82.png

But notice that if we evaluatex"outside" of theModuleit doesn't have the value 7 that it was assigned withing theModule.

learningmathematica_83.png

learningmathematica_84.png

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

learningmathematica_85.png

learningmathematica_86.png

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 theModule.Notice that there is no semicolon after the final statement—the learningmathematica_87.png, 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 aModulethat helps keep the local symbols "private".

learningmathematica_88.png

learningmathematica_89.png

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 theModuleworks.  For each of the symbols in the list of local variables, Mathematica actually renames them to have a unique new name each time theModuleis 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 aModuleyou can use symbols from outside theModuleas long as they are not made local by being put in theModule'slist.

Here is an example:

learningmathematica_90.png

learningmathematica_91.png

learningmathematica_92.png

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 aboutModule,click here: learningmathematica_93.png

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 calledRangecan be used to make easily list of integers.Rangecan 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 tellRangeto use.  In this formRangehas one argument. Here is an example of this:

learningmathematica_94.png

learningmathematica_95.png

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

learningmathematica_96.png

learningmathematica_97.png

The third form forRangehad 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 at30and going to60, separated by4:

learningmathematica_98.png

learningmathematica_99.png

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

For more information about Range, click here: learningmathematica_100.png

PrimeQ, and Factor Integer

PrimeQis 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.PrimeQuses very advanced mathematics to do what is does. But you don't need to know how it does its work to use it.

FactorIntegerdoes 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.

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

learningmathematica_101.png

learningmathematica_102.png

Well, sincePrimeQtells us that123456789is not prime, we can useFactorIntegerto see what its prime factors are.  

learningmathematica_103.png

learningmathematica_104.png

For more information aboutPrimeQ,click here: learningmathematica_105.png

For more information about FactorInteger,click here: learningmathematica_106.png

Select

The Mathematica functionSelecthelps you select things from a list that have a particular property that you are interested in. Selecttakes two arguments.  The first it the list you are selecting from.  The second argument  that you giveSelectis 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 givesTrueorFalse,so thatSelectknows—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 usingRange. And let's make sure to give it a name—a symbol—and we'll call that symbolsomeIntegers.We use the = sign to assign the result of usingRangeto 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.

learningmathematica_107.png

Now we can useSelectwithPrimeQas the test to choose the prime numbers from this list:

learningmathematica_108.png

learningmathematica_109.png

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

The sort of slightly confusing things about howPrimeQappears in the second argument ofSelectis that it doesn't have any square brackets.  But the waySelectworks 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 thenSelecttakes 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 answerTrue.

For more information aboutSelect,click here: learningmathematica_110.png

Partition

The Mathematica functionPartitionis 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 thePartitionfunction 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 givePartitionthese 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:

learningmathematica_111.png

learningmathematica_112.png

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

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

So here is an example.  In this we are tellingPartitionto break the original list into lists of5items for each, and not to let them overlap:

learningmathematica_113.png

learningmathematica_114.png

Here's a small but important point.  If you askPartitionto 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, thenPartitionwill leave out the last  couple of items in our original list if we ask it to break things into groups of 3 like this:

learningmathematica_115.png

learningmathematica_116.png

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

learningmathematica_117.png

learningmathematica_118.png

Notice that I putRange[10]inside of thePartitionfor the first argument just for this example.  This makes sense because first Mathematica computesRange[10]and this is a list as it needs to be, and then Mathematica computes thePartitionof 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 usePartition(out of many others) that is very helpful for some problems.  This is to make the lists that you create withPartitionoverlap the each other.  You do this by givingPartitiona 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 usingtestListagain here):

learningmathematica_119.png

learningmathematica_120.png

And here we make it shift by 2 each time

learningmathematica_121.png

learningmathematica_122.png

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

learningmathematica_123.png

learningmathematica_124.png

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 usingPartitionwithout the third argument like the was we did it originally:

learningmathematica_125.png

learningmathematica_126.png

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:

learningmathematica_127.png

learningmathematica_128.png

For more information about Partition, click here: learningmathematica_129.png

Map

One more Mathematica function that is very useful for us is calledMap.

Mapis 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.

Maphas two arguments—very much the way thatSelectdoes, 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 whatMapcan do is to pretend that we have a function—call itemily—that Mathematica does not know about.  So whenever you use it,  Mathematica will just give you back what you wrote.  

learningmathematica_130.png

learningmathematica_131.png

So let's use this to see whatMapdoes.

learningmathematica_132.png

learningmathematica_133.png

SoMapgoes 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 usingPrimeQas the function and usingtestListfrom before:

learningmathematica_134.png

learningmathematica_135.png

So, corresponding to each of the integers from1to1 we see theTrue/Falsevalue that tells us whether that number is a prime.

Here is another example usingMapalong withemilyandPartitio to see how things work. First lets invent another symbol for pairs of numbers

learningmathematica_136.png

learningmathematica_137.png

learningmathematica_138.png

learningmathematica_139.png

So you see thatMapstill wrapsemilyaround the items in the list even though those items are in fact lists themselves.  

For more information about Map, click here: learningmathematica_140.png

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 functionsMaxandMindo this for you.

So, remembertestList?It had the numbers from1to10in it :

learningmathematica_141.png

learningmathematica_142.png

Obviously the maximum number here is10and the minimum one is, well,1.But at least this shows clearly howMaxandMinwork.

learningmathematica_143.png

learningmathematica_144.png

learningmathematica_145.png

learningmathematica_146.png

For more information aboutMax,click here: learningmathematica_147.png

For more information aboutMin,click here: learningmathematica_148.png

Using Modules to help create your own functions.

Now you can useModulesto 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,andPrimeQ 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: learningmathematica_149.png or in the places earlier in this document where they are described.

learningmathematica_150.png

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

Here are the primes between 1950 and 2010:

learningmathematica_151.png

learningmathematica_152.png

So you can figure out whether you were born in a prime year! 

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 calledPartitionthat we talked about earlier. Also, inside of it it uses—as a local functoin inside theModule—the function calledpairDifference that we invented earlier:

learningmathematica_153.png

And here is how it works.

learningmathematica_154.png

learningmathematica_155.png

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....

learningmathematica_156.png

learningmathematica_157.png

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 likeprimeDifferenceDataand end it with a semicolon so it doesn't get printed out:

learningmathematica_158.png

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

learningmathematica_159.png

learningmathematica_160.png

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.

learningmathematica_161.gif

learningmathematica_162.png

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 aModule(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 =.

learningmathematica_163.png

Now we can use it

learningmathematica_164.png

learningmathematica_165.png

Here is an example for the the biggest prime difference that exists between learningmathematica_166.png and learningmathematica_167.png:

learningmathematica_168.png

learningmathematica_169.png

Pretty cool....