AIM: Write a Python program to find numerical solution of ordinary differential equations by Runge-Kutta method.
Source Code:
# RK-4 method python program
# function to be solved
def f(x,y):
return x+y
# RK-4 method
def rk4(x0,y0,xn,n):
# Calculating step size
h = (xn-x0)/n
print("--------SOLUTION--------")
print("-------------------------")
print("x0\ty0\tyn")
print("-------------------------")
for i in range(n):
k1 = h * (f(x0, y0))
k2 = h * (f((x0+h/2), (y0+k1/2)))
k3 = h * (f((x0+h/2), (y0+k2/2)))
k4 = h * (f((x0+h), (y0+k3)))
k = (k1+2*k2+2*k3+k4)/6
yn = y0 + k
print("%.4f\t%.4f\t%.4f"% (x0,y0,yn) )
print("-------------------------")
y0 = yn
x0 = x0+h
print("At x=%.4f, y=%.4f" %(xn,yn))
print("Enter initial conditions:")
x0 = float(input("x0 = "))
y0 = float(input("y0 = "))
print("Enter calculation point: ")
xn = float(input("xn = "))
print("Enter number of steps:")
step = int(input("Number of steps = "))
rk4(x0,y0,xn,step)
Output:# function to be solved
def f(x,y):
return x+y
# RK-4 method
def rk4(x0,y0,xn,n):
# Calculating step size
h = (xn-x0)/n
print("--------SOLUTION--------")
print("-------------------------")
print("x0\ty0\tyn")
print("-------------------------")
for i in range(n):
k1 = h * (f(x0, y0))
k2 = h * (f((x0+h/2), (y0+k1/2)))
k3 = h * (f((x0+h/2), (y0+k2/2)))
k4 = h * (f((x0+h), (y0+k3)))
k = (k1+2*k2+2*k3+k4)/6
yn = y0 + k
print("%.4f\t%.4f\t%.4f"% (x0,y0,yn) )
print("-------------------------")
y0 = yn
x0 = x0+h
print("At x=%.4f, y=%.4f" %(xn,yn))
print("Enter initial conditions:")
x0 = float(input("x0 = "))
y0 = float(input("y0 = "))
print("Enter calculation point: ")
xn = float(input("xn = "))
print("Enter number of steps:")
step = int(input("Number of steps = "))
rk4(x0,y0,xn,step)
Enter initial conditions:
x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 3
--------SOLUTION--------
-------------------------
x0 y0 yn
-------------------------
0.0000 1.0000 1.4578
-------------------------
0.3333 1.4578 2.2286
-------------------------
0.6667 2.2286 3.4361
-------------------------
At x=1.0000, y=3.4361
x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 3
--------SOLUTION--------
-------------------------
x0 y0 yn
-------------------------
0.0000 1.0000 1.4578
-------------------------
0.3333 1.4578 2.2286
-------------------------
0.6667 2.2286 3.4361
-------------------------
At x=1.0000, y=3.4361