0% found this document useful (0 votes)
12 views3 pages

Welcome To Colab - Colab

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Welcome To Colab - Colab

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#Name: Rupam Mondal

#Roll no.: 233142-21-0076


#Date: 16/12/24

import numpy as np
import matplotlib.pyplot as plt

# Function for first-order ODE


def f1(x, y):
return x + y

# RK2 method
def RK2_first_order(f, x0, y0, xn, h):
n = int((xn - x0) / h)
x, y = x0, y0
x_vals, y_vals = [x], [y]

for _ in range(n):
k1 = h * f(x, y)
k2 = h * f(x + h, y + k1)
y += (k1 + k2) / 2
x += h
x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# RK4 method
def RK4_first_order(f, x0, y0, xn, h):
n = int((xn - x0) / h)
x, y = x0, y0
x_vals, y_vals = [x], [y]

for _ 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)
y += (k1 + 2*k2 + 2*k3 + k4) / 6
x += h
x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Function for second-order ODE


def g(x, y, v):
return x + y

def RK4_second_order(g, x0, y0, v0, xn, h):


n = int((xn - x0) / h)
x, y, v = x0, y0, v0
x_vals, y_vals, v_vals = [x], [y], [v]

for _ in range(n):
k1_y = h * v
k1_v = h * g(x, y, v)

k2_y = h * (v + k1_v / 2)
k2_v = h * g(x + h/2, y + k1_y/2, v + k1_v/2)

k3_y = h * (v + k2_v / 2)
k3_v = h * g(x + h/2, y + k2_y/2, v + k2_v/2)

k4_y = h * (v + k3_v)
k4_v = h * g(x + h, y + k3_y, v + k3_v)

y += (k1_y + 2*k2_y + 2*k3_y + k4_y) / 6


v += (k1_v + 2*k2_v + 2*k3_v + k4_v) / 6
x += h

x_vals.append(x)
y_vals.append(y)
v_vals.append(v)

return np.array(x_vals), np.array(y_vals)

# Define parameters
x0, y0, v0 = 0, 1, 0
xn = 10
h = 0.1

x_rk2, y_rk2 = RK2_first_order(f1, x0, y0, xn, h)


x_rk4, y_rk4 = RK4_first_order(f1, x0, y0, xn, h)

x_rk4_2nd, y_rk4_2nd = RK4_second_order(g, x0, y0, v0, xn, h)

# Plot results
plt.figure(figsize=(10, 5))

# First-order ODE
plt.subplot(1, 2, 1)
plt.plot(x_rk2, y_rk2, 'b-', label="RK2 Solution")
plt.plot(x_rk4, y_rk4, 'r--', label="RK4 Solution")
plt.xlabel("x")
plt.ylabel("y")
plt.title("First-Order ODE Solution")
plt.legend()

# Second-order ODE
plt.subplot(1, 2, 2)
plt.plot(x_rk4_2nd, y_rk4_2nd, 'g-.', label="RK4 Second-Order Solution")
plt.xlabel("x")
plt.ylabel("y")
plt.title("Second-Order ODE Solution")
plt.legend()

plt.tight_layout()
plt.show()

You might also like