Accuracy, Representation, and Precision
W. Craig Carter MIT IAP 2006
http://pruffle.mit.edu/

One advantage (and also one thing that causes confusion) in a symbolic program like Mathematica is its ability to to exact calculations:

cosPiOver6  = Cos[(π/6)]

sinPiOver6  = Sin[(π/6)]

ExactlyOne  =  (Sqrt[(sinPiOver6^2)   +  (cosPiOver6^2)])

contrast this with:

NumericalPi  =  N[π, 80]

NcosPiOver6  = Cos[(NumericalPi/6)]

NsinPiOver6  = Sin[(NumericalPi/6)]

NumericalOne =   (Sqrt[(NsinPiOver6^2)   +  (NcosPiOver6^2)])

General Practical Advice:

		Name the expressions that you might use again;
		Use longish names that self-document the expression

Mathematica variables have different types---and the behavior of a Mathematica function can depend on the type of variable it acts on (polymorphism)

?? Head

Mathematica will check the "head" of an expression when considering how to act upon that expression, here are some example Heads

Head[f[x]]

Head[Sin[x]]

Head[ExactlyOne]

Head[NumericalOne]

Head[NumericalTwo]

Head[π]

Head[NumericalOne*ExactlyOne]

Head[(ExactlyOne/3)]

Head[(ExactlyOne/π)]

FullForm[(ExactlyOne/3)]

FullForm[(ExactlyOne/Pi)]

Head[ I]

Head[NumericalTwo I]

Perhaps this doesn't seem so important now, but....

-6.02 (10^(23 ))  +  2.0  -  1.0  +  
      6.02 (10^(23 ))

-6.02 (10^(23 ))  +  2.0  +  
      6.02 (10^(23 )) -  1.0

Let's jump ahead to some things that haven't been covered yet and see what all the different permutations would give:

\(For[
      i = 1, 
i\  <= \ 
        Length[PermTable\  = \ 
            Permutations[{\(-6.02\)\ 10\^\(\(23\)\(\ \)\), \ 2.0, \ 
                6.02\ 10\^\(\(23\)\(\ \)\), \ \(-1.0\)}]], 
Print["(", PermTable[\([i, 1]\)], ")    +    (", 
        PermTable[\([i, 2]\)], ")    +    (", 
        PermTable[\([i, 3]\)], ")    +    (", 
        PermTable[\([i, 4]\)], ")    =    ", 
Apply[
          Plus, PermTable[\([\(i++\)]\)]]]]\)

General Practical advice:
	
		Hold off making things numerical until the very end----if ever.  In other words, an 		answer like:

mass  =  
        (restmass/(Sqrt[1  - (( (v^2))/(c^2))]));

    
KineticEnergy = (( mass (v^2))/2);

    
EnergyExpansion  =  Series[KineticEnergy, {v, 0, 2}]

When does something get evaluated?

Head[Sin[x]]

Head[Sin[(Pi/2)]]

Head[Unevaluated[Sin[(Pi/2)]]]

Deciding WHEN something should be evaluated is  extremely important when defining functions

The Importance of Evaluation and Functions

a  =  Sqrt[x]

x  =  Sqrt[y]

a

f[z]  =  (z^2)

f[z]

f[2]

\(Think\ about\ what\ a\ function, \ 
    f \((x)\)\  = \ 
      x\^2\ does . \ \ The\ variable\ x\ is\ a\ placeholder\ for\ something\ that\ f\ operates\ on, \ \ x\ is\ not\ really\ \(important : \ 
        it\ is\ just\ a\ "handle."\)\)

Patterns

Mathematica's underscore plays the role of x in f(x)

first, a kind of weird example showing how patterns work

LongExpression  =  Expand[(a  +  b  +  c)^5]

LongExpression /. (_ -> Thing)

We need a way of "naming" the expression for later use...

LongExpression /. t_^4 -> FP[t]

The usual use of the underscore is in the definition of function:

h[z_]  = Sin[ArcCos[z]]

h[0.2]

Plot[h[x], {x, 0, 1}]

Holding off on Evaluation ------> The difference between = and :=

