File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed
contents/thomas_algorithm Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ # note this example is inplace and destructive
2+ def thomas ( a , b , c , d )
3+ # set the initial elements
4+ c [ 0 ] = c [ 0 ] / b [ 0 ]
5+ d [ 0 ] = d [ 0 ] / b [ 0 ]
6+
7+ n = d . length # number of equations to solve
8+ ( 1 ...n ) . each do |i |
9+ scale = 1 / ( b [ i ] - c [ i - 1 ] * a [ i ] ) # scale factor for c and d
10+ c [ i ] *= scale
11+ d [ i ] = ( d [ i ] - a [ i ] * d [ i - 1 ] ) * scale
12+ end
13+
14+ # do the back substitution
15+ ( n - 2 ) . downto ( 0 ) . each do |j |
16+ d [ j ] -= c [ j ] * d [ j + 1 ]
17+ end
18+
19+ d
20+ end
21+
22+ # example for matrix
23+ # [1 4 0][x] [7]
24+ # [2 3 5][y] = [5]
25+ # [0 3 6][z] [3]
26+
27+ # [.8666]
28+ # soln will equal [1.533]
29+ # [-.266]
30+ # note we index a from 1 and c from 0
31+
32+ a = [ 0.0 , 2.0 , 3.0 ]
33+ b = [ 1.0 , 3.0 , 6.0 ]
34+ c = [ 4.0 , 5.0 , 0.0 ]
35+ d = [ 7.0 , 5.0 , 3.0 ]
36+
37+ soln = thomas ( a , b , c , d )
38+ puts soln
Original file line number Diff line number Diff line change @@ -129,6 +129,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
129129[ import, lang:"crystal"] ( code/crystal/thomas.cr )
130130{% sample lang="kotlin" %}
131131[ import, lang:"kotlin"] ( code/kotlin/thomas.kt )
132+ {% sample lang="ruby" %}
133+ [ import, lang="ruby"] ( code/ruby/thomas.rb )
132134{% endmethod %}
133135
134136<script >
You can’t perform that action at this time.
0 commit comments