Python 检查矩阵在Numpy中是否对称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42908334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:15:21  来源:igfitidea点击:

Checking if a matrix is symmetric in Numpy

pythonpython-3.xnumpymatrix

提问by plshalp

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:

我正在尝试使用(a,tol=1e-8)返回一个布尔值的参数创建一个函数,该值告诉用户矩阵是否对称(对称矩阵等于其转置)。到目前为止,我有:

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 definedmessage so I'm pretty sure that doesn't work at all...... the tests I'd like to pass are:

虽然我不断收到一条axes isn't defined消息,所以我很确定这根本不起作用......我想通过的测试是:

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!

任何帮助表示赞赏,谢谢!

回答by Nils Werner

You can simply compare it to its transpose using allclose

您可以简单地将它与它的转置进行比较 allclose

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

回答by Andrés Marulanda

The following function also solves the problem:

下面的函数也解决了这个问题:

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