我收到“norm”的导入错误。我做得不对吗?
我愿意接受有关改进代码的建设性反馈,但我必须保持参数不变!
感谢!!!
代码如下:
import numpy as np
from numpy import norm, inalg, array, zeros, diag, diagflat, dot, linalg
"""Test Case Data"""
A = np.matrix([[4,-1,-1],[-2,6,1],[-1,1,7]])
b = np.matrix([[3],[9],[-6]])
x = np.matrix([[0],[0],[0]])
"""Main Function"""
def jacobi(A, b, x, Tolerance, Iterations):
V = np.diag(A)
D = np.diag(V)
R = D-A
D_I = D.I
D = np.asmatrix(D)
Counter_1 = 1
tol_gauge = 100
while Counter_1 <= Iterations:
# I considered using the "dot" function in NUMPY but I was wary of mixed results
iterative_approach_form = D_I * ((R*x)+b)
tol_gauge = np.linalg.norm(iterative_approach_form-x)
x = iterative_approach_form
if initial_tol <= Tolerance:
return("The Solution x = {},y={}, z={} ".format(x[0], x[1], x[2]))
return("The Solution was found in %s interation(s)" %(Counter_1))
else:
pass
Counter_1 +=1
return("The Solution was not found in {} iteration(s)".format(Iterations))
答案 0 :(得分:0)
您需要指定要从哪个numpy模块导入。如果您只想按名称使用函数,则以下内容有效:
from numpy import linalg
from numpy.linalg import norm
from numpy import zeros, array, diag, diagflat, dot
然而,查看您的代码,您不需要第二个导入行,因为在其余代码中,numpy函数是根据接受的规范指定的。例如,norm已作为np.linalg.norm存在于代码中。
您的代码还有三个问题:1)initial_tol未分配值; 2)tol_gauge已分配但未在代码中使用; 3)最后一个return语句没有正确缩进(可能只在这里),而你的while循环中的块很可能是相同的。