我正在尝试编写一个以矩阵为参数的代码,并使用改进的Gram-Schmidt算法计算并打印QR分解。
我在为代码获取正确的输出方面遇到困难,任何帮助都是很棒的。
我想要的输出:
multiply(scalar,vector) is sqrt(2)
dot(qi,vector01) is [1/(sqrt(2)), 0, 1/(sqrt(2))]
scalarVec(rj,qi) is [1, 0, 1]
vecSubtract(vector01,vector03) is [1, 1, -1]
我的代码附在下面:
def twoNorm(vector):
'''
twoNorm takes a vector as it's argument. It then computes the sum of
the squares of each element of the vector. It then returns the
square root of this sum.
'''
# This variable will keep track of the validity of our input.
inputStatus = True
# This for loop will check each element of the vector to see if it's a number.
for i in range(len(vector)):
if ((type(vector[i]) != int) and (type(vector[i]) != float) and (type(vector[i]) != complex)):
inputStatus = False
print("Invalid Input")
# If the input is valid the function continues to compute the 2-norm
if inputStatus == True:
result = 0
# This for loop will compute the sum of the squares of the elements of the vector.
for i in range(len(vector)):
result = result + (vector[i]**2)
result = result**(1/2)
return result
vector = [1, 0, 1]
print(twoNorm(vector))
def multiply(scalar,vector):
qi = []
for i in vector:
qi.append(i/scalar)
return qi
def dot(qi,vector01):
if len(qi) != len(vector01):
print('invalid input')
else:
total = 0
for i in range(len(qi)):
total += qi[i] * vector01[i]
return total
def scalarVec(rj,qi):
vector03 = []
for i in qi:
vector03.append(i * rj)
return vector03
def vecSubtract(vector01,vector03):
if len(vector01) != len(vector03):
print('invalid input')
else:
result = []
for i in range(len(vector01)):
total = vector01[i] - vector03[i]
result.append(total)
return result
vector01 = [2, 1, 0]
scalar = twoNorm(vector)
vector = [1, 0, 1]
matrix = [[1, 2], [0, 1], [1, 0]]
print(multiply(scalar,vector))
qi = multiply(scalar,vector)
print(dot(qi,vector01))
rj = dot(qi,vector01)
print(multiply(rj, qi))
vector03 = scalarVec(rj,qi)
print(vecSubtract(vector01,vector03))