【问题标题】:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all(
【发布时间】:2016-01-26 21:25:39
【问题描述】:

我的代码有问题。该代码假设在一个框中找到线性电位 (V)。它给出了一个我以前从未见过的错误。 虽然错误似乎合乎逻辑的代码。谁能解释为什么会发生“if 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()        

【问题讨论】:

标签: python


【解决方案1】:

您正在尝试将元组与浮点数进行比较。检查你的功能:

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 中你得到了这个:

newVij = relax(v)
delta0 = np.abs(newVij - v[i,j])
if delta0 > delta:

嗯,delta0 是一个元组,而 delta 是一个浮点数,这就是问题所在。

【讨论】:

  • 非常感谢。感谢您花时间查看我的程序。
猜你喜欢
  • 2020-05-12
  • 2019-07-30
  • 2014-04-06
  • 2020-01-28
相关资源
最近更新 更多