Write code to solve

10.C] Write code to solve \frac{dy}{dx} = 1 + \frac{y}{x}, \quad y(1) = 2 at x = 2, using RK-4 method with h = 0.2

Answer:

'''Program to find y using RK4 method'''

from sympy import symbols, lambdify
import numpy as np

# Define symbolic variables
x, y = symbols('x y')

# Define the differential equation dy/dx = 1 + y/x
diff_eq = 1 + y / x
f = lambdify([x, y], diff_eq)

# Initial conditions
x0 = 1.0
y0 = 2.0
h = 0.2
xn = 2.0

# Store the results
results = []

# Runge-Kutta 4th Order Iteration
while x0 <= xn + 1e-8:  # Include xn with a small tolerance
    k1 = h * f(x0, y0)
    print(f'k1 = {k1:.4f}')

    k2 = h * f(x0 + h/2, y0 + k1/2)
    print(f'k2 = {k2:.4f}')

    k3 = h * f(x0 + h/2, y0 + k2/2)
    print(f'k3 = {k3:.4f}')

    k4 = h * f(x0 + h, y0 + k3)
    print(f'k4 = {k4:.4f}')

    y1 = y0 + (1/6) * (k1 + 2*k2 + 2*k3 + k4)
    results.append(y1)

    print(f'x = {x0 + h:.1f}, y = {y1:.6f}\n')

    # Prepare for next iteration
    x0 += h
    y0 = y1

# Final result
print(f'Approximate value of y at x = {xn:.1f} is: {results[-1]:.6f}')

Leave a Reply

Your email address will not be published. Required fields are marked *