Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import numpy as np
  2. import numpy.linalg as nla
  3. np.set_printoptions(suppress=True)
  4.  
  5. # G&vL 3rd pg. 210
  6. def make_house_vec(x):
  7. n = x.shape[0]
  8. dot_1on = x[1:].dot(x[1:])
  9.  
  10. # v is our return vector; we hack on v[0]
  11. v = np.copy(x)
  12. v[0] = 1.0
  13.  
  14. if dot_1on < np.finfo(float).eps:
  15. beta = 0.0
  16. else:
  17. # apply Parlett's formula (G&vL page 210) for safe v_0 = x_0 - norm(X)
  18. norm_x= np.sqrt(x[0]**2 + dot_1on)
  19. if x[0] <= 0:
  20. v[0] = x[0] - norm_x
  21. else:
  22. v[0] = -dot_1on / (x[0] + norm_x)
  23. beta = 2 * v[0]**2 / (dot_1on + v[0]**2)
  24. v = v / v[0]
  25. return v, beta
  26.  
  27. def full_house(n, col, v, beta):
  28. ''' for size n, apply a Householder vector v in the lower right corner of
  29. I_n to get a full-sized matrix with a smaller Householder matrix component'''
  30. full = np.eye(n)
  31. full[col:, col:] -= beta * np.outer(v,v)
  32. return full
  33.  
  34. # G&VL Algo. 5.4.2 with explicit reflections
  35. def house_bidiag_explicit_UV(A):
  36. m,n = A.shape
  37. assert m >= n
  38. U,Vt = np.eye(m), np.eye(n)
  39.  
  40. for col in range(n):
  41. v, beta = make_house_vec(A[col:,col])
  42. A[col:,col:] = (np.eye(m-col) - beta * np.outer(v,v)).dot(A[col:,col:])
  43. Q = full_house(m, col, v, beta)
  44. U = U.dot(Q)
  45.  
  46. if col <= n-2:
  47. # transpose here, reflection for zeros above diagonal in A
  48. # col+1 keeps us off the super diagonal
  49. v,beta = make_house_vec(A[col,col+1:].T)
  50. A[col:,col+1:] = A[col:, col+1:].dot(np.eye(n-(col+1)) - beta * np.outer(v,v))
  51. P = full_house(n, col+1, v, beta)
  52. Vt = P.dot(Vt)
  53. return U, A, Vt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement