1

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"

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()        
al exx
  • 75
  • 1
  • 8
  • Post the error (traceback) – Kobi K Oct 27 '15 at 12:52
  • 3
    Possible duplicate of [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](http://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – Dimitris Fasarakis Hilliard Oct 27 '15 at 12:52

1 Answers1

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]).

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.

Kamejoin
  • 347
  • 2
  • 8