Menu Close

Euler’s Modified Method | Python

Euler’s modified method, also known as the improved Euler method, is a variation of Euler’s method that improves the accuracy of the solution.

It is a first-order method, but it uses the slope at the midpoint of the interval, rather than the slope at the starting point to estimate the value of the solution at the next time step.

Here is a simple example of how to implement Euler’s modified method in Python for solving the ODE dy/dx = -y with the initial value y(0) = 1:

Euler’s Modified Method in Python

				
					import numpy as np

def euler_modified_method(f, y0, x0, x_end, h):
    # Initialize the solution array
    x = np.arange(x0, x_end+h, h)
    y = np.zeros(len(x))
    y[0] = y0
    
    # Euler's Modified Method [By Bottom Science]
    
    # Iterate over the steps
    for i in range(1, len(x)):
        k1 = h*f(x[i-1], y[i-1])
        k2 = h*f(x[i-1] + h/2, y[i-1] + k1/2)
        y[i] = y[i-1] + k2
        
    return x, y

# Define the ODE function
def f(x, y):
    return -y

# Set the initial condition and the step size
y0 = 1
x0 = 0
x_end = 10
h = 0.1

# Solve the ODE
x, y = euler_modified_method(f, y0, x0, x_end, h)

for xx,yy in zip(x,y):
    print("x = ",xx," y = ",yy)

				
			

More Related Stuff