在Numpy中检查矩阵是否对称 [英] Checking if a matrix is symmetric in Numpy
本文介绍了在Numpy中检查矩阵是否对称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用参数(a,tol=1e-8)
创建一个函数,该函数返回一个布尔值,该布尔值告诉用户矩阵是否对称(对称矩阵等于其转置矩阵).到目前为止,我有:
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
尽管我一直收到一条axes isn't defined
消息,所以我很确定这根本不起作用……我想通过的测试是:
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)
感谢您的帮助,谢谢!
推荐答案
您可以简单地使用allclose
def check_symmetric(a, rtol=1e-05, atol=1e-08):
return numpy.allclose(a, a.T, rtol=rtol, atol=atol)
这篇关于在Numpy中检查矩阵是否对称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文