RK 4 order method & RK 2 order
RK Fourth Order:
#Given dy / dx = y − x where y (0) = 2, find y (0.1)
def f(x,y):
return y-x
x,y,n=input('Enter initial values of x,y and no. of intervals: ')
xf=input('Enter x for which y is required: ')
h=(xf-x)/float(n)
for i in range(n):
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 'The values of y at %f=%f' %(x,y)
Output:
Enter initial values of x,y and no. of intervals: 0,2,1
Enter x for which y is required: .1
The values of y at 0.100000=2.205171
RK Second Order:
def f(x,y):
return y-x
x,y,n=input('Enter initial values of x,y and no. of intervals: ')
xf=input('Enter x for which y is required: ')
h=(xf-x)/float(n)
for i in range(n):
k1=h*f(x,y)
k2=h*f(x+h/2,y+k1/2)
x=x+h
y=y+(k1+k2)/2.0
print 'The values of y at %f=%f' %(x,y)
Output:
Enter initial values of x,y and no. of intervals: 0,2,1
Enter x for which y is required: .1
The values of y at 0.100000=2.202500
#Given dy / dx = y − x where y (0) = 2, find y (0.1)
def f(x,y):
return y-x
x,y,n=input('Enter initial values of x,y and no. of intervals: ')
xf=input('Enter x for which y is required: ')
h=(xf-x)/float(n)
for i in range(n):
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 'The values of y at %f=%f' %(x,y)
Output:
Enter initial values of x,y and no. of intervals: 0,2,1
Enter x for which y is required: .1
The values of y at 0.100000=2.205171
RK Second Order:
def f(x,y):
return y-x
x,y,n=input('Enter initial values of x,y and no. of intervals: ')
xf=input('Enter x for which y is required: ')
h=(xf-x)/float(n)
for i in range(n):
k1=h*f(x,y)
k2=h*f(x+h/2,y+k1/2)
x=x+h
y=y+(k1+k2)/2.0
print 'The values of y at %f=%f' %(x,y)
Output:
Enter initial values of x,y and no. of intervals: 0,2,1
Enter x for which y is required: .1
The values of y at 0.100000=2.202500
Comments
Post a Comment