在下面的代码中,我得到了错误
n = 101 # Number of grid points
P = np.zeros((n, n))
xmin, xmax = 0.0, 1.0 # limits in the x direction
ymin, ymax = -0.5, 0.5
x = np.linspace(xmin, xmax, nx)
y = np.linspace(ymin, ymax, ny)
X, Y = np.meshgrid(x, y, indexing='ij')
a = ((D/(dx*dx))-(X-Y*Y)/(2*dx))
b = (2+X-4*D/(dx*dx))
c = ((D/(dx*dx))-(Y+X*Y)/(2*dx))
d = ((D/(dx*dx))+(Y+X*Y)/(2*dx))
e = ((D/(dx*dx))+(X-Y*Y)/(2*dx))
### boundary conditions
for i in range(len(P)):
P[i, 0] = 0 # Left boundary
P[i, -1] = 0 # Right boundary
P[0, i] = 0 # Lower boudary
P[-1, i] = 0
f = 0.
w = 1.2
resid_crit = 1.0e-6
# Arbitrary value at the begining, higher than resid_crit
resid_ave = 100.
count = 0
while resid_ave > resid_crit:
# Set at 0 so we can sum it up later
resid_ave = 0.
# Set count for points in checker-boarding
cnt_points = 0
# Loop over internal points only
for i in range(1, n - 1):
for j in range(1, n - 1):
# Checker-boarding
if ((i + j) % 2) == count % 2:
# Residual
residual = a[i,j] * P[i - 1, j] + b[i,j] * P[i, j] + c[i,j] * P[i, j - 1] + d[i,j] * P[i, j + 1] + e * P[
i+1, j] - f
# Update psi value
P[i, j] += -w * residual / b[i,j]
# Update resid_ave as a sum of residuals
resid_ave += abs(residual)
cnt_points += 1
# Get average residual
resid_ave = resid_ave / cnt_points
# Print every 1000-dth residual
if count % 1000 == 0:
print("Residual: %.7f" % resid_ave)
#print("Residual: ", resid_ave)
# Count iterations
count = count + 1
输出显示:
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gitsa\PycharmProjects\sagarPy1\SKtest.py", line 89, in <module>
P[i, j] += -w * residual / b[i,j]
ValueError: setting an array element with a sequence.
1条答案
按热度按时间2j4z5cfb1#
如果你是python新手,那么你已经借用了有经验的人写的代码。但我们不知道你改了什么代码或输入。
这个错误的代码是
P[i,j]
一个2d数组的单个元素。*=
的RHS必须是数组(1或2d)才会产生此错误。w
是标量,一个数字。b[i,j]
是2d数组的元素。问题是residual
。在
residual
计算中,f
也是标量。其他术语是2d阵列的元素。但是e
看起来像是X
和Y
的计算结果,它们是2dmeshgrid
的结果。同样,我们不知道这个代码编写者的知识或意图。也许有人写了
e
而不是e[i,j]
。