PROGRAMMING IN MATHEMATICA

Tuesday, 8 July 2003

Procedural Programming Style

Mathematica supports a variety of so-called programming styles.  You can program in the spirit of C or Fortran; you may also do object oriented programming like C++; or you can do functional programming like LISP; and the rule-based programming style is powerful and can be concise.  Here we demonstrate few ways of write a factorial function:

\(fac[m_Integer] := 
      Module[\ {i, \ n}, \ 
	
        If[\ m\  < \ 0, \ 
		Return[Infinity]]; 
	
        n\  = \ 1; 
	
        For[i\  = \ 1, \ i\  <= \ m, \ \(++i\), \ 
	
          n\  = \ n*i]; 
\ \ \ \ \ n]\)

Few fine points: (1) use m only as a constant, (2) declare all variables except the argument as local, (3) return value is the last expression.  We use the function as usual:

fac[2]

A much quicker way is to used the build-in function n!

fac[n_Integer]  :=  n!

Or use a recursive definition

fac[0]  =  1;  fac[n_Integer]  := n * fac[n - 1]

Or use functional programming style:

fac[n_Integer]  :=  Times  @@  Range[n]

Procedural Programming Constructs

Apart from syntactic differences, many of these constructs are similar to C.  The For loop:

For[initial,  condition,  
      inc, 
    body]

For[i  =  0,  
      i  <  4,  ++i, 
   Print["i=",  
        i]
]

i  =  3;  While[ i  > 0,  --i;  Print[i]]

?Which

Which is like a sequence of if-else.

\(f[x_]\  := \ 
      Which[x < \(-1\), \ \(-1\), 
		x <= 0, \ \(-1\)/
          2, 
		x > 0\  && \ x\  < 1, \ 
        1/2, 
		x\  >= \ 1, \ 1]\)

Plot[f[x],  {x, -3, 3}]

The If condition is in one of the three forms:

If[test,  then]

If[test,  then,  else]

If[test,  then,  else,  unknown]

Where test is an expression which evaluates to the symbol True or False; if test evaluates to True, the ``then'' expression is evaluated, otherwise, the ``else'' expression is evaluated.  If test is an expression other than True or False, unknown part will be evaluated.

If[True,  a,  b,  c]

Logical expressions can be formed similarly to C:

<                   less than
<= ( ≤ )      less equal
>                   greater than
>=  ( ≥ )     greater equal
==                  equal
!= ( ≠  )     not equal
 && ( ∧ )     AND
 || ( ∨ )     OR
===              identical
=!=              not identical

With in notebook interface, we can also use equivalent math symbols: e.g.:

x = 4; 
    If[x  ≠  0  ∧  x  >  2,  Print[x]]

The last two (===,=!=) is a stronger form of equal or not equal:

{a == b,  a === b}

(1 + x)^2  ==  1  +  2  x  +  x^2

Typing of special symbols

Special symbol like π or α can be typed in 
	(1) using palettes,
	(2) key strokes with ESC code ESC.  e.g. π is ESC p ESC, or TEX style input ESC \pi ESC.
Superscripts/subscripts can be typed in with Ctrl-^, Ctrl-_; Control-space get you back to normal type.  e.g.  (Subscript[x, 2.])

(((1  +  α ))^2)  //  Expand

N[π]

Programming example: Gaussian elimination

1. What user interface to use?
2. How much to check the validity of input data?
3. Error handling, what to do if solution does not exist?

gauss[a_List,  b_List]  :=  
      Module[ {m = a, n, i, j, c0, c1,  new}, 
m  =  
          Transpose[m] ~Join~{ b}; 
m  =  
          Transpose[m];  
n  =  
          Length[b]; 
For[i  =  1,  
          i  <  n,  ++i, 
 
          c0  =  m[[i, i]]; 
For[j  =  i + 1,  
            j  ≤  n,  ++j, 
 
            c1  =  m[[j, i]]; 
new  =   c0 * 
                  m[[j]]  -  
                c1 * m[[i]]; 
m[[j]]  =  
              Simplify  /@  new;
]; 
 
          Print[MatrixForm[m]]
]; 
 
        backsub[m]
]

backsub[] will be left for the next lab problem.