Examples - Lecture 1

Course: Foundations of Numerical Methods
Software: Mathematica 5.0 (so far, may change....)
Lecturer: Carla Figueira de Morisson Faria
Please note:
(a) The program is divided in cells
(b) To initialize the cells: (shift+enter); you should try only in the yellow cells

If statements

(* 
      notes on syntax :  
          Print[] writes something on the screen,  
      the semi - 
        colon does not let anything be printed *) 
 (* 
      initialization of variables *) 
a = 
        1;

    b = 3;
 (* 
      if statement *) 

    If[a < b,  Print[a], Print[b]]

     (* Question :  
        what do I have to do to get 1 on the screen? *)

Do statements

Do[Print[2*i], {i, 1, 10}]

Nested if statements

f[x_] := 
      If[x ≤ -5, 0, If[x <= 5, 1, 0]]

      
Plot[f[x], {x, -20, 20}, PlotRange -> {0, 2}]

Combined if statements/do  loops

Do[If[i > 5, Print[50], Print[i]], {i, 1, 10}]

Truncation error

Comments on Syntax:
  (a)  Here we used the built-in exponential function
   (b) If a do loop involves only a sum, in Mathematica it can be performed in the way below
      (how about doing it in the standard way?)

x = 
        2;
  

    expon = N[Exp[x]]
  

    etest = N[Sum[x^n/(n!), {n, 0, 5}]]
  

    abserror = Abs[expon - etest]

    relerr = Abs[(expon - etest)/expon]

x = 2;
expon = N[Exp[x]]
etest = 
      N[Sum[x^n/(n!), {n, 0, 100}]]
abserror = Abs[expon - etest]
relerr = Abs[(expon - etest)/expon]