Skip to content

Commit e00884b

Browse files
c252berquist
authored andcommitted
added a nim implementation of the forward euler method (#543)
1 parent 5394d66 commit e00884b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import math
2+
3+
proc solveEuler(timestep: float, n: int): seq[float] =
4+
var res = newSeq[float](n)
5+
6+
res[0] = 1.0
7+
8+
for i in 1 .. n - 1:
9+
res[i] = res[i - 1] - 3 * res[i - 1] * timestep
10+
11+
return res
12+
13+
proc check(res: seq[float], timestep, threshold: float): bool =
14+
var approx: bool = true;
15+
16+
for i in 0 .. len(res) - 1:
17+
let solution: float = exp(-3.0 * float(i) * timestep)
18+
if abs(res[i]) - solution > threshold:
19+
echo res[i]
20+
echo solution
21+
approx = false
22+
23+
return approx
24+
25+
const
26+
timestep: float = 0.1
27+
n: int = 100
28+
threshold: float = 0.1
29+
eulerResult: seq[float] = solveEuler(timestep, n)
30+
approx: bool = check(eulerResult, threshold, timestep)
31+
32+
echo approx

contents/forward_euler_method/forward_euler_method.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ Full code for the visualization follows:
132132
[import, lang:"asm-x64"](code/asm-x64/euler.s)
133133
{% sample lang="java" %}
134134
[import, lang:"java"](code/java/ForwardEuler.java)
135+
{% sample lang="nim" %}
136+
[import, lang:"nim"](code/nim/forwardeuler.nim)
135137
{% endmethod %}
136138

137139
<script>

0 commit comments

Comments
 (0)