Euler Method Functions

EulerMethodPoints[n_,h_,x0_,y0_,f_]:=Module[
{i=0,pts={{x0,y0}},point},
For[,i<n,i++,
point=Last[pts];
AppendTo[pts,point+{h,h Apply[f,point]}];
];
pts
]
EulerMethodPointsN[n_,h_,x0_,y0_,f_]:=Module[
{i=0,pts={{x0,y0}},point},
For[,i<n,i++,
point=Last[pts];
AppendTo[pts,point+N[{h,h Apply[f,point]}]];
];
pts
]
EulerMethodTable[n_,h_,x0_,y0_,f_]:=Module[
{i=0,pts={Prepend[N[{x0,y0,f[x0,y0]}],0]},point,newpoint,entry},
For[,i<n,i++,
entry=Last[pts];
point=entry[[2;;3]];
newpoint=point+{h,h entry[[4]]};
AppendTo[pts,Prepend[N[Append[newpoint,Apply[f,newpoint]]],i+1]];
];
TraditionalForm[Grid[Prepend[pts,{"n","xn","yn","yn'"}],Frame->All,Alignment->"."]]
]

IVP : y’ = x - y, y(0) = 1; estimate y(1)

f1[x_, y_]=x-y;

solexact1[x_]=x-1+2 (E^(-x));

solexact1[1]//N

plotexact1=Plot[solexact1[x],{x,0,1},PlotRange->{1/4,1}];

plot1euler2=ListLinePlot[EulerMethodPoints[2,1/2,0,1,f1]];
plot1euler5=ListLinePlot[EulerMethodPoints[5,1/5,0,1,f1]];
plot1euler10=ListLinePlot[EulerMethodPoints[10,1/10,0,1,f1]];
plot1euler100=ListLinePlot[EulerMethodPoints[100,1/100,0,1,f1]];
plot1euler1000=ListLinePlot[EulerMethodPoints[1000,1/1000,0,1,f1]];

Show[plotexact1,plot1euler2]

Show[plotexact1,plot1euler2,plot1euler5]

Show[plotexact1,plot1euler2,plot1euler5,plot1euler10]

Show[plotexact1,plot1euler2,plot1euler5,plot1euler10,plot1euler100]

Show[plotexact1,plot1euler2,plot1euler5,plot1euler10,plot1euler100,plot1euler1000]

finalvalues1=Map[{#,Last[EulerMethodPointsN[#,1/#,0,1,f1]][[2]]}&,
{2,5,10,100,1000,10000}
];
TraditionalForm[Grid[Prepend[Map[{#[[1]],#[[2]],N[solexact1[1]-#[[2]]]}&,
finalvalues1
],{"n","yn","error"}],Frame->All,Alignment->"."]]

IVP: y = (1/2)(y^2), y(0) = 1; estimate y(2)

f2[x_,y_]=(1/2)(y^2);

solexact2[x_]=(2/(2-x));

plotexact2=Plot[solexact2[x],{x,0,2},PlotRange->{{0,3},{0,20}}];

plot2euler2=ListLinePlot[EulerMethodPoints[3,1,0,1,f2]];
plot2euler4=ListLinePlot[EulerMethodPoints[6,1/2,0,1,f2]];
plot2euler64=ListLinePlot[EulerMethodPointsN[96,1/32,0,1,f2],PlotRange->{0,20}];

Show[plotexact2]

Show[plotexact2,plot2euler2]

Show[plotexact2,plot2euler2,plot2euler4]

Show[plotexact2,plot2euler2,plot2euler4,plot2euler64]

EulerMethodTable[64,1/32,0,1,f2]