pls*_*alp 17 python numpy matrix python-3.x
我正在尝试使用(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
Run Code Online (Sandbox Code Playgroud)
虽然我一直收到一条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)
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏,谢谢!
Nil*_*ner 45
你可以简单地使用 allclose
def check_symmetric(a, rtol=1e-05, atol=1e-08):
return numpy.allclose(a, a.T, rtol=rtol, atol=atol)
Run Code Online (Sandbox Code Playgroud)
小智 15
下面的函数也解决了这个问题:
def check_symmetric(a, tol=1e-8):
return np.all(np.abs(a-a.T) < tol)
Run Code Online (Sandbox Code Playgroud)
这是一篇旧文章,但我会推荐另一种方法。特别是对于稀疏矩阵,这可以快数百倍。
def is_symmetric(A, tol=1e-8):
return scipy.sparse.linalg.norm(A-A.T, scipy.Inf) < tol;
Run Code Online (Sandbox Code Playgroud)
或者类似,但你明白了。使用范数是一种更加优化的计算。
| 归档时间: |
|
| 查看次数: |
20967 次 |
| 最近记录: |