如何使此函数能够使用numpy数组作为参数并在python中返回数组?

2024-09-30 18:15:15 发布

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

如何使此函数能够使用numpy数组作为参数,并返回与python中按元素应用tan()时大小相同的数组? 我当前的代码如下所示,但它并没有为这两个选项返回完整的数组。如何使用tanc()值创建输出数组?你知道吗

def tanc(x):

    if x == 0:
        return 1
    else:
        return np.tan(x)/x

希望输出如下: array([ 1.0, 0.27323654e+00, -4.89610183e-17])


Tags: 函数代码numpy元素参数returnifdef
3条回答

使用掩码对每个元素的条件进行编码:

mask = (x != 0)

可以对满足条件的数据部分应用numpy操作:

output = np.zeros(x.shape, dtype=float)
output[~mask] = 1
output[mask] = tan(x[mask]) / x[mask]

全部(减少冗余操作):

def tanc(x):
    output = np.zeros(x.shape, dtype=float)
    output[~mask] = 1
    selected = x[mask]
    output[mask] = tan(selected) / selected
    return output

后脚本

根据我的选择,@jirasaimok's excellent answer是一种更优雅的(numpythonic,如果您愿意的话)方法来完成同样的事情:避免每个元素进行一次以上的计算,并避免零除法。我建议可以使用tandivideout关键字进一步增强他们的答案,以避免分配和复制不必要的临时数组:

def tanc(x):
    mask = (x != 0)
    output = np.tan(x, where=mask)
    np.divide(output, x, where=mask, out=output)
    output[~mask] = 1
    return output

或者更好:

def tanc(x):
    mask = (x != 0)
    output = np.tan(x, where=mask, out=np.ones(x.shape, float))
    return np.divide(output, x, where=mask, out=output)

你可以简单地做:

def tanc(x):
    return np.sinc(x/np.pi)/np.cos(x)

可以使用^{},并将where参数设置为^{}^{}。你知道吗

np.where(cond, a, b)给出一个数组,其中来自a的值用于cond的真实元素,b的元素用于cond的虚假元素。你知道吗

np.dividenp.tanwhere参数告诉它们只在另一个数组中为真的位置执行操作,并保留一些未初始化的其他元素(因此它们可以是任何元素,但这并不重要,因为这里不使用它们)。你知道吗

nonzero = x != 0 # we only care about places where x isn't 0
# Get tan, then divide by x, but only where x is not 0
nonzero_tan = np.tan(x, where=nonzero)
nonzero_tanc = np.divide(nonzero_tan, x, where=nonzero)
# Where x is not zero, use tan(x)/x, and use 1 everywhere else
tanc = np.where(nonzero, nonzero_tanc, 1)

正如hpaulj在他们的注释中所建议的,您还可以通过使用np.divideout参数来定义输出数组的默认值来组合最后两个步骤:

nonzero = x != 0
nonzero_tan = np.tan(x, where=nonzero)
tanc = np.divide(nonzero_tan, x, out=np.ones_like(x), where=nonzero)

相关问题 更多 >