{ } Raw JSON

bundles / numpy 2.4.4 / numpy / linalg / inv

_ArrayFunctionDispatcher

numpy.linalg:inv

source: /numpy/linalg/_linalg.py:536

Signature

def inv(a)

Summary

Compute the inverse of a matrix.

Extended Summary

Given a square matrix a, return the matrix ainv satisfying a @ ainv = ainv @ a = eye(a.shape[0]).

Parameters

a : (..., M, M) array_like

Matrix to be inverted.

Returns

ainv : (..., M, M) ndarray or matrix

Inverse of the matrix a.

Raises

: LinAlgError

If a is not square or inversion fails.

Notes

Broadcasting rules apply, see the numpy.linalg documentation for details.

If a is detected to be singular, a LinAlgError is raised. If a is ill-conditioned, a LinAlgError may or may not be raised, and results may be inaccurate due to floating-point errors.

Examples

import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2.], [3., 4.]])
ainv = inv(a)
np.allclose(a @ ainv, np.eye(2))
np.allclose(ainv @ a, np.eye(2))
✓
True
If a is a matrix object, then the return value is a matrix as well:
ainv = inv(np.matrix(a))
ainv
✓
matrix([[-2. ,  1. ],
        [ 1.5, -0.5]])
Inverses of several matrices can be computed at once:
a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
✓
inv(a)
✗
array([[[-2.  ,  1.  ],
        [ 1.5 , -0.5 ]],

       [[-1.25,  0.75],
        [ 0.75, -0.25]]])
If a matrix is close to singular, the computed inverse may not satisfy ``a @ ainv = ainv @ a = eye(a.shape[0])`` even if a `LinAlgError` is not raised:
a = np.array([[2,4,6],[2,0,2],[6,8,14]])
✓
inv(a)  # No errors raised
a @ inv(a)
✗
array([[ 0.  ,  0.  ,  0.  ],
       [-0.5 ,  0.75,  0.25],
       [ 0.  ,  0.  ,  1.  ]])
To detect ill-conditioned matrices, you can use `numpy.linalg.cond` to compute its *condition number* [1]_. The larger the condition number, the more ill-conditioned the matrix is. As a rule of thumb, if the condition number ``cond(a) = 10**k``, then you may lose up to ``k`` digits of accuracy on top of what would be lost to the numerical method due to loss of precision from arithmetic methods.
from numpy.linalg import cond
✓
cond(a)
✗
np.float64(6.326316942768597e+16)
It is also possible to detect ill-conditioning by inspecting the matrix's singular values directly. The ratio between the largest and the smallest singular value is the condition number:
from numpy.linalg import svd
sigma = svd(a, compute_uv=False)  # Do not compute singular vectors
✓
sigma.max()/sigma.min()
✗
np.float64(6.326316942768597e+16)

See also

numpy.linalg.cond

Compute the condition number of a matrix.

numpy.linalg.svd

Compute the singular value decomposition of a matrix.

scipy.linalg.inv

Similar function in SciPy.

Aliases

  • numpy.linalg.inv

Referenced by