7/1/25, 6:29 AM simultaneous_equations.
py
~\Desktop\lab\simultaneous_equations.py
1 # RK4 Method for System of ODEs
2 # Name: Bigyan Adhikari
3 # Roll No: 080BEL021
4
5 import numpy as np
6 import matplotlib.pyplot as plt
7
8 # Define the system of differential equations
9 def f1(x, y, z):
10 return 2*y + z
11
12 def f2(x, y, z):
13 return y - 3*z
14
15 # Initial conditions
16 x0 = 0
17 y0 = 0
18 z0 = 0.5
19
20 # Step size and number of steps
21 h = 0.1
22 n = 20 # From x=0 to x=2
23
24 # Lists to store values
25 x_vals = [x0]
26 y_vals = [y0]
27 z_vals = [z0]
28
29 # RK4 Iteration
30 for _ in range(n):
31 x = x_vals[-1]
32 y = y_vals[-1]
33 z = z_vals[-1]
34
35 k1 = h * f1(x, y, z)
36 l1 = h * f2(x, y, z)
37
38 k2 = h * f1(x + h/2, y + k1/2, z + l1/2)
39 l2 = h * f2(x + h/2, y + k1/2, z + l1/2)
40
41 k3 = h * f1(x + h/2, y + k2/2, z + l2/2)
42 l3 = h * f2(x + h/2, y + k2/2, z + l2/2)
43
44 k4 = h * f1(x + h, y + k3, z + l3)
45 l4 = h * f2(x + h, y + k3, z + l3)
46
localhost:54033/c41705e7-3141-4afb-bf26-e0e6421863b5/ 1/2
7/1/25, 6:29 AM simultaneous_equations.py
47 y_next = y + (k1 + 2*k2 + 2*k3 + k4) / 6
48 z_next = z + (l1 + 2*l2 + 2*l3 + l4) / 6
49
50 x_vals.append(x + h)
51 y_vals.append(y_next)
52 z_vals.append(z_next)
53
54 # Print output table
55 print("x\t\ty\t\tz")
56 for i in range(len(x_vals)):
57 print(f"{x_vals[i]:.4f}\t{y_vals[i]:.4f}\t{z_vals[i]:.4f}")
58
59 # Exact solutions
60 def y_exact(x):
61 return 0.1 * (np.exp(2*x) - np.exp(-3*x))
62
63 def z_exact(x):
64 return 0.1 * (np.exp(2*x) + 4*np.exp(-3*x))
65
66 # Smooth values for exact curves
67 x_exact = np.linspace(x0, x0 + n*h, 500)
68 y_ex = y_exact(x_exact)
69 z_ex = z_exact(x_exact)
70
71 # Plotting
72 plt.figure(figsize=(12, 5))
73
74 plt.subplot(1, 2, 1)
75 plt.plot(x_vals, y_vals, 'bo-', label='RK4 y')
76 plt.plot(x_exact, y_ex, 'r--', label='Exact y')
77 plt.xlabel('x')
78 plt.ylabel('y')
79 plt.title('x vs y')
80 plt.legend()
81 plt.grid(True)
82
83 plt.subplot(1, 2, 2)
84 plt.plot(x_vals, z_vals, 'go-', label='RK4 z')
85 plt.plot(x_exact, z_ex, 'm--', label='Exact z')
86 plt.xlabel('x')
87 plt.ylabel('z')
88 plt.title('x vs z')
89 plt.legend()
90 plt.grid(True)
91
92 plt.suptitle('RK4 Solution vs Exact Solution\nBigyan Adhikari | 080BEL021')
93 plt.tight_layout()
94 plt.show()
95
localhost:54033/c41705e7-3141-4afb-bf26-e0e6421863b5/ 2/2