Skip to content

Commit 9b4cb05

Browse files
Modified Euler's Method (#5258)
* Magnitude and Angle Core function to find Magnitude and Angle of two Given Vector * Magnitude and Angle with Doctest added Doctest to the functions * Update linear_algebra/src/lib.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update linear_algebra/src/lib.py Co-authored-by: Christian Clauss <cclauss@me.com> * Changes done and Magnitude and Angle Issues * black * Modified Euler's Method Adding Modified Euler's method, which was the further change to a Euler method and known for better accuracy to the given value * Modified Euler's Method (changed the typing of function) Modified function is used for better accuracy * Link added Added link to an explanation as per Contributions Guidelines * Resolving Pre-Commit error * Pre-Commit Error Resolved * Pre-Commit Error import statement Change * Removed Import Math * import math built issue * adding space pre-commit error * statement sorter for doc Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 943e03f commit 9b4cb05

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

maths/euler_modified.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from typing import Callable
2+
3+
import numpy as np
4+
5+
6+
def euler_modified(
7+
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
8+
) -> np.array:
9+
"""
10+
Calculate solution at each step to an ODE using Euler's Modified Method
11+
The Euler is straightforward to implement, but can't give accurate solutions.
12+
So, they Proposed some changes to improve the 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+
>>> 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+
>>> 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+
51+
if __name__ == "__main__":
52+
import doctest
53+
54+
doctest.testmod()

0 commit comments

Comments
 (0)