Introduction to Mathematica

Activity #0

Exercise 1

Here, you create a list of data (list of pairs) and plot it.  If it' s real data, you might enter the pairs by hand or import the data from a file.  In this exercise, you’ll use the Table function to generate a data set.  I’ve used a parabolic function (y = (x^2) + 3), but you can use any polynomial function.

Smarts=Table[{i,150+i^2},{i,0,5}]

Mathematica outputs the result of each input, unless you tell it not to (by adding a ; after the command). Based on the Output, we see that the Table function worked correctly.  Now, we can plot the data.

ListPlot[Smarts,PlotMarkers->{Automatic,Medium},Joined->True,AxesLabel->{"Time (years)","Student Learning (IQ Points)"}]

Now, let' s use the Fit function to fit our dataset.  The Fit function fits polynomials to the order specified.

MyFit=Fit[Smarts,{1,x,x^2}, x]

Now we can plot the fit.

Plot[MyFit,{x,0,5},PlotStyle->Red]

It' s nice to show the fit and the data together.  Below, I use the Show function and give it the Output labels for the two plots.

Show[Out[2],Out[4]]

Exercise 2

Now, create a new data set, by hand, by creating an array with these pairs : (1.5, -412.35), (2, -419.88), (2.5, -420.09), (3, -419.141), (3.5, -418.199), (4, -417.452), (5, -416.633).  Then, plot the data.

Clear[MyData] (* I use "MyData" a lot, so it's good to be sure it's cleared from computer memory. *)

MyData={{1.5,-412.35},{2,-419.88},{2.5,-420.09},{3,-419.141},{3.5,-418.199},{4,-417.452},{5,-416.633}};

MyDataPlot = ListPlot[MyData,PlotMarkers->{Automatic,Medium}, AxesLabel->{"Separation (Å)","Energy (eV)"}]

The data are the energy versus separation for bringing Na and Cl ions together.  Now, we’ll define a function to fit the energy versus separation.  This total energy function has a constant offset, C, and two terms that depend on the distance, r, between the ions.  The negative term is the attractive Coulomb potential, and the positive term is the repulsive energy due to Pauli Exclusion.  Notice how the function is defined.

TE[A_,B_,C_,r_]:=A (((-9)/r)+(B/(r^7)))+C

Let' s plot the function.

TEP=Plot[TE[220,30,4,r],{r,1.5,5}]

To see if it fits the data, we can plot them together :

Show[TEP,MyDataPlot]

The function does not fit the data.  We can use Mathematica to fit the data, but we need to use the FindFit function since we' ve defined our own model of the data.

FindFit[MyData,TE[a,b,c,x],{a,b,c},x]

Let' s plot the fit results with the data :

Show[ListPlot[MyData,PlotStyle->Red],Plot[TE[a,b,c,x]/. {a->1.8943304194006896`,b->111.69571056420325`,c->-413.3339316427511`},{x,1,7}]]

Not bad!

With the potential energy function, we can calculate the force between the ions and determine the equilibrium spacing.

Force=-D[TE[a,b,c,x]/. {a->1.8943304194006896`,b->111.69571056420325`,c->-413.3339316427511`},x]

NSolve[Force==0,x,Reals]

So the equilibrium spacing between the ions is 2.10 Å.