Fast way to calculate conditional function

Viewed 418

What is the most fast way to calculate function like

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

One possible way is:

# 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)

But seems numpy goes through array element by element. Is there any way to use something conceptually similar to np.exp(x) to achieve better performance?

4 Answers
Related