Write a python function with a call of l, v = rayleighQuotient(A, v0, tol, itermax)…
- User
Write a python function with a call of l, v = rayleighQuotient(A, v0, tol, itermax) which implements the Rayleigh-Quotient iteration for eigenvalue and eigenvector calculation. The file containing this function must be called rayleighQuotient.py.
The inputs are:
A: A real and square matrix. This will be a numpy array. v0: The arbitrary vector to initialize the iteration with. This will be a numpy array and might not be a unit vector. tol: The tolerance for convergence. Use abs((ln-ln-1)/(ln)<tol as the convergence criteria. itermax: The maximum number of iterations. If the maximum number of iteration is exceeded raise an exception with this exact error message: Error: Maximum Number of Iterations The outputs are:
l: The calculated eigenvalue v: The associated eigenvector You are allowed to use numpy in the programming project. In particular you will need the following functions:
eye dot shape linalg.inv linalg.norm
- Assistant
Here is the full implementation of the Rayleigh Quotient Iteration in Python using the given problem statement.
pythonimport numpy as np def rayleighQuotient(A, v0, tol, itermax): n, m = np.shape(A) if n != m: raise ValueError("Matrix A must be square") v = v0 / np.linalg.norm(v0) l = np.dot(v.T, np.dot(A, v)) I = np.eye(n) l_old = None iterations = 0 while iterations < itermax: try: v = np.dot(np.linalg.inv(A - l * I), v) v /= np.linalg.norm(v) l_old = l l = np.dot(v.T, np.dot(A, v)) if l_old is not None and abs((l - l_old) / l) < tol: break iterations += 1 except np.linalg.LinAlgError: raise ValueError("Singular matrix encountered") if iterations == itermax: raise Exception("Error: Maximum Number of Iterations") return l, v - User
def rayleighQuotient(A, v0, tol, itermax): # The function implements the Rayleigh-Quotient iteration for eigenvalue and eigenvector calculation # # Inputs: # A - A real and square matrix. # v0 - The arbitrary vector to initialize the iteration with. # tol - The tolerance for convergence. # itermax - The maximum number of iterations. # # Outputs: # l: The calculated eigenvalue # v: The associated eigenvector
coden, m = np.shape(A) if n != m: raise ValueError("Matrix A must be square") v = v0 / np.linalg.norm(v0) l = np.dot(v.T, np.dot(A, v)) I = np.eye(n) l_old = np.inf iterations = 0 while iterations < itermax: try: v = np.dot(np.linalg.inv(A - l * I), v) v /= np.linalg.norm(v) l_old = l l = np.dot(v.T, np.dot(A, v)) if l_old is not None and abs((l - l_old) / l) < tol: break iterations += 1 except np.linalg.LinAlgError: raise ValueError("Singular matrix encountered") if iterations == itermax: raise Exception("Error: Maximum Number of Iterations") return l, v - Assistant
Here is the corresponding MATLAB code for the Rayleigh Quotient Iteration function:
matlab