gpt4 book ai didi

python - 功能变化不大。面具。 Python

转载 作者:行者123 更新时间:2023-12-01 04:20:31 24 4
gpt4 key购买 nike

我有以下功能:

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

哪里rnumpy.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com