Quit[];

(* Esercizio 5.2.1 *)

(* a *) f[t_,y_]:=t*E^(3t)-2y;
α=0.;
tA=0.0; tB=1.;
n=10;
h=(tB-tA)/n;
t[0]=tA;
t[n]=tB;
Do[t[i+1]=t[i]+h,{i,0,n-1}]
w[0]=α;
Do[w[i+1]=w[i]+h*f[t[i],w[i]],{i,0,n-1}];
sol=Table[{t[i],w[i]},{i,0,n}];
solnum=NDSolve[{y'[t]==f[t,y[t]],y[tA]==α},y[t],{t,tA,tB}][[1]];
(*soltrue=DSolve[{y'[t]==f[t,y[t]],y[tA]==α},y[t],t][[1]]*)
trange={tA,tB};
yrange={0,2};
pl1=ListPlot[sol,PlotRange->{trange,yrange}];
pl2=Plot[y[t]/.solnum,{t,tA,tB},PlotRange->{trange,yrange}];
(*pl3=Plot[y[t]/.soltrue,{t,tA,tB},PlotRange->{trange,yrange},PlotStyle->RGBColor[1,0,0]];*)
Show[pl1,pl2]

(* b *) f[t_,y_]:=1+(t-y)^2;
α=1.;
tA=2.; tB=3.;
n=2;
h=(tB-tA)/n
t[0]=tA;
t[n]=tB;
Do[t[i+1]=t[i]+h,{i,0,n-1}]
w[0]=α;
Do[w[i+1]=w[i]+h*f[t[i],w[i]],{i,0,n-1}];
sol=Table[{t[i],w[i]},{i,0,n}];
solnum=NDSolve[{y'[t]==f[t,y[t]],y[tA]==α},y[t],{t,tA,tB}][[1]];
(*soltrue=DSolve[{y'[t]==f[t,y[t]],y[tA]==α},y[t],t][[1]]*)
trange={tA,tB};
yrange={0,2};
pl1=ListPlot[sol,PlotRange->{trange,yrange}];
pl2=Plot[y[t]/.solnum,{t,tA,tB},PlotRange->{trange,yrange}];
(*pl3=Plot[y[t]/.soltrue,{t,tA,tB},PlotRange->{trange,yrange},PlotStyle->RGBColor[1,0,0]];*)
Show[pl1,pl2]