Skip to content

thomas python example #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Chinmaya Mahesh
Unlambder
Kjetil Johannessen
CDsigma
Gammison
hsjoihs
DominikRafacz
lulucca12
42 changes: 42 additions & 0 deletions chapters/matrix_methods/thomas/code/python/thomas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Author: gammison

# note this example is inplace and destructive
def thomas(a, b, c, d):

#set the initial elements
c[0] = c[0] / b[0]
d[0] = d[0] / b[0]

n = len(d) #number of equations to solve
for i in range(1,n):
#scale factor for c and d
scale = 1 / (b[i] - c[i-1]*a[i])

c[i] = c[i] * scale
d[i] = (d[i] -a[i] * d[i-1]) * scale


# do the back substitution
for i in range(n-2,-1,-1):
d[i] = d[i] - c[i]*d[i+1]

return d

def main():
# example for matrix
# [1 4 0][x] [7]
# [2 3 5][y] = [5]
# [0 3 6][z] [3]
# [.8666]
# soln will equal [1.533]
# [-.266]
# note we index a from 1 and c from 0
a = [0, 2, 3]
b = [1, 3, 6]
c = [4, 5, 0]
d = [7, 5, 3]
soln = thomas(a, b, c, d)
print(soln)

if __name__ == '__main__':
main()
2 changes: 2 additions & 0 deletions chapters/matrix_methods/thomas/thomas.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ In code, this will look like this:
{% method %}
{% sample lang="jl" %}
[import, lang:"julia"](code/julia/thomas.jl)
{% sample lang="py" %}
[import, lang:"python"](code/python/thomas.py)
{% endmethod %}

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.
Expand Down