Menu Close

Euler’s Method | Python

Euler’s method is a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial value.

It is a simple and widely used method for approximating the solution of a first-order ODE at discrete time steps.

The idea behind Euler’s method is to approximate the solution of the ODE at discrete time steps by using the derivative at the current time step to estimate the solution at the next time step.

Here’s a simple example of how to use Euler’s method to solve the ODE dy/dx = -y with the initial value y(0) = 1:

Euler’s Method in Python

				
					import numpy as np

def euler_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 Method [By Bottom Science]
    
    # Iterate over the steps
    for i in range(1, len(x)):
        y[i] = y[i-1] + h*f(x[i-1], y[i-1])
        
    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_method(f, y0, x0, x_end, h)

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

More Related Stuff