Solution of Differential Equations

python code:

#solve by Euler method:  dy/dx=-y, given y(0)=1
def f(x,y):
    return -y
h=0.01
y=1.0
x=0
while x<.04:
    y=y+h*f(x,y)
    x=x+h
    print x,"  ",y



Output



RK Method Second order
#to evaluate the differential equ dy/dx=y-x at x=0.1 to x=1.1,y(0)=2
def f(x,y):
    return y-x
h=0.1
y=2.0
x=0.0
k1=0.0
k2=0.0
while x<0.4:
    k1=h*f(x,y)
    k2=h*f(x+h,y+k1)
    y=y+(k1+k2)/2.0
    x=x+h
    print x,"    ",y

 Output
 0.1     2.205
0.2     2.421025
0.3     2.649232625
0.4     2.89090205063


RK method Fourth Order:
#to evaluate the differential equ dy/dx=y-x at x=0.1 & x=.2
def f(x,y):
    return y-x
x,y,h=0.0,2.0,.1
while x<0.2:
        k1=h*f(x,y)
        k2=h*f(x+h/2,y+k1/2)
        k3=h*f(x+h/2,y+k2/2)
        k4=h*f(x+h,y+k3)
        x=x+h
        y=y+(k1+2*(k2+k3)+k4)/6.0
        print "k1,k2,k3,k4=",k1,k2,k3,k4
        print 'The value of y at %f=%f'%(x,y)

Output:
k1,k2,k3,k4= 0.2 0.205 0.20525 0.210525
The value of y at 0.100000=2.205171
k1,k2,k3,k4= 0.210517083333 0.2160429375 0.216319230208 0.222149006354
The value of y at 0.200000=2.421403


Comments