Implementation of Euler's Method

Example 8.1 from Brannon and Boyce

ODE:  y' = -y/2 + 3/2 - t

f[t_,y_]=-y/2+3/2-t

sf=VectorPlot[{1,f[t,y]}/Norm[{1,f[t,y]}],{t,0,2.5},{y,0,2.5},VectorStyle->Arrowheads[0]]

Initial value:  y(0) = 1
We will approximate on the interval [0,1] with stepsize h = 1/N

tzero = 0;
yzero = 1;

euler[N_]:=For[j=1; soln={{tzero,yzero}},j<N+1,j++,soln=Union[soln,{{tzero+j (1/N),soln[[j]][[2]]+f[tzero + (j-1)/N,soln[[j]][[2]]] (1/N)}}]]

euler[1]

soln

show1=Show[sf,ListPlot[soln,Joined->True,PlotStyle->Green]]

euler[2]
soln

show2=Show[show1,ListPlot[soln,Joined->True,PlotStyle->Green]]

euler[5]
soln
N[soln]

show3=Show[show2,ListPlot[soln,Joined->True,PlotStyle->Green]]

euler[10]
soln

show4=Show[show3,ListPlot[soln,Joined->True,PlotStyle->Black]]

nsoln=NDSolve[{ny'[nt]==f[nt,ny[nt]],ny[tzero]==yzero},ny,{nt,0,1}]

rky[t_]=ny[t]/.nsoln[[1]]

Show[show4,Plot[rky[t],{t,0,1},PlotStyle->Red]]

Show[show4,Plot[rky[t],{t,0,1},PlotStyle->Red],PlotRange->{{0,1},{1,2}}]

Improved Euler Method

ieuler[N_]:=For[j=1; soln={{tzero,yzero}},j<N+1,j++,mone=f[tzero+(j-1)/N,soln[[j]][[2]]];mtwo = f[tzero+j/N,soln[[j]][[2]]+mone (1/N)];soln=Union[soln,{{tzero+j (1/N),soln[[j]][[2]]+((mone+mtwo)/2) (1/N)}}]]

ieuler[5]
N[soln]

Show[show3,ListPlot[soln,Joined->True,PlotStyle->Orange],PlotRange->{{0,1},{1,1.5}}]

Show[show3,ListPlot[soln,Joined->True,PlotStyle->Orange],Plot[rky[t],{t,0,1},PlotStyle->Red],PlotRange->{{0,1},{1,1.5}}]

Fourth Order Runge-Kutta Method

rk[N_]:=For[j=1; soln={{tzero,yzero}},j<N+1,j++,mone=f[tzero+(j-1)/N,soln[[j]][[2]]];mtwo = f[soln[[j]][[1]]+1/(2 N),soln[[j]][[2]]+mone (1/(2 N))];mthree=f[soln[[j]][[1]]+1/(2 N),soln[[j]][[2]]+mtwo (1/(2 N))] ;mfour=f[tzero+j/N,soln[[j]][[2]]+mthree (1/N)];soln=Union[soln,{{tzero+j (1/N),soln[[j]][[2]]+((mone+2 mtwo+2 mthree+mfour)/6) (1/N)}}]]

rk[5]
N[soln]

Show[ListPlot[soln,Joined->True,PlotStyle->Black],Plot[rky[t],{t,0,1},PlotStyle->Red],PlotRange->{{0,1},{1,1.5}}]