在python广播中被0除?

2024-05-13 17:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是Jupyter抱怨除法是0(“RuntimeWarning:divide中遇到的除法是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')

有什么提示吗


Tags: fielddistnpreswheregenprintsquare
1条回答
网友
1楼 · 发布于 2024-05-13 17:34:19

别以为np.where做了这里所有的工作。在运行调用np.where之前,Python仍然会首先计算所有输入参数

因此,在命令kmod = np.where( dist>0.00001, q_cons / dist, 0 )中,Python将计算dist>0.00001(ok)和q_cons / dist(bad!)在运行np.where之前

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

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

相关问题 更多 >