74 Pi: Mathematica Tips and Traps (74.html)
(Our thanks to the author: Stephen Wong)
NOTE: The information exists in this webpage, but the underlined Web Links in the outline (immediately below) are not clickable.
-
A Defensive Move
-
Manipulating Input
Regions
-
Defining Variables
-
Integers
and Decimals are Not the same!
-
Defining Functions
-
Single Line Functions
-
Multiple Line Functions
-
Compiled Functions
-
Defining Arrays
-
One dimensional
Arrays/Lists
-
Multidimensional
Arrays/Lists
-
Generating Array/Lists
-
Using Conditionals
-
Defining Equations
-
Graphics
-
Plotting Functions
-
Plotting Data Points
-
Surface Plots
-
Plotting Options
-
Using Rules
-
Turning
Expressions into Functions
-
Execution Speed
-
Submit your own!
-
Related References!
The US$35 Raspberry Pi 2 B (4 core 1GB) computer runs the free Raspberry Pi (Linux) OS (formerly Raspbian)
which . . .
includes mathematica (i.e. m)
(and Wolfram) etc. A later model of this computer was
announced in Feb 2015. To be fully operational, just add a
$10 5V power supply, a $15 Micro SD memory card, keyboard,
mouse and access to an HDMI TV. Then boot into m or
connect to the Internet. As of 2023 the Raspberry Pi Model 4,
Pi-400 and Compute modules also exist. Source 04 lists
many tips and tricks for coding in Mathematica.
|
Raspberry Pi (bigger? click)
|
A
Defensive Move
Mathematica always remembers everything that it has previously done
in a session, including the most recent values of variables. This is useful if you
want to repeat a previous calculation using new values for the variables,
but can cause major problems if you try to execute a notebook from the
start and don't want the new values. Here is a way of making Mathematica
"forget" everything you told it:
Always put this line as the first line in your notebook. Mathematica
will complain the first time you run the notebook because it will say that
it doesn't know anything to forget-just ignore it. Subsequent executions
of the notebook in future sessions will not produce an error message and Mathematica
will "forget" everything that was done thus far (technically, it will remove
them from the system). This will enable you to restart a calculation with
a clean slate.
Note: It is good practice to re-execute the notebook from the start
periodically. The reason is that often while trying to get Mathematica
code to run correctly, the values of variables get changed without the
programmer realizing it. With incorrect values stored, the algorithms may
be correct but still produce erroneous results ("garbage in -garbage out").
Re-executing the notebook from the beginning will insure that the variables
are set correctly. [Deprecated note from Stephen Wong: This is also how
the graders and I will execute notebooks
and judge their outputs-so always do a final execution of the whole notebook
before turning anything in (make sure you have the above line installed!) ].
Go back to the Main Menu
Manipulating
Input Regions
The vertical brackets on the side of the display indicate input and
output regions. By clicking and highlighting a bracket, the entire region
enclosed by it can be manipulated. The type of things that can be done
include:
-
Changing the format style from input to/from text. A text region is very
useful for adding comments or to temporarily disabling some code and prevent
it from executing ("commenting out").
-
Copy, cut or delete a region (accessible via a right-button click). Note
that just deleting the input region will not automatically delete the output
region. To delete both at once, be sure to highlight the bracket that encloses
both.
-
Paste a region in between two regions. After cutting or copying a region,
place the cursor between two regions. The cursor will become a horizontal
bar. Right click and select "Paste".
-
To suppress an output from a line, put a semicolon (;) at the end of the
line. This helps keep the screen from getting cluttered up with output
you already know is OK.
-
You may place more than one line of code in a region, but they will be
executed as a unit. To execute a single line of code, put it on its own
line. "Shift+Enter" will execute the line the cursor is on.
Go back to the Main Menu
Defining Variables
There are two ways to assign a value (numeric or symbolic) to a variable
in Mathematica:
-
x = a This assigns the present value of a to x. If
the value of a changes later, the value of x is unaffected.
As this method will greatly speed up calculations, it is the preferable
method to use, as long as the value of a is completely determined
at the time of the assignment to x.
-
x := a This is a " delayed" assignment. This means that the value
of a will not be given to x until x is used.
This essentially establishes a relationship between the variables
a and x. If the value of a changes later on, then
the value of x will also change. This is much slower computationally
than the other assignment method, so use it only in situations where you
are trying to establish a generic relationship and not a transfer of values.
Try rearranging the order in which variables are calculated to eliminate
":=" type assignments and reduce execution times.
DO NOT CONFUSE AN ASSIGNMENT WITH THE CREATION OF AN EQUATION! THESE
ARE TWO VERY DIFFERENT THINGS IN MATHEMATICA!
Go back to the Main Menu
Integers
and Decimals are Not the same!
Mathematica treats integers and decimals (values with a decimal point
somewhere) differently. This is because integers are exact numbers and
can be treated as such by the symbolic math processor. Operations such
as Sqrt, etc are left unevaluated for integers because they have exact
values. These unevaluated expressions are considered to be algebraic expressions
by Mathematica and may have unexpected side effects on some operations,
such as boolean operations for conditionals, which are comparing expressions.
Decimal inputs, however, are evaluated to approximate decimal values. To
force Mathematica to evaluate integer values when execution speed is more
important than alegraic accuracy, or numerical results are needed, use
the N[] command.
For instance, compare:
[In 1] Sqrt[3]
[Out 1] Sqrt[3]
[In 2] Sqrt[3.0]
[Out 2] 1.73205
[In 3] N[Sqrt[3]]
[Out 3] 1.73205
Go back to the Main Menu
Defining Functions
Single Line Functions
A function can be defined by using the following form:
f[x_] := an expression involving x (no underbar)
Example:
Note that the rules for using "=" vs. ":=" apply here as well. That is,
the above function will utilize the values of a and k (not
x, since it is defined as being the variable input) at the time
that f[x] is defined. If a and k are changed later, f[x]
will not be affected. However, if ":=" had been used, the values of a
and k used will be those at the time f[x] is executed. That
is, if a and k are changed later, f[x] will also change.
If you use "=" and a and k do not have values yet,
the results of f[x] are not predictible if a and k are later
assigned values. Be sure that ALL your external variables have values BEFORE
f[x] is declared if you use "="!
To use this function put anything you want in as the input:
In general, I find that things tend to work better when I use ":=" rather
than "=" for functions. For instance, this sequence is problematic:
[In] x = 5
[Out] 5
[In] f[x_] = 3*x
[Out] 15
[In] f[2]
[Out] 15
Notice how f[x_] used the existing value of x (= 5) and thus f[2] gives
an incorrect result. The following code works better using the ":=" in
the function declaration:
[In] x = 5
[Out] 5
[In] f[x_] := 3*x
[Out]
[In] f[2]
[Out] 6
Tip: Avoid the use of external variables inside of functions. Instead,
create a function with more than one input variable:
Go back to the Main Menu
Multiple Line
Functions
If you need more than one line to define a function, put the expression
inside of a "Module" (I've also shown how to make a function of more than
one input variable):
f[time_, dfinal_, vfinal_] = Module[ {acc,v0, eq1, eq2,result},
|
|
eq1 := vfinal== (1/2)*acc*time + v0;
|
|
eq2 := dfinal == acc*time^2 + v0*time;
|
|
result = {acc,v0} /.Solve[{eq1,eq2},{acc, v0}];
|
|
|
|
|
|
Numbered notes from above:
-
These declare "local" variables that are only needed inside the function.
Inside the function, local variables will always take precedence over any
"global" variables with the same name. Local variables do not appear outside
the function.
-
Note the indentation. This is good programming practice and helps to visually
separate the body of the function from its definition.
-
The output of the function is the last line. Note the lack of the semicolon.
You will get no output with a semicolon here.
-
Note that this square brace is directly under its matching brace. This
helps identify matching braces.
Go back to the Main Menu
Compiled
Functions
To create a function that is compiled for extra speed, use this format:
f = Compile[ {x,y,z}, Module[
--body of the module --
]]
Above, "f" is the name of the function, and x, y, and z are the input
parameters to the function. the Module is the same as would appear in any
multi-line function. For a single line function, the Module expression
can be replaced with a single line expression as in an ordinary function.
To specify a particular type of input parameter, use a numerical type
identifier as such:
g= Compile [{{a, _Real}, {b, _Complex}}, Module [ etc....
If a function calls another function, compiling it does not always generate
much increase in execution speed. Compiling a function seems to be the
most effective when the function is totally self-contained.
Go back to the Main Menu
Defining
Arrays
One
dimensional Arrays/Lists
Arrays are referred to as "lists" in Mathematica. A list can be declared
as such:
The elements of zlist can be accessed individually using double square
brackets:
zelement = zlist[[2]]
zlist[[3]] = aNewElement
Note how double square brackets are used to identify array elements, as
opposed to the single square brackets used to identify the inputs to functions.
Go back to the Main Menu
Multidimensional
Arrays/Lists
A list can be made of lists. Here is a 2-dimensional array with 3 rows
and 4 columns:.
z2D = {{a,b,c,d},{e, f, g, h},{i, j, k, l}};
The rows can be accessed as a single entity:
z2D[[2]]
returns the list {e, f, g, h}.
The trick is to remember that the element in the i'th row and j'th column
in an array is really the j'th element in the i'th row of the array. Thus
we do this to get z2D23:
Go back to the Main Menu
Generating
Array/Lists
Go back to the Main Menu
Using
Conditionals
Mathematica is capable of perfoming conditional branching, where one
set of instructions is executed when a certain condition is true and another
set is executed when the condition is false. The basic syntax is the "If"
statement:
If[condition_statement,
true_statements,
false_statements,
unknown_statements
]
where
condition_statement is an expression that evaluates to either
"True" or "False". Examples: x>0, y<ymax, z==0, etc.
true_statements is a set of expressions to be executed if the
condition_statement evaluates to "True". Each expression needs to
be terminated with a semicolon.
false_statements is a set of expressions to be executed if the
condition_statement evaluates to "False". Each expression needs
to be terminated with a semicolon.
unknown_statements is a set of expressions to be executed
if the condition_statement evaluates to neither "True" nor "False".
Each expression needs to be terminated with a semicolon. This is essentially
a fail-safe catch mechanism.
If you do not need one of the above statements, you may leave it blank,
but be sure to put any necessary commas in to delineate where the statements
are supposed to be.
Be careful when using conditional statements that involve operations
on integer values, as unevaluated integer operations (See Integers
and Decimals are Not the same!) appear as symbolic expressions and
may not be processed by the conditional statements correctly.
Examples:
If[x<xmax, y =x, z=x]
If[z==0, z=zmax,]
If[result>n, n=n++;result=0, result=result+1,error= True]
Go back to the Main Menu
Defining
Equations
In Mathematica, an equation is a perfectly valid expression that can
be assigned to a variable. An equation is declared by using the logical
equals symbol "==":
For instance, the second order differential wave equation can be expressed
as such:
waveeq := y''[t] == -w^2*y[t]
Defining variables as equations greatly simplifies specifying the inputs
to equation solvers such as Solve or DSolve. See the example here under
"Multiple Line Functions".
Go back to the Main Menu
Graphics
Plotting
Functions
The simplest way to plot a function is by invoking the Plot function in
Mathematica:
The inputs inside the curly braces tell the Plot function the independent
variable and its minimum and maximum values respectively.
To plot more than one function at once, hand Plot a list of functions:
Plot[{f[t], g[t], h[t]},{t,-5,10}]
Note that there is a restriction here that each function must have the
same domain.
A useful way of plotting a function which has additional adjustable
parameters is to plot the same function multiple times, but with different
inputs:
Plot[{f[x, var1], f[x, var2], f[x, var3]}, {x, xmin, xmax}]
This will create a plot with three lines, each corresponding to the the
function f vs x with the f's second parameter's values at var1, var2, and
var3. This is a classic way of studying the behavior of a function w.r.t.
to its adjustable parameters.
To plot multiple plots with different domains, create a Plot for each
unique domain and assign each Plot to its own variable. Then combine those
variables into a list and use the Show function:
p1 = Plot[f[x],{x, xmin, xmax}]
p2 = Plot[y[t],{t, tmin, tmax}]
Show[{p1, p2}]
Go back to the Main Menu
Plotting
Data Points
To plot a series of (x,y) data points, the data must first be in the form
of a 2-dimensional list:
data = {{0,0}, {1, 2}, {4, 5.5}}
To plot the data, use ListPlot:
To plot more than one list, use MultipleListPlot. This add-on must be loaded
first: "<<Graphics`MultipleListPlot`."
Go back to the Main Menu
Surface Plots
A 3-D surface plot can be created using the Plot3D command and a function
of at least two variables.
Plot3D[f[x,y], {x, xmin, xmax}, {y, ymin, ymax}]
Some common options:
PlotRange -> All : insures that the entire graph is shown.
PlotPoints ->{# of x points, # of y points} : controls the x and y resolutions.
Always start with the default value, which is about 15 points in each direction.
If higher resolution is needed, increas the numbers slowly. Values above
100 will take a long time to execute.
Mesh -> False : This controls the grid lines that are drawn at every
x and y point. The mesh is helpful to see the surface shape for low resolutions,
but can be distracting at high resolutions.
ViewPoint -> {X,Y,Z} : This is the coordinate from where a 3-D plot
is viewed from space. The easiest way to set these values is to use the
"3D ViewPoint Selector" from the main Mathematica menu. The "Paste" button
will write the ViewPoint option wherever the cursor is located (if you
are changing the viewpoint, be sure to highlight the whole ViewPoint option
to be replaced). Because 3D plots can take a long time to generate, it
is usually more efficient to assign the 3D plot to a variable and then
use the "Show[]" command with a ViewPoint option to manipulate the image.
A 3D surface plot can be turned into a normal contour plot this way (pS
is a surface plot):
Show[ContourGraphics[pS], ColorFunction -> Hue]
The ColorFunction option controls the colors in which each contour area
is shown. "Hue" colors each region a different color.
Go back to the Main Menu
Plotting
Options
PlotRange -- Allows you to specify the x,y, and z ranges for
a plot. "PlotRange->All" will force Mathematica to show the entire plot.
"PlotRange->{{-5,10}, {20, 35}}" will show the plot with the x-axis going
form -5 to 10 and the y-axis going from 20 to 35.
AspectRatio -- Controls the height vs width ratio of a plot display.
"AspectRatio->Automatic" will give a 1:1 aspect ratio that will show circles
as circles, squares as squares, etc.
PointStyle -- Specifies the color, point size and line style
for each function plotted. The styles for each function are given as a
list of styles.
Colors -- Load the color definitions add-on:
Point Size--
Line Styles --
DisplayFunction -- "DisplayFunction -> Identity" will suppress graphics
output to the screen, but still allow the graph to be assigned to a variable.
This is useful if you are generating multiple plots that will later be
shown together, but you don't want to clutter the screen with unnecessary
graphs. But sure, however, to turn the DisplayFunction back on in the Show
command by using the "DisplayFunction -> $DisplayFunction" option. Example:
p=Plot[Sin[x],{x,0,10},PlotStyle -> {{Red}}, DisplayFunction -> Identity];
Show[p,DisplayFunction->$DisplayFunction]
SymbolStyle
SymbolShape
PlotJoined -- "PlotJoined->True" will connect the points of a
ListPlot together with a line.
AxesOrigin -- Specifies where the origin of thedisplayed axis
is located. "AxesOrigin -> {0,0}" will force Mathematica to put the axis
at the origin.
There are many, many more options available than discussed here. Check
out the on-line help and the Mathematica book for details.
Go back to the Main Menu
Using Rules
Many Mathematica functions such as Solve or FindRoot return "rules"
as their output. A rule is a mapping that defines a replacement operation.
In such, the user can define rules as a way of doing algebraic replacements.
A rule has this syntax:
The interpretaion of this is to replace expr1 with expr2.
A rule is executed using the replacement operator "/." (forward slash +
period). For instance:
In[1] rule1 = z->x^2+1
In[2] (3+z) /. rule1
Out[2] x^2+4
In[3] ans = FindRoot[(y-4)^2,{y,3.5}]
Out[3] {y->4}
In[4] (2+y)^3 /. ans
Out[4] 216
Go back to the Main Menu
Turning
Expressions into Functions
Functions such as Fit will return an algebraic expression that one
would often like to turn into a function. This can be accompished using
the replacement operator, "/." (see the section of Using
Rules), to replace the variable in the expression with the local input
variable in a function. For example:
In[1] data= {{0,3}, {1,5}, {2,6}, {3,9}}
Out[1] {{0, 3}, {1, 5}, {2, 6}, {3, 9}}
In[2] ans=Fit[data, {1, x, x^2 }, x]
Out[2] 3.15 + 1.15 x + 0.25 x^2 [Editor's Note: correction of "^2" was inserted]
In[3] f[y_] := ans/.x->y
In[4] f[10]
Out[4] 39.65
Go back to the Main Menu
Execution Speed
-
Use "=" instead of ":=" whenever possible.
-
Use the decimal value of expressions if the accuracy is not an issue: Using
"N[Sqrt[3]]" will execute much faster than simply "Sqrt[3]".
-
Use a compiled function if needed. Though be careful that if the function
calls another function, there may not much of a speed increase even if
both functions are compiled. The (ugly) solution is to combine the two
functions into a single function and compile just one monolithic function.
-
Suppress the output of unnecessary graphics, which take up large amouts
of memory, especially 3-D graphics. Restart the worksheet and only execute
the lines that are necessary by commenting out lines used for testing purposes.
-
To time an expression, use "Timing[expr]" where expr is the
entire expression to be evaluated, including any assignments.
Source 05 is a link to a mathematica notebook by Kyle Keane. This mathematica module may be a welcome introduction to mathematica.
The Computer Science Department of Purdue University has produced (years ago) the pdf documents in Source 01, Source 02 and Source 03. They still serve as a useful introduction to IT and Mathematica. Chapter 01 is a brief introduction to Information Technology. Interestingly, on page 23, it compares two versions of a program, one
in (ancient) Fortran 77 and the other in Mathematica. It is an interesting sidenote that (with very few changes), Chapters 1, 2 and 3 could all be created using a single mathematica program (notebook) module. As of 2023, Chapter 3 still contains a few typographical errors:
Errata in Source 03 (Chapter 3)
-
p45 statement should be
Do[Print[k,” “,k^2” “,k^3], {k,3}]
-
p65 statement should be
-16.12 {result from last expression: a*b}
-
p81 text should be
Copy[“file 1”, “file 2”] - copies items in file 1 to file 2.
-
p81 statement should be
SetDirectory[“dirname”] - set current working dir.
-
p83 heading should be
Number Representations in Mathematica
-
Submit your own!
Please submit your favorite tips and traps!
E-mail a tip, trap or suggestion.
Original Source: Oberlin College-Physics and Astronomy Department (deprecated)
Original Author: Stephen.Wong@oberline.edu [bad email-deprecated]
Related References!
Web Sources
Web Source: S074:01 www
Chapter 1: General [CS / IT] Topics by Purdue University as of 2023 I Sep 13
Web Source: S074:02 www
Chapter 2: Mathematica by Purdue University as of 2023 I Sep 13
Web Source: S074:03 www
Chapter 3: Programming in Mathematica by Purdue University as of 2023 I Sep 13
Web Source: S074:04 www
Mathematica Tips, Tricks, and Techniques (PDF) by Michael A. Morrison Date: 2000 D Apr 02
Web Source: S074:05 www
Free Wolfram Language on Raspberry Pi tutorial (NB) by Kyle Keane of MIT c2014
heading
Go Back to the Main Menu
WebMaster: David Cole
Created: 2015 D Apr 01
Updated: 2023 I Sep 13
/74.html