Numpy数组在for循环中获取“ValueError:设置具有序列的数组元素”?

2024-09-28 20:53:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我明白了他的错误,也不知道为什么。显然,这段代码在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方法,为什么会出现这个错误


Tags: 代码ifstep错误nparraydotmax
1条回答
网友
1楼 · 发布于 2024-09-28 20:53:44

最可能的情况是,您有多个名称相似的文件,或者您位于错误的文件夹中。看起来您运行的代码是错误的

以下行没有出现在您共享的代码中,您可能希望检查您的Abx是什么:

x[i]=(1-w)*x[i]-w*(np.dot(A[i,:],x)-b[i]-A[i,i]*x[i])/A[i,i]

您应该能够在我更改了终止条件的地方运行以下代码,因为当前第一个if语句未完成:

import numpy as np 
import math 

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) and (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))

我获得了Python 2和Python 3的以下输出:

X = [ 270.45162499 -324.44194999]
The number of iterations is: 19
[-1.18878715e+03  1.00000000e+00]

相关问题 更多 >