在python广播中除以0?

问题描述 投票:0回答:1

我正在使用Python2.7创建一个简单的矢量场,然后绘制它......

但是Jupyter抱怨除以0(“运行时警告:在分界中遇到零除”),我找不到它。

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')

有什么提示吗?

python numpy-broadcasting divide-by-zero
1个回答
1
投票

不要被愚弄,认为np.where在这里完成所有工作。在运行调用np.where之前,Python仍将首先评估所有输入参数。

所以在你的命令kmod = np.where( dist>0.00001, q_cons / dist, 0 )中,Python会在运行dist>0.00001之前评估q_cons / dist(ok)和np.where(bad!)。

试试np.divide吧。我想你想要这样的东西:

np.divide(q_cons, dist, where=dist>0.00001 )
© www.soinside.com 2019 - 2024. All rights reserved.