【问题标题】:How to specify dtype correctly in python when dealing with complex numbers and numpy?处理复数和numpy时如何在python中正确指定dtype?
【发布时间】:2017-09-21 21:04:18
【问题描述】:

我需要检查一个矩阵在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'

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

【问题讨论】:

    标签: python python-3.x numpy linear-algebra complex-numbers


    【解决方案1】:

    Don't use 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        ]])
    

    【讨论】:

    • 哦!括号!谢谢,它奏效了。我将改用数组!
    • 没问题,我很高兴它有效。请不要忘记accept 最有帮助的答案。 :)
    【解决方案2】:

    这是因为 matrix 构造函数只将 first 参数作为数据,第二个作为 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        ]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2013-09-09
      • 2018-09-19
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多