Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # QR decomposition
- import re
- import numpy as np
- from collections import namedtuple
- # functions
- def get_q(a, Q, n):
- u = a
- if n != 0:
- for j in range(0, n):
- u = u - (a.dot(Q[j]) * Q[j])
- return u / np.linalg.norm(u)
- def QR_decompose(A):
- Q = np.zeros(A.shape)
- for i in range(A.shape[0]):
- Q[i] = get_q(A[i], Q, i)
- R = Q.dot(A)
- return namedtuple("qr", ["Q", "R"])(Q.T, R)
- # execution code
- split_regex = r'[\/\\|, ]+'
- elements = list(map(
- float,
- re.split(split_regex, input('Enter elements: '))
- ))
- shape = list(map(
- int,
- re.split(split_regex, input('Enter shape (N rows x M columns: '))
- ))
- A = np.array(elements).reshape(shape)
- print ('A : \n' , A)
- qr_decomposition = QR_decompose(A.T)
- Q = qr_decomposition.Q
- R = qr_decomposition.R
- print ('Q : \n', Q)
- print ('R : \n', R)
- print ('Pass test: ' + str(np.array_equal(A, np.dot(Q, R))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement