Skip to content

Commit 4f40ef0

Browse files
committed
Thomas Algorithm in Javascript
1 parent afcaf4d commit 4f40ef0

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// note this example is inplace and destructive
2+
thomas = (a, b, c, d) => {
3+
4+
// set the initial elements
5+
c[0] = c[0] / b[0]
6+
d[0] = d[0] / b[0]
7+
8+
n = d.length // number of equations to solve
9+
for (i = 1; i < n; i++) {
10+
scale = 1 / (b[i] - c[i-1] * a[i]) // scale factor for c and d
11+
c[i] *= scale
12+
d[i] = (d[i] - a[i] * d[i-1]) * scale
13+
}
14+
15+
// do the back substitution
16+
for (i = n-2; i >= 0; i--) {
17+
d[i] -= c[i] * d[i+1]
18+
}
19+
20+
return d
21+
}
22+
23+
/*
24+
example for matrix
25+
[1 4 0][x] [7]
26+
[2 3 5][y] = [5]
27+
[0 3 6][z] [3]
28+
29+
[.8666]
30+
soln will equal [1.533]
31+
[-.266]
32+
note we index a from 1 and c from 0
33+
*/
34+
35+
a = [0, 2, 3]
36+
b = [1, 3, 6]
37+
c = [4, 5, 0]
38+
d = [7, 5, 3]
39+
40+
soln = thomas(a, b, c, d)
41+
console.log(soln)

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
127127
[import, lang:"crystal"](code/crystal/thomas.cr)
128128
{% sample lang="kotlin" %}
129129
[import, lang:"kotlin"](code/kotlin/thomas.kt)
130+
{% sample lang="js" %}
131+
[import, lang:"javascript"](code/javascript/thomas.js
130132
{% endmethod %}
131133

132134
<script>

0 commit comments

Comments
 (0)