pythonarraysnumpynumexpr

Optimising numerical operations in numpy using numexpr


I just started using numexpr, and while the github repository seems to have some basic examples of how to use it, I couldn't clearly understand how those would apply to some complicated cases. Suppose I have a function:

def func(x):
  #x is a numpy array of very large size
  return 0.5*np.exp(-x**2)*x**(1/3)+np.exp(-x)*(1.5*np.sqrt(x)+0.3/(1.+x))

What would be the equivalent way of writing this using numexpr?


Solution

  • np.sqrtsqrt; np.expexp

    import numexpr as ne
    y = ne.evaluate(
        '.5 * exp(-x ** 2) * x ** (1 / 3)' 
        '+ exp(-x) * (1.5 * sqrt(x)'
        '+ .3 / (1. + x))'
    )