处理复数和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        ]])

Don't use np.matrix,这几乎总是错误的选择,特别是如果你使用 Python 3.5+。您应该使用 np.array.

此外,您忘记在值周围加上 [],所以您作为 "second row" 传入的 "thought" 实际上是第二个参数。 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        ]])