2017-09-21 6 views
3

私はそのために私は、この機能を使用し、マトリックスのpythonで、一体であるかどうかを確認する必要があります。複素数とnumpyを扱うときに、Pythonでdtypeを正しく指定する方法は?

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' 

ここでデータ型を使用する正しい方法は何ですか?

答えて

0

Don't use np.matrixは、それはあなたは、Python 3.5+を使用する場合は特に、ほとんど常に間違った選択です。むしろnp.arrayを使用してください。

さらに、値の周りに[]を入れるのを忘れてしまったので、「2行目」として渡したと思ったのは実際には2番目の引数でした。そしてarray(およびmatrix)のための第二引数はdtypeとしてnumpyので解釈されます

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  ]]) 
+0

ああ!角かっこ!ありがとう、それは働いた。私は配列の使用に切り替えます! –

+0

問題はありませんが、うまくいきました。最も有益な回答を[承諾する]ことを忘れないでください(https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 :) – MSeifert

0

matrixコンストラクタのみdtypeとしてデータとして最初引数、第二を取り、それがdtypeとして[-cmath.exp(-1j).conjugate(),complex(1/math.sqrt(2))]あなた二行目を見ているためです。

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  ]]) 
関連する問題