我明白了他的错误,也不知道为什么。显然,这段代码在Python2中工作,我使用的是Python3.7,这似乎就是问题所在?有人能解释这里出了什么问题吗
A = np.array([[10,12],[12,10]])
b= np.array([2,1])
x0 = np.array([0., 0.])
tol = 10 ** (-15)
max_iter = 20
w = 1.5
def SOR(A, b, x0, tol, max_iter, w):
if (w<=1 or w>2):
print('w should be inside [1, 2)');
step = -1;
x = float('nan')
return
n = b.shape
x = x0
for step in range (1, max_iter):
for i in range(n[0]):
new_values_sum = np.dot(A[i, :i], x[:i])
old_values_sum = np.dot(A[i, i+1 :], x0[ i+1: ])
x[i] = (b[i] - (old_values_sum + new_values_sum)) / A[i, i]
x[i] = np.dot(x[i], w) + np.dot(x0[i], (1 - w))
if (np.linalg.norm(x - x0) < tol):
if (np.linalg.norm(np.dot(A, x)-b ) < tol):
print(step)
break
x0 = x
print("X = {}".format(x))
print("The number of iterations is: {}".format(step))
return x
x = SOR(A, b, x0, tol, max_iter, w)
print(np.dot(A, x))
我获得了以下错误消息:
Error: x[i]=(1-w)*x[i]-w*(np.dot(A[i,:],x)-b[i]-A[i,i]*x[i])/A[i,i]
ValueError: setting an array element with a sequence.
试图用上面的代码实现SOR方法,为什么会出现这个错误
最可能的情况是,您有多个名称相似的文件,或者您位于错误的文件夹中。看起来您运行的代码是错误的
以下行没有出现在您共享的代码中,您可能希望检查您的
A
、b
和x
是什么:您应该能够在我更改了终止条件的地方运行以下代码,因为当前第一个if语句未完成:
我获得了Python 2和Python 3的以下输出:
相关问题 更多 >
编程相关推荐