2016-01-25 63 views
0

我想知道numpy中是否有任何函数来确定矩阵是否是单一的?有没有方法在numpy测试一个矩阵是否是单一的

这是我写的功能,但它不工作。如果你们能够在我的功能中发现错误,并且/或者告诉我另一种方法来查明给定的矩阵是否是单一的,我会很感激。

def is_unitary(matrix: np.ndarray) -> bool: 

    unitary = True 
    n = matrix.size 
    error = np.linalg.norm(np.eye(n) - matrix.dot(matrix.transpose().conjugate())) 

    if not(error < np.finfo(matrix.dtype).eps * 10.0 *n): 
     unitary = False 

    return unitary 

回答

2

让我们举一个明显的单一阵列:

>>> 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.]]) 

,并尝试在它的功能:

>>> 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_unitary 
    error = np.linalg.norm(np.eye(n) - matrix.dot(matrix.transpose().conjugate())) 
ValueError: operands could not be broadcast together with shapes (4,4) (2,2) 

这是因为

>>> m.size 
4 
>>> np.eye(m.size) 
array([[ 1., 0., 0., 0.], 
     [ 0., 1., 0., 0.], 
     [ 0., 0., 1., 0.], 
     [ 0., 0., 0., 1.]]) 

如果我们更换n = matrix.size无线日len(m)m.shape[0]什么的,我们得到

>>> is_unitary(m) 
True 

我可能只是使用

>>> np.allclose(np.eye(len(m)), m.dot(m.T.conj())) 
True 

其中allclosertolatol参数。

2

如果您正在使用与NumPy的matrix class,没有为埃尔米特共轭的属性,所以:

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

例如

In [79]: P = np.matrix([[0,-1j],[1j,0]]) 

In [80]: is_unitary(P) 
Out[80]: True 
相关问题