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

Viewed 603

I need to check whether a matrix is unitary in python, for that I use this function:

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

but when I'm trying to specify a matrix by:

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

I get a

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

What is the correct way of working with data types here?

2 Answers

That's because the matrix constructor only takes the first argument as data, and the second as dtype, so it sees your second row [-cmath.exp(-1j).conjugate(),complex(1/math.sqrt(2))] as dtype.

You need to pass a nested list, so add square brackets:

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

Or perhaps more elegant:

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

This then produces:

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

The same holds for array by the way:

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

producing:

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

Don't use np.matrix, it's almost always the wrong choice, especially if you use Python 3.5+. You should rather use np.array.

Besides, you forgot to put [ and ] around the values, so what you "thought" you passed in as "second row" was actually a second argument. And the second argument for array (and matrix) is interpreted by NumPy as the 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        ]])
Related