source: trunk/lib/statistics/utility.h @ 464

Last change on this file since 464 was 464, checked in by Peter, 17 years ago

made median template

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 1.8 KB
Line 
1// $Id: utility.h 464 2005-12-16 22:15:25Z peter $
2
3#ifndef _theplu_statistics_utility_
4#define _theplu_statistics_utility_
5
6#include <algorithm>
7#include <cmath>
8#include <vector>
9
10namespace theplu {
11namespace statistics { 
12
13  ///
14  /// Calculates the probabilty to get \a k or smaller from a
15  /// hypergeometric distribution with parameters \a n1 \a n2 \a
16  /// t. Hypergeomtric situation you get in the following situation:
17  /// Let there be \a n1 ways for a "good" selection and \a n2 ways
18  /// for a "bad" selection out of a total of possibilities. Take \a
19  /// t samples without replacement and \a k of those are "good"
20  /// samples. \a k will follow a hypergeomtric distribution.
21  /// @cumulative hypergeomtric distribution functions P(k).
22  ///
23  double cdf_hypergeometric_P(u_int k, u_int n1, u_int n2, u_int t);
24
25
26  ///
27  /// The percentile is determined by the \a p, a number between 0
28  /// and 100. The percentile is found by interpolation, using the
29  /// formula \f$ percentile = (1 - \delta) x_i + \delta x_{i+1} \f$
30  /// where \a p is floor\f$((n - 1)p/100)\f$ and \f$ \delta \f$ is
31  /// \f$ (n-1)p/100 - i \f$.Thus the minimum value of the vector is
32  /// given by p equal to zero, the maximum is given by p equal to
33  /// 100 and the median value is given by p equal to 50.
34  ///
35  /// @return \a p'th percentile
36  ///
37  template <class T>
38  double percentile(std::vector<T>& vec, double p)
39  {
40    if (p==100)
41      return  vec[vec.size()-1];
42    sort(vec.begin(), vec.end());
43    double j = p/100 * (vec.size()-1);
44    int i = static_cast<int>(j);
45    return (1-j+floor(j))*vec[i] + (j-floor(j))*vec[i+1];
46 
47  }
48
49  ///
50  /// Median is defined to be value in the middle. If number of
51  /// values is even median is the average of the two middle
52  /// values. @return median
53  ///
54  template <class T> 
55  inline double median(std::vector<T>& v) { return percentile(v,50.0); }
56
57 
58}} // of namespace statistics and namespace theplu
59
60#endif
61
Note: See TracBrowser for help on using the repository browser.