forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler_modified.py
More file actions
Latest commit
54 lines (43 loc) · 1.4 KB
/
Copy patheuler_modified.py
File metadata and controls
54 lines (43 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
fromcollections.abcimportCallable
importnumpyasnp
defeuler_modified(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
) ->np.array:
"""
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 -- 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 f1(x, y):
... return -2*x*(y**2)
>>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0)
>>> y[-1]
0.503338255442106
>>> import math
>>> def f2(x, y):
... return -2*y + (x**3)*math.exp(-2*x)
>>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3)
>>> y[-1]
0.5525976431951775
"""
n=int(np.ceil((x_end-x0) /step_size))
y=np.zeros((n+1,))
y[0] =y0
x=x0
forkinrange(n):
y_get=y[k] +step_size*ode_func(x, y[k])
y[k+1] =y[k] + (
(step_size/2) * (ode_func(x, y[k]) +ode_func(x+step_size, y_get))
)
x+=step_size
returny
if__name__=="__main__":
importdoctest
doctest.testmod()