Skip to content

Commit 62d0ceb

Browse files
Amarasberquist
authored andcommitted
Forward Euler method, version 2.2: as functional as I could make it (for now)
1 parent bf7923a commit 62d0ceb

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

contents/forward_euler_method/code/coconut/euler.coco

+9-8
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
import math
22

33
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+
88

99

1010
def check(result, threshold, time_step):
1111
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)
1617
approx = False
1718
return approx
1819

contents/forward_euler_method/forward_euler_method.md

+2
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,8 @@ Full code for the visualization follows:
146146
[import, lang:"nim"](code/nim/forwardeuler.nim)
147147
{% sample lang="lisp" %}
148148
[import, lang="lisp"](code/clisp/euler.lisp)
149+
{%sample lang="coco" %}
150+
[import, lang:"coconut"](code/coconut/euler.coco)
149151
{% endmethod %}
150152

151153
<script>

0 commit comments

Comments
 (0)