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.
  1. A Defensive Move
  2. Manipulating Input Regions
  3. Defining Variables
  4. Integers and Decimals are Not the same!
  5. Defining Functions
    1. Single Line Functions
    2. Multiple Line Functions
    3. Compiled Functions
  6. Defining Arrays
    1. One dimensional Arrays/Lists
    2. Multidimensional Arrays/Lists
    3. Generating Array/Lists
  7. Using Conditionals
  8. Defining Equations
  9. Graphics
    1. Plotting Functions
    2. Plotting Data Points
    3. Surface Plots
    4. Plotting Options
  10. Using Rules
  11. Turning Expressions into Functions
  12. Execution Speed
  13. Submit your own!
  14. Related References!

 

See the original webpage (deprecated) for some examples mentioned here in the original web site.

Wolfram's Home Page  Wolfram's Library Page  Raspberry Pi 

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 2 B
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:

Go back to the Main Menu


Defining Variables

 

There are two ways to assign a value (numeric or symbolic) to a variable in Mathematica:

  1. 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.
  2. 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:

Go back to the Main Menu


Defining Functions  
      f[time_, dfinal_, vfinal_] = Module[ {acc,v0, eq1, eq2,result},
      (1) 
        eq1 := vfinal== (1/2)*acc*time + v0;
      (2) 
        eq2 := dfinal == acc*time^2 + v0*time;
        result = {acc,v0} /.Solve[{eq1,eq2},{acc, v0}]; 
        result
      (3)
       ];
      (4)
 
    1. 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.
    2. Note the indentation. This is good programming practice and helps to visually separate the body of the function from its definition.
    3. The output of the function is the last line. Note the lack of the semicolon. You will get no output with a semicolon here.
    4. 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: 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:.

    The rows can be accessed as a single entity: 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:

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:

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:

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


Using Rules


Turning Expressions into Functions


Execution Speed
  1. Use "=" instead of ":=" whenever possible.
  2. 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]".
  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.
  4. 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.
  5. 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)
  1. p45 statement should be
    Do[Print[k,” “,k^2” “,k^3], {k,3}]
  2. p65 statement should be
    -16.12 {result from last expression: a*b}
  3. p81 text should be
    Copy[“file 1”, “file 2”] - copies items in file 1 to file 2.
  4. p81 statement should be
    SetDirectory[“dirname”] - set current working dir.
  5. 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
Click here to return to ePC Articles

WebMaster: David Cole

Created: 2015 D Apr 01
Updated: 2023 I Sep 13
/74.html