Maybe something like this will work?
In [11]: import numpy as np In [12]: import numexpr as ne In [13]: In [13]: x = np.linspace(0.02, 5.0, 1e7) In [14]: y = np.sin(x) In [15]: In [15]: timeit z0 = ((xy) - ((xy) > 1) * (xy - 1))/(x+y) 1 loops, best of 3: 1.02 s per loop In [16]: timeit z1 = ne.evaluate("((xy) - ((xy) > 1.) * ((xy) - 1.))/(x+y)") 10 loops, best of 3: 120 ms per loop In [17]: timeit z2 = ne.evaluate("((xy)/(x+y))") 10 loops, best of 3: 103 ms per loop
There’s a fine for capping the division, but that’s not so bad. Unfortunately, when I tried it for some larger arrays, it was interrupted .: - /
Update: this is much prettier and a little faster:
In [40]: timeit w0 = ne.evaluate("where(xy>1,1,xy)/(x+y)") 10 loops, best of 3: 114 ms per loop
source share