def QR(A): def householder(a): n = len(a) v = np.zeros(n) v[0] = np.linalg.norm(a) if a[0] < 0: v[0] = -v[0] v = v + a v = v / np.linalg.norm(v) H = np.eye(n) - 2 * np.outer(v, v) return H def qr_factorization(A): m, n = A.shape Q = np.eye(m) R = A.copy() for j in range(min(m, n)): a = R[j:, j] H = np.eye(m) H[j:, j:] = householder(a) Q = Q @ H.T R = H @ R return Q, R Q, R = qr_factorization(A) b = sp.Matrix(sp.symbols('a1:11')) # 求解Ly=b中的y y = sp.zeros(10, 1) # 初始化y y = Q.T@b # 求解Ux=y中的x x = sp.zeros(10, 1) # 初始化x for i in range(9, -1, -1): x[i] = y[i] for j in range(i+1, 10): x[i] -= R[i, j] * x[j] x[i] /= R[i, i] matrice_coeff = sp.Matrix(np.zeros((10, 10))) for i in range(10): for j in range(10): matrice_coeff[i, j] = x[i].coeff(sp.Symbol('a{}'.format(j + 1))) return(matrice_coeff)修改这段函数,让def里面不要再嵌套def
时间: 2024-02-14 10:08:36 浏览: 74
可以将内部的两个函数 `householder` 和 `qr_factorization` 移到外部并改为类的方法,这样就不需要嵌套 `def` 了。以下是修改后的代码:
```python
import numpy as np
import sympy as sp
class QRDecomposition:
def __init__(self, A):
self.A = A
self.m, self.n = A.shape
self.Q = np.eye(self.m)
self.R = self.A.copy()
def householder(self, a):
v = np.zeros(self.n)
v[0] = np.linalg.norm(a)
if a[0] < 0:
v[0] = -v[0]
v = v + a
v = v / np.linalg.norm(v)
H = np.eye(self.m) - 2 * np.outer(v, v)
return H
def qr_factorization(self):
for j in range(min(self.m, self.n)):
a = self.R[j:, j]
H = np.eye(self.m)
H[j:, j:] = self.householder(a)
self.Q = self.Q @ H.T
self.R = H @ self.R
def solve(self, b):
y = self.Q.T @ b
x = np.zeros(self.n)
for i in range(self.n - 1, -1, -1):
x[i] = y[i]
for j in range(i + 1, self.n):
x[i] -= self.R[i, j] * x[j]
x[i] /= self.R[i, i]
return x
def get_coefficients(self, b):
self.qr_factorization()
x = self.solve(b)
matrice_coeff = sp.Matrix(np.zeros((self.n, self.n)))
for i in range(self.n):
for j in range(self.n):
matrice_coeff[i, j] = x[i].coeff(sp.Symbol('a{}'.format(j + 1)))
return matrice_coeff
```
这样,我们可以通过创建 `QRDecomposition` 类的实例来调用它的方法。例如,可以按如下方式使用:
```python
A = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1],
[3, 4, 5, 6, 7, 8, 9, 10, 1, 2],
[4, 5, 6, 7, 8, 9, 10, 1, 2, 3],
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4],
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5],
[7, 8, 9, 10, 1, 2, 3, 4, 5, 6],
[8, 9, 10, 1, 2, 3, 4, 5, 6, 7],
[9, 10, 1, 2, 3, 4, 5, 6, 7, 8],
[10, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
b = sp.Matrix(sp.symbols('a1:11'))
qr = QRDecomposition(A)
matrice_coeff = qr.get_coefficients(b)
print(matrice_coeff)
```
阅读全文