Mes*_*zil 3 python numpy fft matrix
我想知道 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
Run Code Online (Sandbox Code Playgroud)
让我们看一个明显的单一数组:
>>> 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.]])
Run Code Online (Sandbox Code Playgroud)
并尝试您的功能:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
这是因为
>>> m.size
4
>>> np.eye(m.size)
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
Run Code Online (Sandbox Code Playgroud)
如果我们n = matrix.size用len(m)orm.shape[0]或什么替换,我们得到
>>> is_unitary(m)
True
Run Code Online (Sandbox Code Playgroud)
我可能只是用
>>> np.allclose(np.eye(len(m)), m.dot(m.T.conj()))
True
Run Code Online (Sandbox Code Playgroud)
其中allclose有rtol和atol参数。
如果您使用 NumPy 的矩阵类,则 Hermitian 共轭有一个属性,因此:
def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
Run Code Online (Sandbox Code Playgroud)
例如
In [79]: P = np.matrix([[0,-1j],[1j,0]])
In [80]: is_unitary(P)
Out[80]: True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4851 次 |
| 最近记录: |