功能变化不大。面具。 Python
Little change in a function. Mask. Python
我有以下功能:
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
是大小为 (shape[0],shape[1])
的 numpy.array
,dr
是单个值。
我想修改函数以使 dr
也是一个与 r
大小相同的数组,并且对于 r
的每个值都从 dr
.[=24 中获取类似的值=]
例如 r[0,0]
与 dr[0,0]
、r[0,1]
与 dr[0,1]
等。
有什么想法吗?
您可以将 2D 掩码与输入数组相乘,这实际上是掩码,因此执行计算得到的是 2D 数组,而不是目前为止使用布尔索引的 1D 数组。唯一的区别是将值设置到输出数组中,为此您需要屏蔽要设置的数组和将从中选择值的二维计算数组。
实现看起来像这样 -
# 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]
我有以下功能:
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
是大小为 (shape[0],shape[1])
的 numpy.array
,dr
是单个值。
我想修改函数以使 dr
也是一个与 r
大小相同的数组,并且对于 r
的每个值都从 dr
.[=24 中获取类似的值=]
例如 r[0,0]
与 dr[0,0]
、r[0,1]
与 dr[0,1]
等。
有什么想法吗?
您可以将 2D 掩码与输入数组相乘,这实际上是掩码,因此执行计算得到的是 2D 数组,而不是目前为止使用布尔索引的 1D 数组。唯一的区别是将值设置到输出数组中,为此您需要屏蔽要设置的数组和将从中选择值的二维计算数组。
实现看起来像这样 -
# 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]