Mathematical Principles for Scientific Computing and Visualization  
http://www.farinhansford.com/books/scv
by Gerald Farin and Dianne Hansford


This notebook demonstrates Euler's method for solving an initial value ODE problem.  
Problem: Find values of y over [0,2] for y' = y given initial value y(0) = 1.
The exact solution is e^x.

We compare the solution using 10 steps and 30 steps.
Compare solution with the solution using Huen's method in Huen.nb.

See Chapter 9: Computing Dynamic Processes for details.

Updated May 2008

(* Output results to folder that this file lives in *)
(SetDirectory[ToFileName[Extract["FileName"/.NotebookInformation[EvaluationNotebook[]],{1},FrontEnd`FileName]]];) 

(* Euler's method *)
euler[f_,{x_,x0_,xn_},{y_,y0_},steps_]:=Block[{xold=x0,yold=y0,sollist={{x0,y0}},x,y,h},h=N[((xn-x0)/steps)];Do[xnew=xold+h;ynew=yold+h (f/.{x->xold,y->yold});sollist=Append[sollist,{xnew,ynew}];xold=xnew;yold=ynew,{steps}];Return[sollist]]


(* Create the plot of the exact solution *)
exactplot=Plot[(E^x),{x,0,2},PlotStyle->{GrayLevel[0.7],Thickness[0.03`]},BaseStyle->{"FontFamily"->"Helvetica","FontSize"->11},  AxesStyle->Directive[GrayLevel[0.0],Thickness[0.005]],TicksStyle->Directive[GrayLevel[0.0],Thickness[0.005]], ColorOutput->CMYKColor];

(* Euler's method with 10 steps *)
eulsol10=euler[y,{x,0,2},{y,1.`},10];

(* create the plot of the solution with 10 steps *)
eulplot10=ListPlot[eulsol10,PlotStyle->{GrayLevel[0],PointSize[0.03`]},Frame->True,BaseStyle->{"FontFamily"->"Helvetica","FontSize"->11}, AxesStyle->Directive[GrayLevel[0.0],Thickness[0.005]],TicksStyle->Directive[GrayLevel[0.0],Thickness[0.005]], ColorOutput->CMYKColor];

(* Store the plot the exact solution and Euler's with 10 steps *)
plt10 =Show[{exactplot,eulplot10}]

(* Export to a postscript file *) 
Export["euler10.eps",plt10]

(* Euler's method with 30 steps *)
eulsol=euler[y,{x,0,2},{y,1.`},30];

(* Store the plot of the solution with 30 steps *)
eulplot=ListPlot[eulsol,PlotStyle->{GrayLevel[0],PointSize[0.03`]},Frame->True,BaseStyle->{"FontFamily"->"Helvetica","FontSize"->11}, AxesStyle->Directive[GrayLevel[0.0],Thickness[0.005]],TicksStyle->Directive[GrayLevel[0.0],Thickness[0.005]], ColorOutput->CMYKColor];


(* Plot the exact solution and Euler's with 30 steps *)
plt=Show[{exactplot,eulplot}]

(* Export to a postscript file *) Export["euler30.eps",plt]