File tree 2 files changed +11
-8
lines changed
contents/forward_euler_method
2 files changed +11
-8
lines changed Original file line number Diff line number Diff line change 1
1
import math
2
2
3
3
def forward_euler(time_step, n):
4
- y = 1
5
- for _ in range(n):
6
- yield y
7
- y *= (1 - 3 * time_step)
4
+ factors = [1] + [1 - 3 * time_step] * (n-1)
5
+ # We want all the cumulative values, thus the use of scan
6
+ return scan((*), factors)
7
+
8
8
9
9
10
10
def check(result, threshold, time_step):
11
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)
12
+ # A scan object has a len if the underlying iterable has a len
13
+ solution = range(len(result)) |> map$(i -> math.exp(-3*i*time_step))
14
+ for y, sol in zip(result, solution):
15
+ if not math.isclose(y, sol, abs_tol=threshold):
16
+ print(y, sol)
16
17
approx = False
17
18
return approx
18
19
Original file line number Diff line number Diff line change @@ -146,6 +146,8 @@ Full code for the visualization follows:
146
146
[ import, lang:"nim"] ( code/nim/forwardeuler.nim )
147
147
{% sample lang="lisp" %}
148
148
[ import, lang="lisp"] ( code/clisp/euler.lisp )
149
+ {%sample lang="coco" %}
150
+ [ import, lang:"coconut"] ( code/coconut/euler.coco )
149
151
{% endmethod %}
150
152
151
153
<script >
You can’t perform that action at this time.
0 commit comments