Lets say I define a big quadratic matrix (e.g. 150x150). One time it is a numpy array (matrix A), one time it is a scipy sparse array (matrix B).
import numpy as np
import scipy as sp
from scipy.sparse.linalg import spsolve
size = 150
A = np.zeros((size, size))
length = 1000
# Set some random numbers at random places
A[np.random.randint(0, size, (2, length)).tolist()] = \
np.random.randint(0, size, (length, ))
B = sp.sparse.csc_matrix(A)
Now I calculate the inverse of both matrices. For matrix B I use both methods for calculating the inverse (sp.sparse.linalg.inv
and spsolve
).
epsilon = 10.**-8 # Is needed to prevent singularity of each matrix
inv_A = np.linalg.pinv(A+np.eye(size)*epsilon)
inv_B = sp.sparse.linalg.inv(B+sp.sparse.identity(size)*epsilon)
inv_B2 = spsolve(B+sp.sparse.identity(size)*epsilon, sp.sparse.identity(size))
To check if both inverses of A and B are equal, I will sum up the differences squared.
# Is not equal zero, question: Why?
# Sometimes very small (~+-10**-27), sometimes very big (~+-10**5)
print("np.sum((inv_A - inv_B)**2): {}".format(np.sum((inv_A - inv_B)**2)))
# Should be zero
print("np.sum((inv_B - inv_B2)**2): {}".format(np.sum((inv_B - inv_B2)**2)))
The problem is this: If I use small matrices, e.g. 10x10, the error between numpy as scipy inverse functions is very small (approx. ~+-10**-32). But I need the sparse version for big matrices (e.g. 500x500).
Am I doing here something wrong, or is there any possibility to calc the correct inverse of a sparse matrix in python?
np.allclose
is a convenient tool for checking float equality. – hpaulj