If you're trying to find the left hand side of a matrix equation Ax = b
, the inversion x=A^-1 b
is almost never the way to go about it. In most numerical systems you solve the equation for the left hand side. In python you can use scipy.linalg.solve to do this. (See https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve.html, referenced in Python: Is there a matlab-like backslash operator?)
For a 1000x1000 random, dense matrix there's about a 2x speedup, but if you have symmetries to exploit, as physical systems often do, you can get that faster.
import numpy as np
from scipy import linalg
from timeit import timeit
mat = np.random.random(1000000).reshape(1000,1000)
rhs = np.random.random(1000)
def lhs_byinversion(mat, rhs):
matinv = linalg.inv(mat)
lhs = matinv.dot(rhs)
return lhs
def lhs_bysolving(mat, rhs):
lhs = linalg.solve(mat, rhs)
return lhs
lhs1 = lhs_byinversion(mat, rhs)
lhs2 = lhs_bysolving(mat, rhs)
# these are equivalent solutions
print('difference in results')
print(np.sqrt(np.sum((lhs1-lhs2)**2)))
# 1.157200161145036e-12
# speed up depends on the actual matrices being used. If there are symmetries to exploit this can be greater
print('time for 100 inversions')
print(timeit('lhs = lhs_byinversion(mat, rhs)', globals=globals(), number=100))
# 1.7345171420020051
print('time for 100 solutions')
print(timeit('lhs = lhs_bysolving(mat, rhs)', globals=globals(), number=100))
# 0.9372443140018731