
h the step size is critical, if it is chosen too big, the curve shape may be omitted causing error.
# Euler's method
# Redefining the Euler's method function and the differential equation
import numpy as np
import matplotlib.pyplot as plt
def euler_method(f, x0, y0, h, n_steps):
x_vals = [x0]
y_vals = [y0]
for _ in range(n_steps):
y0 = y0 + h * f(x0, y0)
x0 = x0 + h
x_vals.append(x0)
y_vals.append(y0)
return x_vals, y_vals
# Define the differential equation dy/dx = y - x^2 + 1
def f(x, y):
return y - x**2 + 1
# Initial conditions
x0, y0 = 0, 0.5
# Parameters for the method
h = 0.1
n_steps = 20
# Apply Euler's method again
x_vals, y_vals = euler_method(f, x0, y0, h, n_steps)
# Plotting the results
plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, 'b-o', label="Euler's Approximation")
plt.title("Euler's Method for ODE")
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
The shortcomings of Euler’s or Huen’s method are improved by widely used and versatile methods is the Runge-Kutta family of methods. The most commonly used member of the Runge-Kutta family is the 4th-order Runge-Kutta method, often referred to simply as the “RK4” method. It achieves higher accuracy by taking the average of four different approximations of the derivative over the interval. The increased accuracy usually comes at the cost of more computational effort, as the method requires four evaluations of the function per step.
