ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all(

2024-10-01 00:26:37 发布

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

我的代码有问题。该程序假设在一个盒子里找到线性势。这是一个我以前从未见过的错误。 而错误所在的代码似乎合乎逻辑。有人能解释为什么会发生在“如果delta0>;delta”的地方吗

提前谢谢你

这是我的密码

           # -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 11:32:00 2015

@author: 50073507
"""

import numpy as np

import matplotlib.pyplot as plt
import matplotlib.cm as cm

from mpl_toolkits.mplot3d import axes3d

np.set_printoptions(formatter={'float': '{: 0.2f}' . format})

def relax(v):
    return (v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1]) 

tolerance = 1.e-6
delta = 1.0
nx =7
ny = 7

v = np.zeros([nx,ny])
v[:,0] = -1
v[:,-1] = 1
v[0,:] = np.linspace(-1,1,nx)
v[ny-1,:] = np.linspace(-1,1,nx)

print("starting values")
print(v)

iteration = 0

while delta > tolerance:
    delta = 0
    for i in range(1,nx-1):
        for j in range(1,ny-1):
            newVij = relax(v)
            delta0 = np.abs(newVij - v[i,j])
            if delta0 > delta:
                delta = delta0
            v[i,j] = newVij
        iteration += 1
        print ("Iteration", iteration)
        print(v)


x = np.linspace(-1,1,nx)
y=  np.linspace(-1,1,ny)
x, y = np.meshgrid(x,y)

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
surf = ax.plot_surface(x, y, v , alpha = 0.7, cmap = cm.coolwarm)
cset = ax.contourf(x,y,v,zdir='v',offset=-1,cmap=cm.coolwarm)
plt.show()


Ey, Ex = np.gradient(-v)

fig , ax = plt.subplots()
ax.quiver(x,y, Ex, Ey, y)
ax.set(aspects = 1, title = 'Eletric Field')
plt.axis([-1.05, 1.05,-1.05,1.05])
plt.show()        

Tags: importasnpfigcmpltaxdelta
1条回答
网友
1楼 · 发布于 2024-10-01 00:26:37

你在尝试比较元组和浮点。检查您的功能:

def relax(v):
    return (v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1]) 

这将返回一个元组(v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1])。在

在你的while中你看到了:

^{pr2}$

好吧,delta0是元组,delta是float,这就是问题所在。在

相关问题 更多 >