处理复数和numpy时如何在python中正确指定dtype?

非化学家

我需要检查矩阵在python中是否为unit,为此我使用了以下功能:

def is_unitary(m):
    return np.allclose(np.eye(m.shape[0]), m.H * m)

但是当我尝试通过以下方式指定矩阵时:

m1=np.matrix([complex(1/math.sqrt(2)),cmath.exp(1j)],[-cmath.exp(-1j).conjugate(),complex(1/math.sqrt(2))],dtype=complex)

我得到一个

TypeError: __new__() got multiple values for argument 'dtype'

这里使用数据类型的正确方法是什么?

塞弗特

不要使用np.matrix,这几乎总是错误的选择,尤其是在使用Python 3.5+的情况下。您应该使用np.array

再说了,你忘了[]周围的价值观,所以你“想”你“第二排”传入实际上是第二个参数。NumPy将array(和matrix的第二个参数解释为dtype

np.array([[complex(1/math.sqrt(2)),     cmath.exp(1j)          ],
          [-cmath.exp(-1j).conjugate(), complex(1/math.sqrt(2))]],
         dtype=complex)
# array([[ 0.70710678+0.j        ,  0.54030231+0.84147098j],
#        [-0.54030231-0.84147098j,  0.70710678+0.j        ]])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章