CaptainKP
CaptainKP

Reputation: 1

Trouble inverting a matrix in python

I have a matrix in python that I am trying to invert. However, the result of multiplying the inverted matrix by the original matrix does not yield the identity matrix.

M = np.matrix(cv)
invM = np.linalg.inv(M)
M@invM

image showing result of matrix multiplication

I am not sure what could be the problem since this is a fairly simple operation. Has anyone else had this problem? or does anyone know how to fix this? Thanks!

Upvotes: 0

Views: 272

Answers (2)

Han-Kwang Nienhuys
Han-Kwang Nienhuys

Reputation: 3254

Likely, your matrix is ill-conditioned, which means that the matrix is close to noninvertible. You can check the condition number of your matrix using this:

np.linalg.cond(M)

The relative precision of double-precision floats is about 1e-16. For a condition number K, you lose about a factor K in precision. If K is above 1e+15, the matrix is noninvertible for practical purposes.

If you want to solve A @ x = b for x, it is often more accurate to use x = np.linalg.solve(A, b) rather than x = np.linalg.inv(A) @ b.

Here are a few matrices with different condition numbers and the quality of their inverse:

import numpy as np
np.random.seed(1)
n = 100

def test_inv(a):
    print(f'Condition number: {np.linalg.cond(a):.3g}')
    max_err = np.abs(a @ np.linalg.inv(a) - np.eye(n)).max()
    print(f'a @ a_inv - eye: maximum error = {max_err:.3g}')    

# identity matrix
test_inv(np.eye(n))

# random numbers
randmat = np.random.uniform(-1, 1, size=(n, n))
test_inv(randmat)

# random numbers, but one row is almost a linear combination of
# two other rows.
badmat = randmat.copy()
badmat[1, :] = badmat[0, :] + badmat[2, :] - 1e-9
test_inv(badmat)

The output:

Condition number: 1
a @ a_inv - eye: maximum error = 0
Condition number: 626
a @ a_inv - eye: maximum error = 2.84e-14
Condition number: 1.64e+10
a @ a_inv - eye: maximum error = 1.53e-06

Upvotes: 2

biplob biswas
biplob biswas

Reputation: 104

m = np.matrix([[2,3],[4,5]])
n = m.I
i = m@n
print(i)

out:
[[1. 0.]
 [0. 1.]]

Try this way.

Upvotes: 0

Related Questions