Skip to content

added a nim implementation of the forward euler method #543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions contents/forward_euler_method/code/nim/forwardeuler.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import math

proc solveEuler(timestep: float, n: int): seq[float] =
var res = newSeq[float](n)

res[0] = 1.0

for i in 1 .. n - 1:
res[i] = res[i - 1] - 3 * res[i - 1] * timestep

return res

proc check(res: seq[float], timestep, threshold: float): bool =
var approx: bool = true;

for i in 0 .. len(res) - 1:
let solution: float = exp(-3.0 * float(i) * timestep)
if abs(res[i]) - solution > threshold:
echo res[i]
echo solution
approx = false

return approx

const
timestep: float = 0.1
n: int = 100
threshold: float = 0.1
eulerResult: seq[float] = solveEuler(timestep, n)
approx: bool = check(eulerResult, threshold, timestep)

echo approx
2 changes: 2 additions & 0 deletions contents/forward_euler_method/forward_euler_method.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ Full code for the visualization follows:
[import, lang:"asm-x64"](code/asm-x64/euler.s)
{% sample lang="java" %}
[import, lang:"java"](code/java/ForwardEuler.java)
{% sample lang="nim" %}
[import, lang:"nim"](code/nim/forwardeuler.nim)
{% endmethod %}

<script>
Expand Down