import math
def runge_kutta_4(f, x0, y0, x_final, step_size):
"""
Implements the Runge-Kutta 4th order method for solving ODEs.
"""
x_vals = [x0 + i * step_size for i in range(int((x_final - x0) / step_size) + 1)]
y = y0
print("\nRunge-Kutta 4 Method")
print("x\t\t y\t\t k1\t\t k2\t\t k3\t\t k4")
for x in x_vals:
k1 = f(x, y)
k2 = f(x + step_size / 2, y + step_size * k1 / 2)
k3 = f(x + step_size / 2, y + step_size * k2 / 2)
k4 = f(x + step_size, y + step_size * k3)
print(f"{x:.2f}\t {y:.4f}\t {k1:.4f}\t {k2:.4f}\t {k3:.4f}\t {k4:.4f}")
y += (step_size / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
# Define the differential equations as functions
def eq1(x, y): return 2*x - 3*y + 1
def eq2(x, y): return 4*x - 2*y
def eq3(x, y): return 1 - y**2
def eq4(x, y): return x**2 - y**2
def eq5(x, y): return math.exp(-y)
def eq6(x, y): return x - y**2
def eq7(x, y): return (x - y)**2
def eq8(x, y): return x*y + math.sqrt(y) if y >= 0 else x*y
def eq9(x, y): return x*y**2 - y
def eq10(x, y): return y - y**2
# Initial conditions and intervals for each problem
problems = [
(eq1, 1, 5, 1.5),
(eq2, 0, 2, 0.5),
(eq3, 0, 0, 0.5),
(eq4, 0, 1, 0.5),
(eq5, 0, 0, 0.5),
(eq6, 0, 0, 0.5),
(eq7, 0, 0.5, 0.5),
(eq8, 0, 1, 0.5),
(eq9, 1, 1, 1.5),
(eq10, 0, 0.5, 0.5)
]
# Solve for step sizes h = 0.1 and h = 0.05
for i, (func, x0, y0, x_final) in enumerate(problems, start=1):
print(f"\nSolving Problem 9.1.{i} with step size h = 0.1")
runge_kutta_4(func, x0, y0, x_final, 0.1)
print(f"\nSolving Problem 9.1.{i} with step size h = 0.05")
runge_kutta_4(func, x0, y0, x_final, 0.05) Click Run or press shift + ENTER to run code