from fractions import Fraction from math import ceil, inf, isfinite def threshold(residuals, alpha): if not isinstance(alpha, Fraction): raise TypeError('Use Fraction for alpha') if not 0 < alpha < 1: raise ValueError('alpha must be between zero and one') values = list(residuals) if not values or any(not isfinite(v) or v < 0 for v in values): raise ValueError('Provide finite nonnegative residuals') values.sort() rank = ceil((len(values) + 1) * (1 - alpha)) return inf if rank > len(values) else values[rank - 1] def interval(prediction, radius): return prediction - radius, prediction + radius def demo(): predicted = [100] * 9 observed = [101, 98, 103, 96, 105, 94, 107, 92, 109] residuals = [abs(y - p) for p, y in zip(predicted, observed)] q = threshold(residuals, Fraction(1, 5)) bounds = interval(120, q) assert q == 8 assert bounds == (112, 128) assert bounds[0] <= 127 <= bounds[1] assert not bounds[0] <= 129 <= bounds[1] assert threshold(residuals, Fraction(1, 10)) == 9 assert threshold(residuals, Fraction(1, 20)) == inf return {'radius_mm': q, 'interval_mm': bounds} if __name__ == '__main__': print(demo())