Index search where one sequence is larger than another

I have two numpy arrays, and I would like to find an index by which the data in one array becomes larger than the others. The following code seems to do the trick, but I'm wondering if there is a better way:

# For example import numpy as np x=np.arange(-10,10,0.01) f1 = x+3.0 f2 = 2*x cross_over_index = np.nonzero(f2 > f1)[0][0] 
+4
source share
2 answers

Since your question only makes sense if the arrays are ordered, you can find the intersection point with the binary search, which will be much faster for large arrays:

 # Find first index of a2 > a1 def crossover(a1, a2): bottom = 0 top = min(len(a1) - 1, len(a2) - 1) if a2[top] <= a1[top]: return -1 while top > bottom: mid = (top + bottom) >> 1 if a2[mid] > a1[mid]: top = mid else: bottom = mid + 1 return top f1 = [ (x + 20) for x in range(80) ] f2 = [ (2 * x) for x in range(100) ] print( crossover( f1, f2 ) ) 

This should (and does) type "21".

0
source

If you are looking for a solution to the equation f 1 (x) = f 2 (x), you can also do this:

 np.argmin(abs(f2-f1)) # 1300 

and get x course

 x[np.argmin(abs(f2-f1))] # 3.0 

But note that this will only sometimes give the same answer as the technically requested one (which in this example returns i0 --> 1301 and x0 --> 3.01 (which is the solution plus stepize x ).

0
source

All Articles