Skip to content

Commit 05a9720

Browse files
Amarasberquist
authored andcommitted
Forward Euler method, version 2
1 parent 3060849 commit 05a9720

File tree

1 file changed

+9
-5
lines changed
  • contents/forward_euler_method/code/coconut

1 file changed

+9
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import numpy as np
1+
import math
22

33
def forward_euler(time_step, n):
44
y = 1
@@ -8,16 +8,20 @@ def forward_euler(time_step, n):
88

99

1010
def check(result, threshold, time_step):
11-
x = np.linspace(0, 1, 1 / time_step)
12-
solution = np.exp(-3 * x)
13-
return np.abs(solution - result) <= threshold).all()
11+
approx = True
12+
for i, y in enumerate(result):
13+
solution = math.exp(-3 * i * time_step)
14+
if not math.isclose(y, solution, abs_tol=threshold):
15+
print(y, solution)
16+
approx = False
17+
return approx
1418

1519

1620
if __name__ == '__main__':
1721
time_step = 0.01
1822
n = 100
1923
threshold = 0.01
2024

21-
result = np.array(list(forward_euler(time_step, n)))
25+
result = list(forward_euler(time_step, n))
2226
approx = check(result, threshold, time_step)
2327
print("All values within threshold") if approx else print("Value(s) not in threshold")

0 commit comments

Comments
 (0)