gram-schmidt算法用python写
时间: 2024-10-08 17:05:00 浏览: 39
Gram-Schmidt正交化算法是一种将一组线性无关向量转化为一组相互正交的新向量的过程。在Python中,你可以使用numpy库来方便地实现这个算法。以下是简单的步骤:
```python
import numpy as np
def gram_schmidt(orthonormal_basis, v):
# 检查v是否在已有的正交基上
if v.shape[0] != orthonormal_basis.shape[0]:
raise ValueError("The column vector v must have the same dimension as the orthogonal basis.")
# Gram-Schmidt过程
q = v.copy()
for i in range(len(orthonormal_basis)):
# 计算投影并从原向量中减去投影部分
proj = np.dot(q, orthonormal_basis[i]) / np.linalg.norm(orthonormal_basis[i])**2
q -= proj * orthonormal_basis[i]
return q
# 示例:给定基础向量集合和新向量
basis = np.array([[1, 0], [0, 1]])
vector_to_ortho = np.array([2, 1])
# 正交化
orthogonal_vector = gram_schmidt(basis, vector_to_ortho)
print("Orthogonalized vector:", orthogonal_vector)
阅读全文