import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def dydt(t, y):
    return -2 * y

y0 = [1]

t_span = (0, 5)
t_eval = np.linspace(0, 5, 100)

sol = solve_ivp(dydt, t_span, y0, method='RK45', t_eval=t_eval)

def analytical_solution(t):
    return np.exp(-2 * t)

numerical_solution = sol.y[0]
analytical_solution_vals = analytical_solution(t_eval)
error = np.abs(numerical_solution - analytical_solution_vals)

plt.figure(figsize=(10, 6))  

plt.subplot(2, 1, 1) 
plt.plot(sol.t, numerical_solution, label='Numerical Solution (RK45)', linestyle='--')
plt.plot(t_eval, analytical_solution_vals, label='Analytical Solution', linestyle='-')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.title('Comparison of Numerical and Analytical Solutions')
plt.legend()

plt.subplot(2, 1, 2) 
plt.plot(t_eval, error, label='Error', color='red')
plt.xlabel('t')
plt.ylabel('Error')
plt.title('Error between Numerical and Analytical Solutions')
plt.tight_layout()

plt.show()
