import numpy as np def qrdec(A): n = A.shape[0] Ap = np.copy(A) Q = np.zeros((n, n)) R = np.zeros((n, n)) for j in range(n): for i in range(j): R[i, j] = Q[:, i] @ A[:, j] Ap[:, j] -= R[i, j] * Q[:, i] R[j, j] = mag(Ap[:, j]) Q[:, j] = Ap[:, j] / R[j, j] return Q, R def testqrdec(A): n = A.shape[0] Q, R = qrdec(A) diffa = A - Q @ R diffq = np.transpose(Q) @ Q - np.identity(n) print(n, mag(diffa), mag(diffq)) if __name__ == '__main__': for n in range(4, 10, 2): A, bs = testcreate(n, 21) testqrdec(A)
# Author: Alex Gezerlis # Numerical Methods in Physics with Python (CUP, 2020) from triang import testcreate from invpowershift import invpowershift from qrmet import qrmet import numpy as np def eig(A,eps=1.e-12): n = A.shape[0] eigvals = np.zeros(n) eigvecs = np.zeros((n,n)) qreigvals = qrmet(A) for i, qre in enumerate(qreigvals): eigvals[i], eigvecs[:,i] = invpowershift(A,qre+eps) return eigvals, eigvecs def testeigall(f,A): eigvals, eigvecs = f(A) npeigvals, npeigvecs = np.linalg.eig(A) print(eigvals); print(npeigvals) print(" ") for eigvec, npeigvec in zip(eigvecs.T,npeigvecs.T): print(eigvec); print(npeigvec) print(" ") if __name__ == '__main__': A, bs = testcreate(4,21) testeigall(eig,A)
def jacobi(A, bs, kmax=50, tol=1.e-6): n = bs.size xnews = np.zeros(n) for k in range(1, kmax): xs = np.copy(xnews) for i in range(n): slt = A[i, :i] @ xs[:i] sgt = A[i, i + 1:] @ xs[i + 1:] xnews[i] = (bs[i] - slt - sgt) / A[i, i] err = termcrit(xs, xnews) print(k, xnews, err) if err < tol: break else: xnews = None return xnews if __name__ == '__main__': n = 4 val = 21 A, bs = testcreate(n, val) A += val * np.identity(n) testsolve(jacobi, A, bs)