I was wondering if there is any function in numpy to determine whether a matrix is Unitary?
This is the function I wrote but it is not working. I would be thankful if you guys can find an error in my function and/or tell me another way to find out if a given matrix is unitary.
def is_unitary(matrix: np.ndarray) -> bool:unitary = Truen = matrix.sizeerror = np.linalg.norm(np.eye(n) - matrix.dot( matrix.transpose().conjugate()))if not(error < np.finfo(matrix.dtype).eps * 10.0 *n):unitary = Falsereturn unitary
Let's take an obviously unitary array:
>>> a = 0.7
>>> b = (1-a**2)**0.5
>>> m = np.array([[a,b],[-b,a]])
>>> m.dot(m.conj().T)
array([[ 1., 0.],[ 0., 1.]])
and try your function on it:
>>> is_unitary(m)
Traceback (most recent call last):File "<ipython-input-28-8dc9ddb462bc>", line 1, in <module>is_unitary(m)File "<ipython-input-20-3758c2016b67>", line 5, in is_unitaryerror = np.linalg.norm(np.eye(n) - matrix.dot( matrix.transpose().conjugate()))
ValueError: operands could not be broadcast together with shapes (4,4) (2,2)
which happens because
>>> m.size
4
>>> np.eye(m.size)
array([[ 1., 0., 0., 0.],[ 0., 1., 0., 0.],[ 0., 0., 1., 0.],[ 0., 0., 0., 1.]])
If we replace n = matrix.size
with len(m)
or m.shape[0]
or something, we get
>>> is_unitary(m)
True
I might just use
>>> np.allclose(np.eye(len(m)), m.dot(m.T.conj()))
True
where allclose
has rtol
and atol
parameters.