Skip to main content
 首页 » 编程设计

python之numpy中有没有一种方法可以测试矩阵是否是单一的

2025年05月04日17lautakyan007

我想知道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 

请您参考如下方法:

让我们来看一个明显的酉数组:

>>> 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 

其中 allclose 有 rtol 和 atol 参数。