作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下功能:
def delta(r, dr):
res = np.zeros(r.shape)
mask1 = (r >= 0.5*dr) & (r <= 1.5*dr)
res[mask1] = (5-3*np.abs(r[mask1])/dr \
- np.sqrt(-3*(1-np.abs(r[mask1])/dr)**2+1))/(6*dr)
mask2 = np.logical_not(mask1) & (r <= 0.5*dr)
res[mask2] = (1+np.sqrt(-3*(r[mask2]/dr)**2+1))/(3*dr)
return res
哪里r
是 numpy.array
尺寸(shape[0],shape[1])
和dr
是单个值。我想修改函数使 dr
也是一个与 r
大小相同的数组对于 r
的每个值从 dr
中获取类似值.
例如r[0,0]
搭配dr[0,0]
, r[0,1]
与 dr[0,1]
等等。有什么想法吗?
最佳答案
您可以将 2D 掩码与输入数组相乘,这实际上是掩码,从而执行计算,生成 2D 数组,而不是迄今为止使用 bool 索引的 1D 数组。唯一的区别是将值设置到输出数组中,为此您需要屏蔽要设置的数组和从中选择值的 2D 计算数组。
实现看起来像这样 -
# Initialize output array
res = np.zeros(r.shape)
# Get mask1 and compute values for all elements and use the mask to set only
# TRUE positions with the computed values
mask1 = (r >= 0.5*dr) & (r <= 1.5*dr)
V1 = (5-3*np.abs(r*mask1)/dr - np.sqrt(-3*(1-np.abs(r*mask1)/dr)**2+1))/(6*dr)
res[mask1] = V1[mask1]
# Similarly for mask2 and the computations with that mask
mask2 = np.logical_not(mask1) & (r <= 0.5*dr)
V2 = (1+np.sqrt(-3*(r*mask2/dr)**2+1))/(3*dr)
res[mask2] = V2[mask2]
关于python - 功能变化不大。面具。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781420/
我是一名优秀的程序员,十分优秀!