Euler's method

339 days ago by david.guichard

The euler function computes and displays approximations to points on the solution curve for the differential equation y'=f(t,y) with initial condition init_t, init_y. The step size is (final_t-init_t)/m. The function displays the points calculated and also returns a list of the points.

def euler(f,init_t,init_y,final_t,m): p=lambda t,y: y+((final_t-init_t)/m)*f(t,y); tt=init_t; yy=init_y; data=[[tt,yy]]; for i in range(m): yy=p(t=tt,y=yy) tt=tt+(final_t-init_t)/m print n(tt),n(yy) data.append([tt,yy]); return data 
       
pts=euler(lambda t,y: t-y^2,0,0,1,5) 
       
0.200000000000000 0.000000000000000
0.400000000000000 0.0400000000000000
0.600000000000000 0.119680000000000
0.800000000000000 0.236815339520000
1.00000000000000 0.385599038513605
0.200000000000000 0.000000000000000
0.400000000000000 0.0400000000000000
0.600000000000000 0.119680000000000
0.800000000000000 0.236815339520000
1.00000000000000 0.385599038513605

Now we can plot the points joined by line segments.

p1=list_plot(pts,plotjoined=true) 
       

Plot the slope field.

dummy=var("x y"); p2=plot_slope_field(x-y^2,(x,0,1),(y,0,0.5)) 
       

Display the two plots together.

show(p1+p2)