Legacy Documentation

Mathematica® Teacher's Edition (2002)

This is documentation for an obsolete product.
Current products and services
 Documentation /  Mathematica Teacher's Edition /  The Teacher's Book /  Front Matter /  Tour of Mathematica /

Programming

Here is a simple Mathematica TE program that generates an Hilbert matrix.

Hilbert[n_] := Table[1/(i + j - 1), i, n, j, n]

This generates a circulant matrix. The entries in each row are the entries of the row before shifted right by one place; the last entry is moved to the beginning.

Circulant[v_List] := NestList[RotateRight, v, Length[v] - 1]

This program finds the characteristic polynomial for a matrix. The /; clause at the end checks that m is indeed a matrix.

CharPoly[m_, x_] :=
Det[m - x IdentityMatrix[Length[m]]] /; MatrixQ[m]

Here is a procedural program in Mathematica TE for finding the next prime after a given integer. The pattern n_Integer matches only integers.

NextPrime[n_Integer] :=
Module[k = n, While[!PrimeQ[k], k = k + 1]; k]

You can often avoid using loops in Mathematica TE by operating directly on complete lists. The resulting programs are usually more elegant and more efficient. Here are programs for computing the mean, variance and quantiles of a list.

Mean[list_List] := Apply[Plus, list] / Length[list]

Variance[list_List] := Mean[ (list - Mean[list])^2 ]

Quantile[list_List, q_] :=
Part[ Sort[list], -Floor[-q Length[list]] ] /; 0 < q < 1

This function takes a list of random numbers in the interval from 0 to 1, and forms a succession of cumulative sums, thereby producing a sequence of points in a one-dimensional random walk.

RandomWalk[n_Integer] :=
FoldList[Plus, 0, Table[Random[ ] - 1/2, n]]

Here is an elegant program, written in a functional programming style, which finds the first terms in the continued fraction decomposition of a number .

ContinuedFraction[x_Real, n_Integer] :=
Floor[ NestList [ Function[u, 1/(u - Floor[u])], x, n - 1 ] ]

Mathematica TE programs can create graphics. This program makes polar plots.

PolarPlot[r_, t_, tmin_, tmax_] :=
ParametricPlot[r Cos[t], r Sin[t], t, tmin, tmax,
AspectRatio -> Automatic]

Here is a program that plots the solutions to a polynomial equation as points in the complex plane.

RootPlot[poly_, z_] :=
ListPlot[Re[z], Im[z] /. NSolve[poly == 0, z]] /;
PolynomialQ[poly, z]