Returns the value from the sorted list at point p (0.0-1.0). If p falls between two items in the list, the return value is interpolated. For example, quantile(list, p=0.5) = median(list)
(list, p=0.5, sort=True, a=1, b=-1, c=0, d=1)
| 631 | #--- QUANTILE -------------------------------------------------------------------------------------- |
| 632 | |
| 633 | def quantile(list, p=0.5, sort=True, a=1, b=-1, c=0, d=1): |
| 634 | """ Returns the value from the sorted list at point p (0.0-1.0). |
| 635 | If p falls between two items in the list, the return value is interpolated. |
| 636 | For example, quantile(list, p=0.5) = median(list) |
| 637 | """ |
| 638 | # Based on: Ernesto P. Adorio, http://adorio-research.org/wordpress/?p=125 |
| 639 | # Parameters a, b, c, d refer to the algorithm by Hyndman and Fan (1996): |
| 640 | # http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html |
| 641 | s = sort is True and sorted(list) or list |
| 642 | n = len(list) |
| 643 | f, i = modf(a + (b+n) * p - 1) |
| 644 | if n == 0: |
| 645 | raise ValueError, "quantile() arg is an empty sequence" |
| 646 | if f == 0: |
| 647 | return float(s[int(i)]) |
| 648 | if i < 0: |
| 649 | return float(s[int(i)]) |
| 650 | if i >= n: |
| 651 | return float(s[-1]) |
| 652 | i = int(floor(i)) |
| 653 | return s[i] + (s[i+1] - s[i]) * (c + d * f) |
| 654 | |
| 655 | #print quantile(range(10), p=0.5) == median(range(10)) |
| 656 |