nearest_element

emlib.misc.nearest_element(item, seq)[source]

Find the nearest element (the element, not the index) in seq

NB: assumes that seq is sorted (this is not checked). seq can also be a

numpy array, in which case searchsorted is used instead of bisect

Parameters:
  • item (float) – the item to search

  • seq (Union[list[float], ndarray]) – either a list of numbers, or a numpy array

Return type:

float

Returns:

the value of the nearest element of seq

Example

>>> seq = list(range(10))
>>> nearest_element(4.1, seq)
4
>>> nearest_element(3.6, [1,2,3,4,5])
4
>>> nearest_element(200, np.array([3,5,20]))
20
>>> nearest_element(0.5, [0, 1])
0
>>> nearest_element(1, [1, 1, 1])
1