gpt4 book ai didi

python - 在 Python 中针对复杂向量修改 Gram Schmidt

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:38 27 4
gpt4 key购买 nike

我写了一些代码来实现修改后的 Gram Schmidt 过程。什么时候我在真实矩阵上测试过,是正确的。但是,当我测试它时在复杂的矩阵上,它出错了。

通过逐步检查,我相信我的代码是正确的。所以,我想知道修改后的 Gram Schmidt 是否有数值原因处理复杂向量失败。

代码如下:

import numpy as np

def modifiedGramSchmidt(A):
"""
Gives a orthonormal matrix, using modified Gram Schmidt Procedure
:param A: a matrix of column vectors
:return: a matrix of orthonormal column vectors
"""
# assuming A is a square matrix
dim = A.shape[0]
Q = np.zeros(A.shape, dtype=A.dtype)
for j in range(0, dim):
q = A[:,j]
for i in range(0, j):
rij = np.vdot(q, Q[:,i])
q = q - rij*Q[:,i]
rjj = np.linalg.norm(q, ord=2)
if np.isclose(rjj,0.0):
raise ValueError("invalid input matrix")
else:
Q[:,j] = q/rjj
return Q

测试代码如下:

import numpy as np

# If testing on random matrices:
# X = np.random.rand(dim,dim)*10 + np.random.rand(dim,dim)*5 *1j
# If testing on some good one
v1 = np.array([1, 0, 1j]).reshape((3,1))
v2 = np.array([-1, 1j, 1]).reshape((3,1))
v3 = np.array([0, -1, 1j+1]).reshape((3,1))
X = np.hstack([v1,v2,v3])
Y = modifiedGramSchmidt(X)
Y3 = np.linalg.qr(X, mode="complete")[0]
if np.isclose(Y3.conj().T.dot(Y3), np.eye(dim, dtype=complex)).all():
print("The QR-complete gives orthonormal vectors")
if np.isclose(Y.conj().T.dot(Y), np.eye(dim, dtype=complex)).all():
print("The Gram Schmidt process is tested against a random matrix")
else:
print("But My modified GS goes wrong!")
print(Y.conj().T.dot(Y))

更新

问题是我在第一个参数中实现了一个为内积线性设计的算法

而我认为它在第二个参数中是线性的。

感谢@landogardner

最佳答案

您的问题与 numpy.vdot 如何处理复数有关 — 第一个参数的复共轭用于计算 (ref)。因此,您将 rij 计算为 q*.Q[:,i] 而不是 q.Q[:,i]*。只需交换参数的顺序:

rij = np.vdot(Q[:,i], q)

这让测试代码对我有用。

关于python - 在 Python 中针对复杂向量修改 Gram Schmidt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47349233/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com