Consider the following code:
>>> import numpy as np
>>> l = [21,22,24,24,26,97]
>>> np.quantile(l, 0.25)
22.5
The documentation says:
linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.
Could anyone please explain what are i
, j
and fraction
in this example and how we get 22.5
?
It works roughly like this:
import numpy as np
def my_quantile(array, q):
n = len(array)
index = (n - 1) * q
if int(index) == index: # has no fractional part
return array[index]
fraction = index - int(index)
left = int(index)
right = left + 1
i, j = array[left], array[right]
return i + (j - i) * fraction
if __name__ == '__main__':
arr = [21, 22, 24, 24, 26, 97]
assert my_quantile(arr, 0.33) == np.quantile(arr, 0.33)
assert my_quantile(arr, 0.25) == np.quantile(arr, 0.25)
assert my_quantile(arr, 0.75) == np.quantile(arr, 0.75)