Skip to content

Commit 2d8d2ef

Browse files
gammisonButt4cak3
authored andcommitted
thomas python example (#191)
1 parent 2a8bf4d commit 2d8d2ef

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Chinmaya Mahesh
1313
Unlambder
1414
Kjetil Johannessen
1515
CDsigma
16+
Gammison
1617
hsjoihs
1718
DominikRafacz
1819
lulucca12
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Author: gammison
2+
3+
# note this example is inplace and destructive
4+
def thomas(a, b, c, d):
5+
6+
#set the initial elements
7+
c[0] = c[0] / b[0]
8+
d[0] = d[0] / b[0]
9+
10+
n = len(d) #number of equations to solve
11+
for i in range(1,n):
12+
#scale factor for c and d
13+
scale = 1 / (b[i] - c[i-1]*a[i])
14+
15+
c[i] = c[i] * scale
16+
d[i] = (d[i] -a[i] * d[i-1]) * scale
17+
18+
19+
# do the back substitution
20+
for i in range(n-2,-1,-1):
21+
d[i] = d[i] - c[i]*d[i+1]
22+
23+
return d
24+
25+
def main():
26+
# example for matrix
27+
# [1 4 0][x] [7]
28+
# [2 3 5][y] = [5]
29+
# [0 3 6][z] [3]
30+
# [.8666]
31+
# soln will equal [1.533]
32+
# [-.266]
33+
# note we index a from 1 and c from 0
34+
a = [0, 2, 3]
35+
b = [1, 3, 6]
36+
c = [4, 5, 0]
37+
d = [7, 5, 3]
38+
soln = thomas(a, b, c, d)
39+
print(soln)
40+
41+
if __name__ == '__main__':
42+
main()

chapters/matrix_methods/thomas/thomas.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ In code, this will look like this:
4040
{% method %}
4141
{% sample lang="jl" %}
4242
[import, lang:"julia"](code/julia/thomas.jl)
43+
{% sample lang="py" %}
44+
[import, lang:"python"](code/python/thomas.py)
4345
{% endmethod %}
4446

4547
This is a much simpler implementation than Gaussian Elimination and only has one for loop before back-substitution, which is why it has a better complexity case.

0 commit comments

Comments
 (0)