From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 Returns the value at a given percentile in a sorted numeric array. "Linear interpolation between closest ranks" method
15423
function percentile(arr, p) {
    if (arr.length === 0) return 0;
    if (typeof p !== 'number') throw new TypeError('p must be a number');
    if (p <= 0) return arr[0];
    if (p >= 1) return arr[arr.length - 1];

    var index = arr.length * p,
        lower = Math.floor(index),
        upper = lower + 1,
        weight = index % 1;

    if (upper >= arr.length) return arr[lower];
    return arr[lower] * (1 - weight) + arr[upper] * weight;
}
772162
public static <T, U> Collector<T, ?, Optional<T>> medianBy(Function<? super T, ? extends U> function, Comparator<? super U> comparator) {
        return percentileBy(0.5, function, comparator);
    }
611433
function sortedLastIndexForNum(array, value) {
    let low = 0
    let high = array == null ? low : array.length

    while (low < high) {
        const mid = (low + high) >>> 1
        const computed = array[mid]
        if (computed <= value) {
            low = mid + 1
        } else {
            high = mid
        }
    }
    return high
}
342524
def _numpy_index_by_percentile(self, data, percentile):
        
        data_perc_low = np.nanpercentile(data, percentile, axis=0, interpolation=self.interpolation)

        indices = np.empty(data_perc_low.shape, dtype=np.uint8)
        indices[:] = np.nan

        abs_diff = np.where(np.isnan(data_perc_low), np.inf, abs(data - data_perc_low))

        indices = np.where(np.isnan(data_perc_low), self.max_index, np.nanargmin(abs_diff, axis=0))

        return indices
450996
def percentile(self, percentile):
        """"""
        return self.bin_centers[np.argmin(np.abs(self.cumulative_density * 100 - percentile))]
193453
def perc(arr, p=95, **kwargs):
    """"""
    offset = (100 - p) / 2
    return np.percentile(arr, (offset, 100 - offset), **kwargs)
873444
def median(ls):
    
    ls = sorted(ls)
    return ls[int(floor(len(ls)/2.0))]
491219
public int getValueAtPercentile(double percentile) {
        int permyriad = (int) (percentile * 100);
        switch (permyriad) {
            case 0: return p0;
            case 500: return p5;
            case 1000: return p10;
            case 1500: return p15;
            case 2000: return p20;
            case 2500: return p25;
            case 3000: return p30;
            case 3500: return p35;
            case 4000: return p40;
            case 4500: return p45;
            case 5000: return p50;
            case 5500: return p55;
            case 6000: return p60;
            case 6500: return p65;
            case 7000: return p70;
            case 7500: return p75;
            case 8000: return p80;
            case 8500: return p85;
            case 9000: return p90;
            case 9500: return p95;
            case 9900: return p99;
            case 9950: return p99_5;
            case 9990: return p99_9;
            case 9995: return p99_95;
            case 9999: return p99_99;
            case 10000: return p100;
            default: throw new IllegalArgumentException("Percentile (" + percentile + ") is not currently cached");
        }
    }
954425
public static <T> Collector<T, ?, Optional<T>> median(Comparator<? super T> comparator) {
        return percentile(0.5, comparator);
    }
887138
def closest_values(L):
    
    assert len(L) >= 2
    L.sort()
    valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))
    return L[argmin - 1], L[argmin]
533503
def percentile(values=None, percentile=None):
    
    if values in [None, tuple(), []] or len(values) < 1:
        raise InsufficientData(
            "Expected a sequence of at least 1 integers, got {0!r}".format(values))
    if percentile is None:
        raise ValueError("Expected a percentile choice, got {0}".format(percentile))

    sorted_values = sorted(values)

    rank = len(values) * percentile / 100
    if rank > 0:
        index = rank - 1
        if index < 0:
            return sorted_values[0]
    else:
        index = rank

    if index % 1 == 0:
        return sorted_values[int(index)]
    else:
        fractional = index % 1
        integer = int(index - fractional)
        lower = sorted_values[integer]
        higher = sorted_values[integer + 1]
        return lower + fractional * (higher - lower)
3829
func Percentile(input stats.Float64Data, percent float64) (percentile float64, err error) {

	if input.Len() == 0 {
		return math.NaN(), stats.EmptyInput
	}

	if percent < 0 || percent > 100 {
		return math.NaN(), stats.BoundsErr
	}

	// Start by sorting a copy of the slice
	sorted := sortedCopy(input)

	// Edge cases
	if percent == 0.0 { // The percentile argument of 0 will return the minimum value in the dataset.
		return sorted[0], nil
	}
	if percent == 50.0 { // The percentile argument of 50 returns the median value.
		return sorted.Median()
	}
	if percent == 100.0 { // The percentile argument of 100 returns the maximum value from the dataset.
		return sorted[len(sorted)-1], nil
	}

	// Find the rank. Rank is the position of an element in the dataset.
	rank := ((percent / 100) * float64(len(sorted)-1))

	ri := int(rank)
	rf := rank - float64(ri)

	percentile = sorted[ri] + rf*(sorted[ri+1]-sorted[ri])
	return
}
54061
def interpolate_at_i(self, i, unit=None):
        
        if isinstance(self.call.i._value, float):
            if self.call.i._value==i:
                return self._to_unit(self._value, unit)
            else:
                return None

        # we can't call i._value here because that may point to a string, and
        # we want this to resolve the array
        i_value = self.call.i.get_value(linebreak=False, sort_by_indep=False)
        if len(i_value) != len(self._value):
            raise ValueError("length mismatch with independent-variable")

        sort_inds = i_value.argsort()
        indep_value = i_value[sort_inds]
        this_value = self._value[sort_inds]
        return self._to_unit(np.interp(i, indep_value, this_value, left=np.nan, right=np.nan), unit)
1242564
def numpy_weighted_median(data, weights=None):
    """"""
    import numpy as np
    if weights is None:
        return np.median(np.array(data).flatten())
    data, weights = np.array(data).flatten(), np.array(weights).flatten()
    if any(weights > 0):
        sorted_data, sorted_weights = map(np.array, zip(*sorted(zip(data, weights))))
        midpoint = 0.5 * sum(sorted_weights)
        if any(weights > midpoint):
            return (data[weights == np.max(weights)])[0]
        cumulative_weight = np.cumsum(sorted_weights)
        below_midpoint_index = np.where(cumulative_weight <= midpoint)[0][-1]
        if cumulative_weight[below_midpoint_index] - midpoint < sys.float_info.epsilon:
            return np.mean(sorted_data[below_midpoint_index:below_midpoint_index+2])
        return sorted_data[below_midpoint_index+1]
303616
def index_nearest(array, value):
    
    idx = (np.abs(array-value)).argmin()
    return idx
298052
def percent_rank(expr, sort=None, ascending=True):
    
    return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending)
363303
def percentile(perc)
      if perc > 100.0 || perc < 0.0
        raise InvalidPercentile, "percentile must be between 0.0 and 100.0"
      end
      return 0.0 if data.empty?

      rank = (perc / 100.0) * (size + 1)

      return data[0]          if rank < 1
      return data[-1]         if rank > size
      return data[rank - 1]   if rank == Integer(rank)
      weighted_average_for(rank)
    end