/
GramSchmidt.py
77 lines (56 loc) · 1.58 KB
/
GramSchmidt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#########################
# GramSchmidt.py
#
# Implements the Gram-Schmidt process
# to solve least squares
# (and to compute a QR decomposition)
#
# Taylor J. Smith - CSCI 554 (Winter 2022)
#########################
import math
import numpy as np
import sys
import time
m = int(input("Dimension m? "))
n = int(input("Dimension n? "))
while m < n:
print("m must be greater than or equal to n.")
m = int(input("Dimension m? "))
n = int(input("Dimension n? "))
V = np.random.randint(0,10,(m,n))
rk = np.linalg.matrix_rank(V)
# We want our matrix to have linearly independent columns
# If rank < number of columns, generate a new random matrix
# (We will rarely enter this while loop, as randomly-generated
# matrices are very likely to have linearly independent columns)
while rk < n:
V = np.random.rand(m,n)
rk = np.linalg.matrix_rank(V)
print("V =\n", V)
#########################
# Our implementation
#########################
Q = np.copy(V.astype(float))
start1 = time.time()
for k in range(0,n):
Vk = V[:,k]
qhatk = Vk
for i in range(0,k):
rik = np.inner(Vk, Q[:,i])
qhatk = qhatk - rik*Q[:,i]
rkk = np.linalg.norm(qhatk)
if rkk == 0:
sys.exit("Columns v1 through vk are linearly dependent!")
qk = (1 / rkk)*qhatk
Q[:,k] = qk
end1 = time.time()
print(" Q =\n", Q)
print(" Time =", end1 - start1)
#########################
# "Good" implementation
#########################
start2 = time.time()
goodQ, goodR = np.linalg.qr(V)
end2 = time.time()
print("\"Good Q\" =\n", goodQ)
print(" Time =", end2 - start2)