Beginner Mistakes Part I

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

(⋯)  parenthesis are for logical grouping and are useful when you are unsure which operations take precedence--they have no operational meaning except for grouping parts of expressions.  When in doubt about operator-precendence, use parenthesis: for example consider a/x+b--use a/(x+b) or (a/x) + b to avoid confusion

Cos(k x)

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

Plot[Sin[x],(x,0, π)]
Table[Sin[x],(x,0,1,.1)]

Sort[(x,y,z)]

Multiplying objects of different types, or not using the intended type of multiplication

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

[⋯]  single brackets are for function operations; double brackets pick out members of a list

SomeList = {a,b,c,d};
SomeList[1]

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

Exp[[1]]

Forgetting Mathematica's convention of capitalization of Functions

Mathematic functions are a mixture of uppercase and lower case letters, the paradigm is that each word in a compound word is captialized, like this: ToBeOrNotToBe

arccos[1]

Arccos[1]

Beginner Mistakes Part II

Forgetting to use patterns in function definitions  (Underscores are Patterns)

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

MyFunction[π,π/2,0]

Forgetting to use delayed evaluation  :=  in function definitions (i.e., with patterns)

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

Plot[myAbsSin[z],{z,-2π,2π},PlotStyle->Thick]

Beginner Mistakes Part II

The difference between assignment = and equality testing ==

Solve[{h= 3 p + 4 q, k = 5p - q},{p,q}]

δ == 24

Not using enough commas

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

e is not e, e is not Exp, Log[Exp[1]] is 1, and Log[e] is just Log[e]

D[e^x,x]
D[Exp[x],x]          (*ok*)
D[E^x,x]                (*ok*)

7. Forgetting that a variable has been defined

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

Where did my result go?

myExpression= Expand[(a+ b + c)^3];
myPlot = Plot3D[Sin[y Sin[x]],{x,0,2π},{y,0,2π}];

MyExpression

myPlot

myFunction[myvar_] := Grid[{{myvar^3,Plot[x^3,{x,-myvar,myvar}]}}]

myFunction[3]

Practical Advice:   Clear Variables

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

Mathematica is Chronological not Spatial: The results do not correspond to the position that they appear on the screen

To see this, evaluate the following example functions.

x= z +y
s = y-x

Corollary:   Separate Mathematica Windows (FrontEnds)  are not independent---they can "Know" about each other.

Practical Advice:   While doing complicated development of code, use a separate Mathematica Window to do small examples and debugging---and then write debugged code (and comments) into a Notebook that you will save.

Defining Expressions as "Forms" can be Misleading and Lead to Unexpected Bugs

mat = {{1,2},{3,4}}//MatrixForm

mat.{x1,x2}

mat = {{1,2},{3,4}};
MatrixForm[mat]

result = mat.{x1,x2}
TableForm[result]

Histogram3D[Table[{RandomReal[],RandomReal[]},{5}]]

Needs["Histograms`"]

Histogram3D[Table[{RandomReal[],RandomReal[]},{5}]]

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

Mathematica Usage Paradigms and Tips

These are subjective and there are many exceptions.  These examples try to illustrate why some usage is better than others

Avoid Defining Symbols for Specific Cases. Instead, Use Rules and Replacements.

Defining length like this, allows rules and replacements to be used for specific cases later

length = length0/Sqrt[1-(v/c)^2]

To show  a concrete example:
Rule-replacement is more useful, extendable,  and powerful

length/.{length0-> 12, v ->  c/3}

Than defining symbols as number and then defining the expression:

length0=12; v = c/3;
length = length0/Sqrt[1-(v/c)^2]

Using rule-replacement allows the construction of general cases simply

gravityArc = { velocity Cos[α] time, velocity  Sin[α] time + accel  time^2/2}

If a specific case is needed, simple rule-replacement  works

gravityArc/.{velocity->1,accel->- 10,α-> Pi/4}

Using rule-replace inside plot

ParametricPlot[gravityArc/.{velocity->1,accel->- 10,α-> Pi/4},{time,0,0.2}]

The power of the symbolic rule-replacement scheme is easy to see when generalized to many parameters

ParametricPlot[Evaluate[Table[gravityArc/.{velocity->1,accel->- 10,α-> f Pi/2}, {f,0,1,1/12}]],{time,0,1},PlotRange-> {{0,.1},{0,0.05}}]

In Mathematica, Everything is an Expression :
Use FullForm to See an Expression.

Something = Every Thing

Fullform allows you to see what Mathematica is using to keep track of your expression

FullForm[Something]

Every valid syntax becomes a new expression, even if it may make no sense to the user.

Everything = ((Graphics3D[Sphere[]])/(Sqrt[EveryThing]))

Treeform is useful if you want to visually pick out parts of expressions

FullForm[Everything]
TreeForm[Everything]
TreeForm[Everything[[2,1]]]

Using Fullform to examine an expression will help you avoid what may seem to be "reasonable approaches"

what = this && that

Here the user wishes to use a rule-replacement to change the && to an ||

what/.{(&&)-> (||)}

Fullform shows how this is to be done.

FullForm[what]

Thus, the following works

what/.And-> Or

Non-Dimensionalize Representations of Physical Quantities.

When trying to non-dimensionalize, FullForm comes in very handy.

dimForce = -k (x -xo)
dimEnergy= k(x-xo)^2/2

Note. the following won't work because there is no x/xo in the fullform.  Below, using x alone on the left-hand-side of a rule does work.

dimForce/.{x/xo-> zeta}

FullForm[dimForce]
FullForm[dimEnergy]

Because "x" is sitting alone, it should be on the left-side of a rule.

nondimRules = {x-> zeta xo, charForce-> k xo, charEnergy-> k xo^2}

nondimForce = Simplify[    ((dimForce/charForce))/.nondimRules  ]

nondimEnergy =  Simplify[    ((dimEnergy/charEnergy))/.nondimRules  ]

Use Evaluate in Plot (Plot is one example of a function that "Holds" is arguments unevaluated until later.)

Not using Evaluate : slow and monochrome.

Plot[Table[LegendreP[i,z],{i,1,11,2}],{z,-1,1},PlotStyle->Thickness[0.01]]

Using Evaluate : Fast and multicolored.

Plot[Evaluate[Table[LegendreP[i,z],{i,1,11,2}]],{z,-1,1},PlotStyle->Thickness[0.01]]

The following won't work as expected, because Plot "holds" onto Integrate without making the integration

Plot[Integrate[Sin[x],x],{x,0, 2 Pi}]

Evaluation forces the Integrate function to do its job

Plot[Evaluate[Integrate[Sin[x],x]],{x,0, 2 Pi}]

Use Longer Variable Names to Avoid Conflicts and Confusion; be careful not to reuse a -defined symbol Mathematica-defined symbol.

absSin[xval_] := Abs[Sin[x]]
myAbsSinPlot[repeats_] := Plot[Sin[2 Pi repeats x],{x,0,1}]
myAbsSinPlot[3]

Localize with Modules

Here, Module will "hide" the temporary assignment to f

blah[ n_] := Module[{f},Table[{f= Integrate[Sin[x]^i,x],f/.x->i Pi} ,{i,1,n}]]

blah[6]

Using f again later causes no dificulties

DSolve[f'[x]==a,f[x],x]

On the other hand (this is generally bad practice), if f is not "hidden." It could lead to subsequent difficulties.

blah[ n_] := Table[{f= Integrate[Sin[x]^i,x],f/.x->i Pi} ,{i,1,n}]

blah[6]

DSolve[f'[x]==a,f[x],x]

Clear[f]

Work Symbolically First and With Exact Values; Then Inexact Numbers or Numerically Last if Necessary

A sequence from of examples working from (what I would consider) naive practice to good practice.  This example analysis a damped and forced linear harmonic oscillator.  There are countless problems in physical sciences that reduce to this problem.  The statement begins with a differential statement of F=ma, and adds a frictional force proportional to the velocity.  The system has an external driving , (Subscript[F, app])(t) (e.g., a child swinging her legs on a swing):

(Subscript[F, app]) =  mass acceleration  + viscosity velocity + spring_constant displacement
(Subscript[F, app]) =  m a + ν v + k  y
(Subscript[F, app])(t) = m (((d^2)y)/(dt^2)) + ν(dy/dt) + k y(t)

In this example, a simple external periodic driving force (Subscript[F, app])(t) = (Subscript[F, o])cos((Subscript[ω, app]) t) is demonstrated.  The frequency, (Subscript[ω, app]), as we will show is a very important predictor of physical behavior.  A particular driving frequency, (Subscript[ω, res])= (Sqrt[k/m]), gives insightful results.

In this example, the behavior at small values of viscosity and its approach to zero are investigated.

DSolve[f'[x]==a,f[x],x]

Naive (solve a specific model with real numbers near the resonant frequency)

In this naive example, a real number is inserted into the differential equation, real coefficients are used, and a numerical viscosity parameter that is "assumed" to behave as if it is practically small

NaiveODEsol = DSolve[{Cos[1.73205 t]==D[y[t],{t,2}]+10^(-6) D[y[t],t]+3.0 y[t],y[0]==0,y'[0]==0},y[t],t]

The solution will be just fin--and  useful if this is as far as one wishes to delve.

ysolNaive = y[t]/.NaiveODEsol

Simplify will show that there are some small imaginary parts that probably arise from numerical imprecision.

Simplify[ysolNaive]

Using Chop to remove small numbers, the results can be plotted and show resonant behavor.

Plot[Chop[ysolNaive],{t,0,10}]

Beginner (use some intermediate steps to define system, solve a specific model with real numbers, remove possible numerical artifacts from limited precision numbers)

A function (Sqrt) is used to produce more accurate "on resonance" conditions, but this will prove to be problematic because of the smallness of the numerical parameter. Numerical coefficients are still used, which is poor practice generally.

The user stores the equation so that it might be changed and used again later for a different case. This is a good idea.

specificODEandBCs= {Cos[Sqrt[3.0] t]==D[y[t],{t,2}]+10^(-12) D[y[t],t]+3.0 y[t],y[0]==0,y'[0]==0}

This will work just fine again.

BeginnerODEsol = DSolve[specificODEandBCs,y[t],t]

ysolBeginner = y[t]/.BeginnerODEsol

The earlier form of ysolBeginner will probably not be used, reassigning that symbol will help keep the notebook organized (i..e, this avoids "symbol inflation")

ysolBeginner =Chop[Simplify[ysolBeginner]]

The solution doesn't appear to show resonant behavior in contradiction with the previous example

Plot[ysolBeginner,{t,0, 30}]

Rookie (combine several steps, use an informed choice for a small parameter)

An informed decision is used for the small paramer, however it is still numerical, exact coefficients are used which may be expected to make solution look much nicer.

mp=$MachinePrecision
specificODEandBCs = {Cos[Sqrt[3] t]==D[y[t],{t,2}]+10^(-2 mp) D[y[t],t]+3 y[t],y[0]==0,y'[0]==0}

Anticipating the form of the solution, the user combines assignment with a rule-replace-with-result technique.  Because mp is numeric, everything is forced to be numeric---and the anticipated nice format of the solution is lost.

ysolRookie=y[t]/.DSolve[specificODEandBCs,y[t],t]

The solution form is suppressed here with the semicolon (which was probably a good idea). But in doing so, without looking a the graphics too carefully, one might miss the fact that the applitudes are above machine precision.

ysolRookie=Chop[Simplify[ysolRookie]];
Plot[ysolRookie,{t,0,20}]

Apprentice (add a symbolic parameter so that limiting behavior can be analyzed more carefully; now all parameters are exact (i.e., there is no numerical imprecision)

The differential equation and its boundary conditions do not have any inexact numbers, just integers and symbols (it would be even better to use only symbols and non-dimensionalize the equation)

ODEandBCs = {Cos[Sqrt[3] t]==D[y[t],{t,2}]+ν D[y[t],t]+3 y[t],y[0]==0,y'[0]==0}

Thus, the solution depends only on a single parameter, ν, which will be investigated near zero

yApprenticesol=Simplify[y[t]/.DSolve[ODEandBCs,y[t],t]]

Evaluated using a rule-replace shows that something resonant is happening.

yApprenticesol/.ν->0

Using Limit shows something nice and physical, in the limit of zero viscosity the amplitude of the resonant solution will grow linearly with time.

limitsol = Limit[yApprenticesol,ν->0]

Plot[limitsol,{t,0,10}]

Good (general equation, introduce physical assumptions, symbolic limits)

Only symbols are used and physics assumptions are encoded as rules. Everything is symbolic and exact; the assumptions are documenting.

dhoAssumptions=m>0&&k>0&&ν≥0&&t>0
GeneralODEandBCs = {Cos[ω t]==m D[y[t],{t,2}]+ν D[y[t],t]+k y[t],y[0]==0,y'[0]==0}

DSolve's  result is wrapped inside a FullSimplify with Assumptions.

ysolGood=FullSimplify[y[t]/.DSolve[GeneralODEandBCs,y[t],t], ,Assumptions->dhoAssumptions]

Zero viscosity is checked by direct evaluation, Simplify leaves an exponential form.

zeroViscosity1=Simplify[ysolGood/.ν->0,Assumptions->dhoAssumptions]

Making the solution uniformly trignometric helps interpretation

zeroViscosity2=Simplify[ExpToTrig[ysolGood/.ν->0],Assumptions->dhoAssumptions]

The limit is checked to see if it matches the value at ν=0

zeroViscosity3=Simplify[ExpToTrig[Limit[ysolGood,ν->0]],Assumptions->dhoAssumptions]

Here direct evaluation is not illustrative of resonant behavior

zeroViscosity2/.ω->Sqrt[k/m]

The limit gives a nice physical interpretation in full symbolic form.

Limit[zeroViscosity2,ω->Sqrt[k/m]]

Instead of looking of the zero viscosity case in the limit of resonance, the user investigates the resonant case in the limit of zero viscosity.

ysolResonant=FullSimplify[ExpToTrig[Limit[ysolGood,ω->Sqrt[k/m]]],Assumptions->dhoAssumptions]

The limit indicates that the solution could be going to ± ∞

viscLimit=Limit[ysolResonant,ν-> 0]

The directed infinity's argument may be zero, a delayed pattern forces the positive case. The user concludes that the solution diverges towards infinity, but the direction it diverges changes rapidly as ν->0.

Simplify[viscLimit/.{{DirectedInfinity[a_]} :> a},Assumptions->dhoAssumptions]

Restrict Patterns in Function Definitions where Appropriate

sinSquared[theArg_] :=Sin[theArg]^2

Plot[{Exp[sinSquared[x]],Exp[sinSquared[Sqrt[-1]x]]},{x,0,2π}]

sinSquared[theArg_Complex] := Re[Sin[theArg]]^2

Plot[{Exp[sinSquared[x]],Exp[sinSquared[Sqrt[-1]x]]},{x,0,2π}]

If a Function Makes Sense only when it Receives Numerical Arguments, Use its Definition to Restrict to Numerical Argments

yofa[a_] := y/.FindRoot[ y^3  +1 == a,{y,a}]

Plot[yofa[z],{z,0,5},PlotLabel->"When is the integral of this equal to one?"]

Poor practice (no restriction on function definitions)

intfunc[b_] := NIntegrate[yofa[z],{z,0,b}]

intfunc can be plotted, but Mathematica will return some warnings like FindRoot::"srect"  and ReplaceAll::"reps"

Plot[intfunc[y],{y,0,4}]

Finding the root will fail.

FindRoot[intfunc[y]==1,{y,10}]

Better practice (restriction on function definitions)

Clear[intfunc];
intfunc[b_?NumericQ] := NIntegrate[yofa[z],{z,0,b}]

No errors in plotting and much faster

Plot[intfunc[y],{y,0,4}]

Numerical root finding works. However, there may be warnings from NIntegrate about numerical resolution.

FindRoot[intfunc[y]==1,{y,10}]

When it matters very much, Check the results of a Symbolic Integration with a Numerical Evaluation

integrand=(R (R-rho Cos[alpha-t]))/(3 ((((R^2)+(rho^2)+(((z-zeta))^2)-2 R rho Cos[alpha-t]))^3))

InputForm[integrand]

assumptions ={R>0,rho>0,Element[zeta,Reals],Element[z,Reals],alpha>0}

Although it is very rare, occasionally the result of symbolic integration can be incorrect. This is such a case. That it is such a case can be demonstrated by looking at specific cases, and numerical evaluation

Integrate[integrand,{t,0,2Pi},Assumptions->assumptions]

specificIntegrand= integrand/.{R-> 1, rho-> 2, alpha-> 1/3, zeta-> 1/4,z-> 1/8}

Integrate[specificIntegrand,{t,0,2 Pi}]

Plot[specificIntegrand,{t,0,2 Pi}]

NIntegrate[specificIntegrand,{t,0,2 Pi}]

Use text fields to separate and annotate notebooks for later use

Text cells (like this one) and a Style Sheet will help you:

Read and Re-Read

Organize

Debug