快速计算条件函数的方法

ich*_*nob 5 python performance numpy

什么是计算函数最快的方法

# here x is just a number
def f(x):
    if x >= 0:
        return np.log(x+1)
    else:
        return -np.log(-x+1)
Run Code Online (Sandbox Code Playgroud)

一种可能的方法是:

# here x is an array
def loga(x)
    cond = [x >= 0, x < 0]
    choice = [np.log(x+1), -np.log(-x+1)
    return np.select(cond, choice)
Run Code Online (Sandbox Code Playgroud)

但似乎numpy逐个元素地遍历数组.有没有办法使用概念上类似于np.exp(x)的东西来获得更好的性能?

use*_*079 6

    def f(x):
        return (x/abs(x)) * np.log(1+abs(x))
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用`numpy.sign(x)`而不是`x/abs(x)`,以避免可能被零除.`np.copysign(np.log(1 + abs(x)),x)`将是另一种方式. (2认同)