python判断整数是否对称_在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)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值