Skip to content

Commit 96845d2

Browse files
Vexatosjiegillet
authored andcommitted
Implemented Thomas Algorithm in Crystal (#529)
1 parent 9a0e8c8 commit 96845d2

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+
def thomas(a, b, c, d)
2+
c_prime = c.dup
3+
x = d.dup
4+
5+
# Setting initial elements
6+
c_prime[0] /= b[0]
7+
x[0] /= b[0]
8+
9+
1.upto(a.size - 1) do |i|
10+
# Scale factor is for c_prime and x
11+
scale = 1.0 / (b[i] - c_prime[i - 1]*a[i])
12+
c_prime[i] *= scale
13+
x[i] = (x[i] - a[i] * x[i - 1]) * scale
14+
end
15+
16+
# Back-substitution
17+
(a.size - 2).downto(0) do |i|
18+
x[i] -= (c_prime[i] * x[i + 1])
19+
end
20+
21+
x
22+
end
23+
24+
def main
25+
a = [0.0, 2.0, 3.0]
26+
b = [1.0, 3.0, 6.0]
27+
c = [4.0, 5.0, 0.0]
28+
d = [7.0, 5.0, 3.0]
29+
30+
puts "The system"
31+
puts [b[0], c[0], "", "|", d[0]].join("\t")
32+
puts [a[1], b[1], c[1], "|", d[1]].join("\t")
33+
puts ["", a[2], b[2], "|", d[2]].join("\t")
34+
puts "Has the solution:"
35+
36+
soln = thomas(a, b, c, d)
37+
38+
puts soln.join("\t")
39+
end
40+
41+
main

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
123123
[import, lang:"c_cpp"](code/c++/thomas.cpp)
124124
{% sample lang="lua" %}
125125
[import, lang:"lua"](code/lua/thomas.lua)
126+
{% sample lang="crystal" %}
127+
[import, lang:"crystal"](code/crystal/thomas.cr)
126128
{% endmethod %}
127129

128130
<script>

0 commit comments

Comments
 (0)