Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. # QR decomposition
  2. import re
  3. import numpy as np
  4. from collections import namedtuple
  5. # functions
  6. def get_q(a, Q, n):
  7.     u = a
  8.     if n != 0:    
  9.         for j in range(0, n):
  10.             u = u - (a.dot(Q[j]) * Q[j])
  11.            
  12.     return u / np.linalg.norm(u)
  13.  
  14. def QR_decompose(A):
  15.     Q = np.zeros(A.shape)
  16.    
  17.     for i in range(A.shape[0]):
  18.         Q[i] = get_q(A[i], Q, i)
  19.        
  20.     R = Q.dot(A)
  21.    
  22.     return namedtuple("qr", ["Q", "R"])(Q.T, R)
  23.  
  24. # execution code
  25. split_regex = r'[\/\\|, ]+'
  26. elements = list(map(
  27.                     float,
  28.                     re.split(split_regex, input('Enter elements: '))
  29.                 ))
  30. shape = list(map(
  31.                     int,
  32.                     re.split(split_regex, input('Enter shape (N rows x M columns: '))
  33.                 ))
  34. A = np.array(elements).reshape(shape)
  35. print ('A : \n' , A)
  36. qr_decomposition = QR_decompose(A.T)
  37. Q = qr_decomposition.Q
  38. R = qr_decomposition.R
  39. print ('Q : \n', Q)
  40. print ('R : \n', R)
  41. print ('Pass test: ' + str(np.array_equal(A, np.dot(Q, R))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement