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

时间:2022-07-20 16:07:27

I am having an issue with my code . The code is suppose to find the linear Potential (V) in a box. It is giving an error that I have not seen before. While the code where the error seems logical. Could anyone explain why is is happening where " if delta0 > delta"

我的代码有问题。这段代码假设在一个盒子里找到线性势(V)。它犯了一个我以前没见过的错误。当代码出现错误时。有人能解释为什么会发生"如果德尔塔0 > "

Thank you in advance,

谢谢你提前,

Here is my code

这是我的代码

           # -*- 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()        

1 个解决方案

#1


0  

You're trying to compare a tuple with a float. Check your function:

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

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

This will return a tuple (v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1]).

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

And in your while you got this:

当你得到这个的时候

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

Well, delta0 its a tuple and delta a float, that's the problem.

它是一个tuple和一个float,这就是问题所在。

#1


0  

You're trying to compare a tuple with a float. Check your function:

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

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

This will return a tuple (v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1]).

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

And in your while you got this:

当你得到这个的时候

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

Well, delta0 its a tuple and delta a float, that's the problem.

它是一个tuple和一个float,这就是问题所在。