Skip to content

Instantly share code, notes, and snippets.

@nyameko
Forked from cbellei/TDMAsolver.py
Created June 15, 2018 13:58
Show Gist options
  • Save nyameko/21d70aa858c67b965cefc2cf01da13b5 to your computer and use it in GitHub Desktop.
Save nyameko/21d70aa858c67b965cefc2cf01da13b5 to your computer and use it in GitHub Desktop.
Tridiagonal Matrix Algorithm solver in Python
import numpy as np
## Tri Diagonal Matrix Algorithm(a.k.a Thomas algorithm) solver
def TDMAsolver(a, b, c, d):
'''
TDMA solver, a b c d can be NumPy array type or Python list type.
refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
and to http://www.cfd-online.com/Wiki/Tridiagonal_matrix_algorithm_-_TDMA_(Thomas_algorithm)
'''
nf = len(d) # number of equations
ac, bc, cc, dc = map(np.array, (a, b, c, d)) # copy arrays
for it in xrange(1, nf):
mc = ac[it-1]/bc[it-1]
bc[it] = bc[it] - mc*cc[it-1]
dc[it] = dc[it] - mc*dc[it-1]
xc = bc
xc[-1] = dc[-1]/bc[-1]
for il in xrange(nf-2, -1, -1):
xc[il] = (dc[il]-cc[il]*xc[il+1])/bc[il]
return xc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment