diff --git a/contents/forward_euler_method/code/coconut/euler.coco b/contents/forward_euler_method/code/coconut/euler.coco new file mode 100644 index 000000000..7297e9c51 --- /dev/null +++ b/contents/forward_euler_method/code/coconut/euler.coco @@ -0,0 +1,28 @@ +import math + +def forward_euler(time_step, n): + factors = [1] + [1 - 3 * time_step] * (n-1) + # We want all the cumulative values, thus the use of scan + return scan((*), factors) + + + +def check(result, threshold, time_step): + approx = True + # A scan object has a len if the underlying iterable has a len + solution = range(len(result)) |> map$(i -> math.exp(-3*i*time_step)) + for y, sol in zip(result, solution): + if not math.isclose(y, sol, abs_tol=threshold): + print(y, sol) + approx = False + return approx + + +if __name__ == '__main__': + time_step = 0.01 + n = 100 + threshold = 0.01 + + result = forward_euler(time_step, n) + approx = check(result, threshold, time_step) + print("All values within threshold") if approx else print("Value(s) not in threshold") diff --git a/contents/forward_euler_method/forward_euler_method.md b/contents/forward_euler_method/forward_euler_method.md index dfb185431..3547deb1c 100644 --- a/contents/forward_euler_method/forward_euler_method.md +++ b/contents/forward_euler_method/forward_euler_method.md @@ -146,6 +146,8 @@ Full code for the visualization follows: [import, lang:"nim"](code/nim/forwardeuler.nim) {% sample lang="lisp" %} [import, lang="lisp"](code/clisp/euler.lisp) +{%sample lang="coco" %} +[import, lang:"coconut"](code/coconut/euler.coco) {% endmethod %}