g[x_]  =  Log[Exp[(x^2)]]

Plot[g[x], {x, 0, 1}]

g[5/4]

r[x_]  :=  Log[Exp[x^2]]

r[z]

Plot[r[s], {s, 0, 3}]

Observation and Practical Advice

When defining a function you (almost always) use :=

Defining and Using Functions

The cannonical example: factorial

28!

0!

28.5!

(-5)!

ListPlot[Table[Log[n!], {n, 10, 30, 0.25}]]

Roll our own... an example with mistakes...

fact1[n_]  :=  n*fact1[n - 1]

fact1[3111]

fact1[112]

fact2[0]  =  1;
fact2[n_]  :=  n*fact2[n - 1]

fact2[123]

Your Turn to Try:

The Fibonacci sequence is defined by
   
    (Subscript[F, 1 ])= (Subscript[F, 2]) = 1
    			and
    (Subscript[F, m ])= (Subscript[F, m - 1])  +  (Subscript[F, m-2 ])
    
1. Write a function that calculates (Subscript[F, m ])

2. Look up Mathematica's Table functions; create a list of Logs of the first 10, 20, and 30 Fibonacci numbers.

3. Look up Mathematica's ListPlot function; Plot Log[(Subscript[F, m ])] versus m.

Making functions smarter, 
	or making functions more smartly,
		     or making smart functions....

