-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler.py
80 lines (61 loc) · 1.75 KB
/
euler.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Euler's method iterative scheme to estimate ODE - EXPLICIT (Forward)
# and IMPLICIT (Backwards).
#
# You have to know the DERIVATIVE of the function to utilize this method
# Ex. you know dy/dx and a certain point like y(3) = 1.
#
# To run, use:
#
# import sympy as sym
# f = sym.Function('f')
# x1 = sym.Symbol('x1')
# x2 = sym.Symbol('x2')
# f = '''dy/dx equation with x1, x2 as x, y'''
# euler_forward(f, x0, y0, lower bound, upper bound, num steps)
# # euler_backward(f, x0, y0, lower bound, upper bound, num steps)
#
# Note: do not use x or y as values. Use x1, x2, etc.
#
# Output format: [y_values, total_time]
#
import sympy as sym
import time
def euler_forward(
f, x, y, a, b, n
) -> list: # function, x0, y0, lower bound, upper bound, num steps
x1 = sym.Symbol("x1")
x2 = sym.Symbol("x2")
start_time = time.time()
p = 0 # flag
h = (b - a) / n # step size
x_val = []
y_val = []
while p < n:
x_val.append(x)
y_val.append(y)
x += h
y = y + h * f.evalf(subs={x1: x, x2: y})
p += 1
end_time = time.time()
total_time = end_time - start_time
return [y_val, total_time]
def euler_backward(
f, x, y, a, b, n
) -> list: # function, x0, y0, lower bound, upper bound, num steps
x1 = sym.Symbol("x1")
x2 = sym.Symbol("x2")
start_time = time.time()
p = 0 # flag
h = (b - a) / n # step size
x_val = []
y_val = []
while p < n:
x_val.append(x)
y_val.append(y)
x += h
y_p = y + h * f.evalf(subs={x1: x, x2: y})
y = y + h * f.evalf(subs={x1: x + h, x2: y_p})
p += 1
end_time = time.time()
total_time = end_time - start_time
return [y_val, total_time]