Chapter 1
Preliminaries

from
Introduction to Programming with Mathematica,
2nd Ed.

by
Richard J. Gaylord
Samuel N. Kamin
Paul R. Wellin

Copyright 1995 TELOS/Springer-Verlag

Initialization (evaluate to turn off spell messages)

Off[General::spell]

Off[General::spell1]

1.1  Introduction

Sin[.86] - Log[1.23](1 + .08/12)^12

rent = 350

food = 175

heat = 83

rent + food + heat

Factor[x^2 - 1]

Solve[x^3 - 2x + 1 == 0, x]

Integrate[x^2.5 - 5.0911x, {x, 0, 20}]

Integrate[1/(1 - x^3), x]

Plot[Sin[x + Sqrt[2] Sin[x^2]], {x, -Pi, Pi}]

2^64

%

Out[1]

%6

BowlingScore[pins_] := Module[{score},
    score[{x_, y_, z_}] := x + y + z;
    score[{10, y_, z_, r___}] := 10+y+z+score[{y, z, r}];
    score[{x_, y_, z_, r___}] := x+y+z+score[{z, r}] /;
                                 x + y == 10;
    score[{x_, y_, r___}] := x+y+score[{r}] /; x+y < 10;
    score[If[pins[[-2]] + pins[[-1]] >= 10, pins,
            Append[pins, 0]]]]

BowlingScore[{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}]

1.2  Using Mathematica

1.2.1  Getting Into and Out of Mathematica

1.2.2  Getting Help

?ParametricPlot

?Int*

1.2.3  The Syntax of Inputs

39/13

2^5

2 5

2*5

Factor[x^5 - 1]

Conjugate[3 + 4 I]

Plot[Sin[x + Sqrt[2] Sin[x]], {x, -2Pi, 2Pi}]

Integrate[Cos[x], {x, a, b}]

x = Range[10000];

Apply[Plus, x]

% / 10000

3 *

4

3

*4

(3
 *4)

Clear[x]

D[Sin[x],        (* differentiate Sin[x]   *) 
       {x, 1}]   (* with respect to x once *)

x^5 - 1 //Factor

1.2.4  Errors

Sine[1.5]

Off[General::spell, General::spell1]

Sine[1.5]

BowlingScore[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

Log[2, 16, 3]

FactorInteger[12.5]

FindRoot[x - Sin[x], {x, 0.2}]

1.3  The Mathematica Language

1.3.1  Internal Forms of Expressions

{Head[7], Head[1/7], Head[7.0], Head[7 + 2 I]}

Head[a + b]

Head[{1, 2, 3, 4, 5}]

FullForm[a + b]

FullForm[{1, 2, 3, 4, 5}]

Plus[1, 2, 3, 4, 5]

FullForm[a x^2 + b x + c]

1.3.2  Predicates and Boolean Operations

PrimeQ[144]

PrimeQ[2^31 - 1]

OddQ[21]

EvenQ[21]

IntegerQ[5/9]

Relational and Logical Operators

7 < 5

Equal[3, 7 - 4, 6/2]

x^2 - 1 == (x^4 -1) / (x^2 + 1) //Simplify

4 < 5 && 8 > 1

TableForm[
   {{True&&True, True&&False}, {False&&True, False&&False}},
   TableHeadings -> {{T, F}, {T, F}}]

TableForm[Outer[And, {True,False},{True,False}],
	TableHeadings -> {{T, F}, {T, F}}]

4 == 3 || 3 == 6/2

0 == 0 || 3 == 6/2

True || True

Xor[True, True]

Xor[True, False]

1.3.3  Evaluation of Expressions

Trace[3 * (4 + 5)]

TracePrint[3 * (4 + 5)]

Timing

Timing[ FactorInteger[1000!]; ]

Timing[ BernoulliB[200] ]

Timing[ BernoulliB[200] ]

timings = Table[Timing[FactorInteger[(100j)!]][[1]],
               {j, 1, 15}]

ListPlot[timings/Second, PlotStyle -> PointSize[.02]]

1.3.4  Attributes

Attributes[Plus]

Plus[(a + b) + c]

s + u + p + e + r + b

x^3 + x^5 + x^4 + x^2 + 1 + x

x^3 y^2 + y^7 x^5 + y x^4 + y^9 x^2 + 1 + x

FullForm[Plus[Plus[a + b]]]

1.4  The Mathematica Interface