繁体   English   中英

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

[英]How to specify dtype correctly in python when dealing with complex numbers and numpy?

我需要检查一个矩阵在python中是否是单一的,因为我使用了这个函数:

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'

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

那是因为matrix构造函数只将第一个参数作为数据,第二个作为dtype ,所以它看到你的第二行 [-cmath.exp(-1j).conjugate(),complex(1/math.sqrt(2))]作为dtype

您需要传递嵌套列表,因此添加方括号:

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

或者更优雅:

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

然后产生:

>>> m1
matrix([[ 0.70710678+0.j        ,  0.54030231+0.84147098j],
        [-0.54030231-0.84147098j,  0.70710678+0.j        ]])

顺便说一句, array也适用于:

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

生产:

>>> m1
array([[ 0.70710678+0.j        ,  0.54030231+0.84147098j],
       [-0.54030231-0.84147098j,  0.70710678+0.j        ]])

不要使用np.matrix ,它几乎总是错误的选择,特别是如果你使用Python 3.5+。 你应该使用np.array

此外,你忘了把[]放在值的周围,所以你“认为”你传入的“第二行”实际上是第二个参数。 array (和matrix )的第二个参数由NumPy解释为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        ]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM