问题
As part of a python code for a numerical calculation, I must invert somewhat large (sparse) matrices (~100x100) many times. I would really like to speed up the program, and one of the ways suggested to me is to call to a subroutine in C for the matrix inversion step.
Are there any recommended efficient and well-tested C routines for this task?
Thank you.
回答1:
>>> from numpy import *
>>> from numpy.linalg import inv
>>> from scipy.sparse import csr_matrix
>>> m = matrix([[3,1,5],[1,0,8],[2,1,4]])
>>> s = csr_matrix(m)
>>> invs = inv(a) # Inverse sparse matrix
>>> dot(a,inva) # Check the result, should be eye(3) within machine precision
csr_matrix([[ 1.00000000e-00, 2.77555756e-17, 3.60822483e-16],
[ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00],
[ -1.11022302e-16, 0.00000000e+00, 1.00000000e+00]])
Is it really the inverse you need? You may be able to achieve your goal without inversion:
Cases where you really need the inverse are rare. Moreover, the inverse of a sparse matrix is not necessarily sparse. Typically, inverting is more expensive than an LU factorization and prone to rounding errors.
-- http://mail.scipy.org/pipermail/scipy-user/2007-October/013936.html
--> http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.factorized.html#scipy.sparse.linalg.factorized
来源:https://stackoverflow.com/questions/11184037/good-matrix-inversion-routines-in-c