EagleTamer
EagleTamer

Reputation: 57

Numpy: finding the indices of the 2 numbers in an array that is closest to input

I have a large array with values from 0 to 360 in increments of .08. So I have an input value and I need to go through this large array and find the 2 closest values: the one that is greater and the one that is less. For example (simplified):

array = [0, .08, .16, .24, .32, .40]

input = .10 (variable)
output = [1,2]

since .10 is in between .08 and .16 the indices will be 1 and 2. Thanks in advance for the help!!

Upvotes: 0

Views: 81

Answers (3)

B. M.
B. M.

Reputation: 18628

It looks like a arithmetic problem with O(1) solution :

a=arange(0,360,0.08)
input=123.456

i=int(input/0.08)

print(a[i:i+2])
print([i,i+1])
#[ 123.44  123.52]
#[1543, 1544]

Upvotes: 0

f5r5e5d
f5r5e5d

Reputation: 3706

looks like numpy has the function nailed: searchsorted

array = [0, .03, .05, .16, .24, .32, .40]
input = 0.1
undx = np.searchsorted(array, input)

array[undx-1], input, array[undx]
Out[6]: (0.05, 0.1, 0.16)

Upvotes: 2

Longwen Ou
Longwen Ou

Reputation: 879

If your step isn't constant, you can use bisect assuming you array is sorted.

import bisect

array = [0, .03, .05, .16, .24, .32, .40]
input = 0.1
ind = bisect.bisect_left(array, input)
print([ind - 1, ind])

Results:

[2, 3]

Upvotes: 3

Related Questions