Skip to content

Commit 93c1cd9

Browse files
c252berquist
authored andcommitted
added thomas alg in nim (#399)
implemented thomas algorithm in nim
1 parent fc53db1 commit 93c1cd9

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
proc thomas_algorithm(a, b, c_in, d_in: seq[float]): seq[float] =
2+
3+
let n: int = len(d_in)
4+
5+
var c: seq[float] = c_in
6+
var d: seq[float] = d_in
7+
8+
c[0] /= b[0]
9+
d[0] /= b[0]
10+
11+
for i in 1..n - 1:
12+
let scale: float = (1 / (b[i] - c[i - 1] * a[i]))
13+
14+
c[i] *= scale
15+
d[i] = (d[i] - a[i] * d[i - 1]) * scale
16+
17+
for i in countdown(n - 2,0):
18+
d[i] -= c[i] * d[i + 1]
19+
20+
21+
return d
22+
23+
24+
const x: seq[float] = @[0.0, 2.0, 3.0]
25+
const y: seq[float] = @[1.0, 3.0, 6.0]
26+
const z: seq[float] = @[4.0, 5.0, 0.0]
27+
const w: seq[float] = @[7.0, 5.0, 3.0]
28+
29+
echo "The system,"
30+
echo "[1.0 4.0 0.0][x] = [7.0]"
31+
echo "[2.0 3.0 5.0][y] = [5.0]"
32+
echo "[0.0 3.0 6.0][z] = [3.0]"
33+
34+
echo "has the solution:"
35+
36+
const soln: seq[float] = thomas_algorithm(x, y, z, w)
37+
38+
for i in 0..len(w) - 1:
39+
echo soln[i]

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
113113
[import, lang:"haskell"](code/haskell/thomas.hs)
114114
{% sample lang="swift" %}
115115
[import, lang:"swift"](code/swift/thomas.swift)
116+
{%sample lang="nim" %}
117+
[import, lang:"nim"](code/nim/thomas_algorithm.nim)
116118
{% sample lang="cpp" %}
117119
[import, lang:"c_cpp"](code/c++/thomas.cpp)
118120
{% endmethod %}

0 commit comments

Comments
 (0)