MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / euler_modified

Function euler_modified

maths/euler_modified.py:6–48  ·  view source on GitHub ↗

Calculate solution at each step to an ODE using Euler's Modified Method The Euler Method is straightforward to implement, but can't give accurate solutions. So, some changes were proposed to improve accuracy. https://en.wikipedia.org/wiki/Euler_method Arguments: ode_func -

(
    ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
)

Source from the content-addressed store, hash-verified

4
5
6def euler_modified(
7 ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
8) -> np.ndarray:
9 """
10 Calculate solution at each step to an ODE using Euler's Modified Method
11 The Euler Method is straightforward to implement, but can't give accurate solutions.
12 So, some changes were proposed to improve accuracy.
13
14 https://en.wikipedia.org/wiki/Euler_method
15
16 Arguments:
17 ode_func -- The ode as a function of x and y
18 y0 -- the initial value for y
19 x0 -- the initial value for x
20 stepsize -- the increment value for x
21 x_end -- the end value for x
22
23 >>> # the exact solution is math.exp(x)
24 >>> def f1(x, y):
25 ... return -2*x*(y**2)
26 >>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0)
27 >>> float(y[-1])
28 0.503338255442106
29 >>> import math
30 >>> def f2(x, y):
31 ... return -2*y + (x**3)*math.exp(-2*x)
32 >>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3)
33 >>> float(y[-1])
34 0.5525976431951775
35 """
36 n = int(np.ceil((x_end - x0) / step_size))
37 y = np.zeros((n + 1,))
38 y[0] = y0
39 x = x0
40
41 for k in range(n):
42 y_get = y[k] + step_size * ode_func(x, y[k])
43 y[k + 1] = y[k] + (
44 (step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get))
45 )
46 x += step_size
47
48 return y
49
50
51if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

ceilMethod · 0.80

Tested by

no test coverage detected