Search code examples
pythonnumpyvectorizationarray-broadcastingdivide-by-zero

Division by 0 in python broadcasting?


I'm using Python2.7 to create a simple vector field and then plotting it...

But Jupyter complains about a division by 0 ("RuntimeWarning: divide by zero encountered in divide"), and I can't find it.

import numpy as np

def field_gen(x0, y0, x, y, q_cons = 1):
    dx = x0-x
    dy = y0-y
    dist = np.sqrt(np.square(dx)+np.square(dy))
    kmod = np.where( dist>0.00001, q_cons / dist, 0  ) 
    kdir = np.where( kmod != 0, (np.arctan2(-dy,-dx) * 180 / np.pi), 0)
    res_X = np.where( kmod !=0, kmod * (np.cos(kdir)) , 0 )
    res_Y = np.where( kmod !=0, kmod * (np.sin(kdir)) , 0 )
    return (res_X, res_Y)

n = 10
X, Y = np.mgrid[0:n, 0:n]

x0=2
y0=2

(u,v)= field_gen(x0, y0, X, Y)
#print(u) #debug
#print
#print(v)
plt.figure()
plt.quiver(X, Y, u, v, units='width')

Any hints on that?


Solution

  • Don't be fooled into think np.where does all the work here. Python will still evaluate all the input arguments first, before running calling np.where.

    So in your command kmod = np.where( dist>0.00001, q_cons / dist, 0 ), Python will evaluate dist>0.00001 (ok) and q_cons / dist (bad!) before running np.where.

    Try np.divide instead. I think you want something like this:

    np.divide(q_cons, dist, where=dist>0.00001 )