Introduction to Programming 
with 
Mathematica

By
Richard J. Gaylord 
(gaylord@ux1.cso.uiuc.edu)

Samuel N. Kamin 
(kamin@cs.uiuc.edu)

Paul R. Wellin 
(wellin@sonoma.edu)

Copyright © 1993 by TELOS/Springer-Verlag

Chapter 2 – A Brief Overview of Mathematica

(Mathematica code)

Functions defined in this Notebook...(page no. in book)

harmonic...46
Nharmonic...47
properDivisors...49
perfectQ...49
perfect...50
Mobius band graphic...43
Klein bottle graphic...44

Initialization (evaluate to turn off spell messages)

Off[General::spell]

Off[General::spell1]

Section 2.2  Graphics

Figure 1; page 39

Plot[x + Sin[x], {x, -5Pi, 5Pi}];

Figure 2; page 39

Plot[Sin[1/x], {x, -1, 1}];

Figure 1; page 40

circ = ParametricPlot[{Cos[t], Sin[t]}, {t, 0, 2Pi}];

Figure 2; page 40

Show[circ, AspectRatio->Automatic];

Figure 1; page 41

ParametricPlot[{Cos[19t], Sin[20t]}, {t, 0, 2Pi},
	AspectRatio->Automatic];

Figure 2; page 41

z[x_, y_] := Sin[x]/Cos[y]
Plot3D[z[x, y], {x, -2Pi, 2Pi}, {y, -2Pi, 2Pi}]

Figure; page 42

Plot3D[z[x, y], {x, -2Pi, 2Pi}, {y, -2Pi, 2Pi},
	PlotPoints->50]

Figure 1; page 43

ContourPlot[Sin[x]/Cos[y], 
	{x, -2Pi, 2Pi}, {y, -2Pi, 2Pi}];

Figure 2; page 43

z[x_, y_] := Sin[x]/Cos[y]
DensityPlot[z[x, y], {x, -2Pi, 2Pi}, {y, -2Pi, 2Pi},
	PlotPoints->150, Mesh->False];

Figure: Moebius  band; page 44

x[u_, v_] := (1 + v/2 Cos[u/2]) Cos[u]
y[u_, v_] := (1 + v/2 Cos[u/2]) Sin[u]
z[u_, v_] :=  v/2 Sin[u/2]
ParametricPlot3D[{x[u, v], y[u, v], z[u, v]},
	{u,0,2Pi}, {v,-1,1}];

Figure: Klein bottle; page 45

a = 2;
f = (a + Cos[u/2] Sin[t] - Sin[u/2] Sin[2t]) Cos[u];
g = (a + Cos[u/2] Sin[t] - Sin[u/2] Sin[2t]) Sin[u];
h =      Sin[u/2] Sin[t] + Cos[u/2] Sin[2t];
ParametricPlot3D[{f,g,h}, {t,0,2Pi}, {u,0,2Pi}, 
   Boxed->False, Axes->False, PlotPoints->30];

Section 2.4  Representation of data

Figure 1; page 46

data = {{.061,6.95},{.403,28.189},{.622,41.1},{2.51,120.8},
{2.96, 147.9},{3.33, 182.8},{8.2,368.8},{28.2,981.3},
{57.4,1303.3},{72.3,1512.5},{340.2,7100.3},{711,10101.1},
{5000.,29895.}};

data >> dataset.m

ListPlot[data]

Figure 2; page 46

<<Graphics`Graphics`

LogLogListPlot[data]

loglogdata = Log[<<dataset.m]

Fit[loglogdata,{1,x},x]

Section 2.5  Programs

2.5.1 User-defined functions

harmonic[n_] := Sum[1/k, {k,1,n}]

harmonic[2]

{harmonic[10], N[harmonic[10]]}

(* Remove comments to evaluate *)
N[harmonic[10^4]]  (* Should take "forever" *)

Nharmonic[n_] := NSum[1/k, {k,1,n}]

(* 
{Nharmonic[10^6], Nharmonic[10^9], Nharmonic[10^12]}
*)

(* Nharmonic[10^9] - N[Log[10^9]] *)

(* N[EulerGamma] - (Nharmonic[10^9] - N[Log[10^9]]) *)

Needs["Algebra`SymbolicSum`"]

harmonic[Infinity]

Sum[i, {i, 1, n}]

Sum[i^2, {i, 1, n}]

2.5.3  Programming

properDivisors[n_] := Drop[Divisors[n],-1]

properDivisors[6]

perfectQ[n_Integer] := Apply[Plus,properDivisors[n]] == n

perfectQ[6]

perfectQ[16]

perfect[n_] := Select[Range[n], perfectQ]

(* Remove comments to evaluate: will take some time *)
(* perfect[10000] *)