我在为QR(矩阵)部分计算代码中两个向量的点积时遇到麻烦。我正在尝试用vector01点q [i]的结果,但我不知道我的代码在哪里不正确。任何帮助都将非常感谢。我的预期输出应该是sqrt(2)
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 QR(matrix):
if len(matrix) != len(vector):
print('Invalid')
else:
qi = []
for i in vector:
qi.append(i/scalar)
return qi
if len(qi) != len(vector01):
print('invalid input')
else:
total = 0
for j in range(len(qi)):
total += qi[j] * vector01[j]
return total
vector01 = [2, 1, 0]
scalar = twoNorm(vector)
vector = [1, 0, 1]
matrix = [[1, 2], [0, 1], [1, 0]]
print(QR(matrix))
答案 0 :(得分:0)
twoNorm()中的两个“ if”结构不正确(也许只是您没有注意到的缩进问题?)。将下面的代码与您的代码进行比较。您会发现问题所在。
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
我没有仔细检查QR(),但是我确定这很麻烦-'return qi'之后的任何东西都不会执行。 QR()是如何工作的?