Holding a subexpression in numexpr

How to effectively express the following using numexpr ?

 z = min(xy, 1.0) / (x+y) 

Here x and y are some large NumPy arrays of the same shape.

In other words, I am trying to hide xy to 1.0 before dividing it by x+y .

I would like to do this using a single numexpr expression ( x and y huge, and I don't want to be iterated over more than once).

+4
source share
1 answer

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 
+6
source

Source: https://habr.com/ru/post/1416226/


All Articles