explicit euler Algorithm
The Explicit Euler Algorithm, also known as the Forward Euler Method, is a simple yet powerful numerical technique used to solve ordinary differential equations (ODEs). It falls under the category of single-step methods, as it estimates the solution of the ODE at each time step based on the information from the previous step. The primary advantage of the Explicit Euler Algorithm is its simplicity and ease of implementation, making it a popular choice for solving a wide range of problems in various fields, such as physics, engineering, and finance.
The algorithm works by iteratively advancing the solution in small time steps, with the size of the time step being a critical factor in the stability and accuracy of the method. To compute the solution at the next time step, the algorithm evaluates the derivative of the function at the current time step, multiplies it by the time step size, and adds the result to the current solution value. Despite its simplicity, the Explicit Euler Algorithm can suffer from instability and significant errors if the time step size is not chosen appropriately. This limitation has led to the development of more advanced numerical methods, such as the Implicit Euler Method and Runge-Kutta Methods, which often provide better stability and accuracy for solving ODEs.
import numpy as np
def explicit_euler(ode_func, y0, x0, step_size, x_end):
"""
Calculate numeric solution at each step to an ODE using Euler's Method
https://en.wikipedia.org/wiki/Euler_method
Arguments:
ode_func -- The ode as a function of x and y
y0 -- the initial value for y
x0 -- the initial value for x
stepsize -- the increment value for x
x_end -- the end value for x
>>> # the exact solution is math.exp(x)
>>> def f(x, y):
... return y
>>> y0 = 1
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
>>> y[-1]
144.77277243257308
"""
N = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((N + 1,))
y[0] = y0
x = x0
for k in range(N):
y[k + 1] = y[k] + step_size * ode_func(x, y[k])
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()