The Computable Differential Equation Lecture ... - Bruce E. Shapiro
The Computable Differential Equation Lecture ... - Bruce E. Shapiro
The Computable Differential Equation Lecture ... - Bruce E. Shapiro
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
CHAPTER 1. CLASSIFYING THE PROBLEM 19<br />
Implementing Numerical Methods with Mathematica<br />
Finally we note that Mathematica contains a full high level programming language<br />
comparable to languages such as C and LISP. We will be using this language to<br />
implement our own versions of various algorithms as they arise.<br />
<strong>The</strong> following piece of code gives an implementation of Euler’s method using the<br />
traditional C-language like structures in Mathematica. It returns a list of number<br />
pairs {{t 0 , y 0 }, {t 1 , y 1 }, . . . }.<br />
EulersMethod[f , t0 , y0 , tmax , h ] :=<br />
Module[{y, t, solution},<br />
solution = {{t0, y0}};<br />
y = y0;<br />
t = t0;<br />
While[t < tmax,<br />
y = y + h*f[t, y];<br />
t = t + h;<br />
solution = Append[solution, {t, y}];<br />
];<br />
Return[solution];<br />
]<br />
Let us dissect this program. To begin with we have to tell Mathematica that we are<br />
defining a function:<br />
⇐=<br />
EulersMethod[f , t0 , y0 , tmax , h ] :=<br />
Module[{y, t, solution},<br />
· · · stuff · · ·<br />
]<br />
This says that we are defining a new function EulersMethod that takes on 5 arguments<br />
(f, t0, y0, tmax, h) and has 3 local variables (y, t, solution). In the<br />
function declaration the names of the parameters always end with an underscore<br />
character ; this tells Mathematica that these are the names of variables that are<br />
passed to the program. Within the function the underscore is not used. <strong>The</strong>se arguments<br />
and the three local variables are only defined within the scope of the program,<br />
so that any other variable inside EulersMethod can refer to them directly, but no<br />
variable outside of the function definition knows of their existence. So if there is<br />
are global variable f or y , their values are not affected by the function definition.<br />
<strong>The</strong> next three lines initialize our local variables equal to certain combinations of<br />
argument values.<br />
solution = {{t0, y0}};<br />
y = y0;<br />
t = t0;<br />
c○2007, B.E.<strong>Shapiro</strong><br />
Last revised: May 23, 2007<br />
Math 582B, Spring 2007<br />
California State University Northridge