Our example of factorial was not very smart (and perhaps your Fibonacci example wasn't very smart either...)
	fact2[n_] := n*fact2[n-1]
When the factorial of 24 was asked for, it implicitly calculates 23! and then multiplies by 24---even if 23! was calculated a few moments before.

In this case, it would be better to "remember" fact2[23] instead of calculating it:

fact3[0]  =  1;
fact3[n_]  :=     fact3[n]  = 
        n*fact3[n - 1]

?Timing

Timing[fact3[3000]]

$RecursionLimit  =  2^12

Clear[fact2]
fact2[0]  =  1;
fact2[n_]  :=  n*fact2[n - 1]

Timing[fact2[3000];]

Timing[fact2[3000];]

Timing[fact3[3000];]

Timing[fact3[4000];]

Timing[fact2[4000];]

fib2[1]  =  fib2[2]  =  1;
fib2[
        n_]  :=  (fib2[n]  =  
          fib2[n - 2]  +  fib2[n - 1])

ListPlot[
      Table[Timing[fib2[i];][[1, 1]], {i, 1, 40}]]

fib1[1]  =  fib1[2]  =  1;
fib1[n_]  :=   fib1[n - 2]  +  fib1[n - 1]

ListPlot[
      Table[Timing[fib1[i];][[1, 1]], {i, 1, 30}]]

Our functions are still not very smart...

$RecursionLimit  =  256

fact3[π]

Pattern restrictions

Name interference and how to go back to scratch: Use Clear
Practical advice, using the quotes allows use of wildcards...

Clear["fact*"];

fact[0]  =  1;
fact[n_Integer]  :=  fact[n]  =  n fact[n - 1]

fact[3]

fact[-π]

fact[-2]

Clear["fact*"]

    
fact[0]  =  1;
fact[n_Integer?Positive]  :=  fact[n]  =  
        n fact[n - 1]

\(Functions\ with\ multiple\ arguments\ are\ simple\ extensions\ of\ the\ single\ argument\ \(case : 

ColoumbEnergy[q1_, q2_, x1_, y1_, z1_, 
            x2_, y2_, z2_]\)\):=((
q1 q2)/((((x1 - 
                      x2))^2) +(((y1 - 
                      y2))^2) +(((z1 - z2))^2) ))

Your Turn to Try:

Generalize the Fibonacci sequence F[2] to F[n] where each term sums up to
  
  (Subscript[F, m≤0 ])[
        n] = 0 
  (Subscript[F, 1 ])[n] = 1
  (Subscript[F, 2 ])[n] = 1
  (Subscript[F, 3 ])[n] = (Subscript[F, 2 ])+ (Subscript[F, 1 ])
  (Subscript[F, 4 ])[n]= (Subscript[F, 3   ])+ ⋯ + (Subscript[F, 4-n ])
  ⋮
  (Subscript[F, m ])[n]= (Subscript[F, m-1   ])  +  ⋯  +  (Subscript[F, m-n ])
   
    
1. Write a function that calculates (Subscript[F, m ])[n]

2. Look up ListPlot3D; Plot Log[(Subscript[F, m ])[n]] versus n and m

Simplifying Symbolic Expressions

Polynomials

UglyExpression  =  
-243*
          E^(9*y)*α^5 + 6561*E^(8*y)*x*α^5 - 
        78732*E^(7*y)*x^2*α^5 + 
        551124*E^(6*y)*x^3*α^5 - 
        2480058*E^(5*y)*x^4*α^5 + 
        7440174*E^(4*y)*x^5*α^5 - 
        14880348*E^(3*y)*x^6*α^5 + 
        19131876*E^(2*y)*x^7*α^5 - 14348907*E^y*x^8*α^5 + 
        4782969*x^9*α^5 + 
        405*E^(9*y)*α^4*β*Cos[θ] - 
        10935*E^(8*y)*x*α^4*β*Cos[θ] + 
        131220*E^(7*y)*x^2*α^4*β*Cos[θ] - 
        918540*E^(6*y)*x^3*α^4*β*Cos[θ] + 
        4133430*E^(5*y)*x^4*α^4*β*Cos[θ] - 
        12400290*E^(4*y)*x^5*α^4*β*Cos[θ] + 
        24800580*E^(3*y)*x^6*α^4*β*Cos[θ] - 
        31886460*E^(2*y)*x^7*α^4*β*Cos[θ] + 
        23914845*E^y*x^8*α^4*β*Cos[θ] - 
        7971615*x^9*α^4*β*Cos[θ] - 
        270*E^(9*y)*α^3*β^2*Cos[θ]^2 + 
        7290*E^(8*y)*x*α^3*β^2*Cos[θ]^2 - 
        87480*E^(7*y)*x^2*α^3*β^2*Cos[θ]^2 + 
        612360*E^(6*y)*x^3*α^3*β^2*Cos[θ]^2 - 
        2755620*E^(5*y)*x^4*α^3*β^2*Cos[θ]^2 + 
        8266860*E^(4*y)*x^5*α^3*β^2*Cos[θ]^2 - 
        16533720*E^(3*y)*x^6*α^3*β^2*Cos[θ]^2 + 
        21257640*E^(2*y)*x^7*α^3*β^2*Cos[θ]^2 - 
        15943230*E^y*x^8*α^3*β^2*Cos[θ]^2 + 
        5314410*x^9*α^3*β^2*Cos[θ]^2 + 
        90*E^(9*y)*α^2*β^3*Cos[θ]^3 - 
        2430*E^(8*y)*x*α^2*β^3*Cos[θ]^3 + 
        29160*E^(7*y)*x^2*α^2*β^3*Cos[θ]^3 - 
        204120*E^(6*y)*x^3*α^2*β^3*Cos[θ]^3 + 
        918540*E^(5*y)*x^4*α^2*β^3*Cos[θ]^3 - 
        2755620*E^(4*y)*x^5*α^2*β^3*Cos[θ]^3 + 
        5511240*E^(3*y)*x^6*α^2*β^3*Cos[θ]^3 - 
        7085880*E^(2*y)*x^7*α^2*β^3*Cos[θ]^3 + 
        5314410*E^y*x^8*α^2*β^3*Cos[θ]^3 - 
        1771470*x^9*α^2*β^3*Cos[θ]^3 - 
        15*E^(9*y)*α*β^4*Cos[θ]^4 + 
        405*E^(8*y)*x*α*β^4*Cos[θ]^4 - 
        4860*E^(7*y)*x^2*α*β^4*Cos[θ]^4 + 
        34020*E^(6*y)*x^3*α*β^4*Cos[θ]^4 - 
        153090*E^(5*y)*x^4*α*β^4*Cos[θ]^4 + 
        459270*E^(4*y)*x^5*α*β^4*Cos[θ]^4 - 
        918540*E^(3*y)*x^6*α*β^4*Cos[θ]^4 + 
        1180980*E^(2*y)*x^7*α*β^4*Cos[θ]^4 - 
        885735*E^y*x^8*α*β^4*Cos[θ]^4 + 
        295245*x^9*α*β^4*Cos[θ]^4 + 
        E^(9*y)*β^5*Cos[θ]^5 - 
        27*E^(8*y)*x*β^5*Cos[θ]^5 + 
        324*E^(7*y)*x^2*β^5*Cos[θ]^5 - 
        2268*E^(6*y)*x^3*β^5*Cos[θ]^5 + 
        10206*E^(5*y)*x^4*β^5*Cos[θ]^5 - 
        30618*E^(4*y)*x^5*β^5*Cos[θ]^5 + 
        61236*E^(3*y)*x^6*β^5*Cos[θ]^5 - 
        78732*E^(2*y)*x^7*β^5*Cos[θ]^5 + 
        59049*E^y*x^8*β^5*Cos[θ]^5 - 
        19683*x^9*β^5*Cos[θ]^5

Simplify[UglyExpression]

Factor[UglyExpression]

Collect[UglyExpression, (E^y)]

Map[Factor, Collect[UglyExpression, (E^y)], 2]

NewUglyExpression  =  
      UglyExpression /.  {(E^( y)) ->  
            z,  (E^(n_Integer y)) ->  z^n}

Factor[NewUglyExpression]

Combinations of Rational Expressions

UglyExpression  =  ((1 - x  -  y)/(x  +  y  +  z))  - (( x  +  y)/(x  -  y  -  z))

Simplify[UglyExpression]

Factor[UglyExpression]

Together[ UglyExpression]

Simplify[Together[UglyExpression]]

Powers and Roots

UglyExpression =  (Sqrt[Expand])[(((x + y  +  z))^2)]

Simplify[UglyExpression]

Factor[UglyExpression]

Simplify[UglyExpression,  
      Assumptions ->  {x  ∈  Reals,  y  ∈  Reals, 
          z  ∈  Reals}]

PowerExpand[UglyExpression]

PowerExpand[Simplify[UglyExpression]]

Trignometric functions

UglyExpression  =  -4 Cos[β]^4 Cos[β - θ] (Cos[β - θ] - 
            Sin[β - θ]) Sin[β - θ] (Cos[β - θ] + Sin[β - θ])

Simplify[UglyExpression]

TrigReduce[UglyExpression]

TrigFactor[UglyExpression]

TrigExpand[UglyExpression]

List of Typical Beginners' Mistakes

1. Forgetting to put spaces between variables
	Examples:

x =  (3/2);

    
k  =  π;


Sin[kx]

It is good practice to use the * or extra spaces

Sin[k   x]

Sin[k*x]

2. Forgetting or not understanding the differences between (⋯) {⋯} [⋯]

(⋯)  parenthesis are for logical grouping and are useful when you are unsure which operations take precedence
		Common Mistakes:

Cos (k x)

Plot[Sin[x], (x, 0,  π)]

Sort[(x, y, z)]

{⋯}  curlies are for lists, iterators, and variable bounds
		Common Mistakes:

{((Sqrt[2])/2)} {a, b, c}

[⋯]  single brackets are for lists, iterators, and variable bounds
		Common Mistakes:

SomeList  =  {a, b, c, d};

    
SomeList[1]

[((z^2)  +  (y^2)) c  +  b (y^3)] a

[[⋯]]  double brackets are for lists, iterators, and variable bounds
		Common Mistakes:

Exp[[1]]

3. Forgetting Mathematica's convention of capitalization of Functions

Common mistakes:

arccos[1]

Arccos[1]

ArcCos[1]

4. Forgetting to use patterns in function definitions

Common mistakes:

MyFunction[x, y, z]  :=  Sin[x] Sin[y] Sin[z]

MyFunction[π, π/2, 0]

5. Forgetting to delayed evaluation, :=, in function definitions when the placeholders have been previously defined.

Common mistakes:

x =  π/2;
AbsSin[x_]  =  Abs[Sin[Abs[x]]]

Plot[AbsSin[z], {z, -2 π, 2  π}]

6. The difference between assignment = and equality testing ==

Common mistakes:

Solve[{β =  3 p  +  4 q,  α  =  5  p  -  q}, {p, 
        q}]

δ  ==  24

7. Not using enough commas

Common mistakes:

Plot[Sin[x  +  Exp[-x]] {x, 0, Pi}]

8. Forgetting that a variable has been defined

Common mistakes:

A  =  (E^(((-1.2)/(k 373))))

ContourPlot3D[
      Cos[Sqrt[x^2 + y^2 + z^2]], {x, -2, 2}, {y, 0, 2}, {z, -2, 
        2}]

<< Graphics`ContourPlot3D`

ContourPlot3D[
      Cos[Sqrt[x^2 + y^2 + z^2]], {x, -2, 2}, {y, 0, 2}, {z, -2, 
        2}]

Practical Advice:
		Clear Variables

Clear[k];
A  =  (E^(((-1.2)/(k 373))))

Second to last resort, 
		clear everything

Clear["Global`*"];

<< Graphics`ContourPlot3D`;
ContourPlot3D[
      Cos[Sqrt[x^2 + y^2 + z^2]], {x, -2, 2}, {y, 0, 2}, {z, -2, 
        2}]

ContourPlot3D[
      Cos[Sqrt[x^2 + y^2 + z^2]], {x, -2, 2}, {y, 0, 2}, {z, -2, 
        2}]

Last resort, 
		kill the kernel and restart it
			Use menu: kernel

9. Using formatting commands in assignments

Common mistakes:

mymat  =  {
                 {1, 
            3, 7}, 
                 {3, 
            2, 4}, 
                {7,  
            4 ,  3}
               } // 
        MatrixForm

Eigenvalues[mymat]

Practical advice, define and display with separate commands

mymat  =  {
                {1, 
            3, 7}, 
                 {3, 
            2, 4}, 
                {7,  
            4 ,  3}
               };
mymat // MatrixForm

Eigenvalues[mymat] // N

10. Forgetting that some functions, like Plot, don't automatically evaluate their arguments.  Therefore, implicitly defined values may not be "known."

Common mistakes:

Plot[Table[LegendreP[i, z], {i, 1, 11, 2}], {z, -1, 1}]

Practical advice:
			Use Evaluate in Plot when in doubt

Plot[
      Evaluate[Table[LegendreP[i, z], {i, 1, 11, 2}]], {z, -1, 
        1}]

11. Useful functions that you should learn soon

N

?N

N[((1  + (Sqrt[ 5]))/2)]

ContinuedFraction[N[((1  + (Sqrt[ 5]))/2), 12]]

Chop

?Chop

Exp[N[2 π I]]

Chop[Exp[N[2 π I]]]

Solve, NSolve, FindRoot

Solve

?Solve

Solve[x^3  +  1  == x, x]

Solve[{a x^2  +  b y == c,  a x  +  y ==  d}, {x, 
        y}]

Solve[x^7  +  x  ==  1, x]

NSolve

?NSolve

NSolve[x^7  +  x  ==  1, x]

NSolve[Sin[x]  ==  Exp[x], x]

FindRoot

FindRoot[Sin[x]  ==  Exp[x], {x, 1/2}]

Series

?Series

Something  =  LegendreP[n + 1, Sin[x]]/LegendreP[n, (Sqrt[x])]

smallxbehavior  = Series[Something, {x, 0, 1}]

Short[smallxbehavior, 6]

Your Turn:
    
    A famous---and not very efficient---way to calculate the value of π is with the infinite product:
 π= (2/((∏_(i = 1)^∞) (Subscript[R, i])))   
    
    where
   
    (Subscript[R, 1= ])(1/2)(Sqrt[2 ])
    (Subscript[R, 2= ])(1/2)(Sqrt[2 + (Sqrt[2])])
    (Subscript[R, 3 = ])(1/2)(Sqrt[2 + (Sqrt[2 + (Sqrt[2])])])
    ⋮
    Use this to calculate π and visualize the convergence