简体   繁体   中英

Checking if a matrix is symmetric in Numpy

I'm trying to make a function with the arguments (a,tol=1e-8) that returns a boolean value that tells the user whether or not the matrix is symmetric (symmetric matrix is equal to its transpose). So far I have:

def check_symmetric(a, tol=1e-8):
if np.transpose(a, axes=axes) == np.transpose(a, axes=axes):
    return True
def sqr(s):
    rows = len(s)
    for row in sq:
        if len(row) != rows:
            return False
    return True
if a != sqr(s):
    raise ValueError

although I keep getting an axes isn't defined message so I'm pretty sure that doesn't work at all...... the tests I'd like to pass are:

e = np.eye(4)
f = np.diag([1], k=3)
g = e[1:, :]

print(check_symmetric(e))
print(not check_symmetric(e + f))
print(check_symmetric(e + f * 1e-9))
print(not check_symmetric(e + f * 1e-9, 1e-10))
try:
    check_symmetric(g)
    print(False)
except ValueError:
    print(True)

Any help is appreciated, thanks!

You can simply compare it to its transpose using allclose

def check_symmetric(a, rtol=1e-05, atol=1e-08):
    return numpy.allclose(a, a.T, rtol=rtol, atol=atol)

The following function also solves the problem:

def check_symmetric(a, tol=1e-8):
    return np.all(np.abs(a-a.T) < tol)

This is an old post but I wold recommend another method. Especially for sparse matrices, this can be hundreds of times faster.

def is_symmetric(A, tol=1e-8):
    return scipy.sparse.linalg.norm(A-A.T, scipy.Inf) < tol;

Or similar but you get the idea. Using a norm is a much more optimized calculation.

If you're not worried about the tot threshold

(a==a.T).all()

is the simplest solution. This works for N-dimensional (N>2) arrays as well.

If using SciPy is acceptable, you can use scipy.linalg.issymmetric() (as of v1.8.0), which also includes some input validation.

  • See implementation here .
  • A note regarding performance (from the docs; emphasis mine):

    When atol and/or rtol are set, then the comparison is performed by numpy.allclose and the tolerance values are passed to it. Otherwise, an exact comparison against zero is performed by internal functions . Hence performance can improve or degrade depending on the size and dtype of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM