00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #ifndef _BINOMIAL_H
00022 #define _BINOMIAL_H
00023
00024 #include <iostream>
00025
00026 #include <math.h>
00027
00028 #include "constants.h"
00029
00030 inline double log_fac(int n)
00031 {
00032
00033 if (0 == n)
00034 return(0);
00035 if (1 == n)
00036 return(0);
00037 return(0.5*log(2 * PI * n) + n*log(n/E));
00038 }
00039
00040 inline double fac(int n)
00041 {
00042 return(exp(log_fac(n)));
00043 }
00044
00045 inline double log_choose(int n, int k)
00046 {
00047 return(log_fac(n) - log_fac(k) - log_fac(n - k));
00048 }
00049
00050 inline double choose(int n, int k)
00051 {
00052 return(exp(log_choose(n, k)));
00053 }
00054
00055 inline double log_prob_binomial(int n, int k, double prob)
00056 {
00057 if (n < k)
00058 {
00059 #ifdef DEBUG
00060 cerr << "log_prob_binomial(): n = " << n << " < k = " << k << ", returning 0.\n";
00061 #endif
00062 return(0);
00063 }
00064 if (0 > n )
00065 {
00066 #ifdef DEBUG
00067 cerr << "log_prob_binomial(): n = " << n << " < 0, returning 0.\n";
00068 #endif
00069 return(0);
00070 }
00071 if (1 < prob)
00072 {
00073 #ifdef DEBUG
00074 cerr << "log_prob_binomial(): p = " << prob << " >= 1, returning 0.\n";
00075 #endif
00076 return(0);
00077 }
00078 if (1 == prob)
00079 {
00080 if (n != k)
00081 {
00082 #ifdef DEBUG
00083
00084
00085 #endif
00086 return(0);
00087 }
00088 else
00089 {
00090 #ifdef DEBUG
00091
00092
00093 #endif
00094 return(1);
00095 }
00096 }
00097 if (0 > prob)
00098 {
00099 #ifdef DEBUG
00100 cerr << "log_prob_binomial(): p = " << prob << " <= 0, returning 0.\n";
00101 #endif
00102 return(0);
00103 }
00104 if (0 == prob)
00105 {
00106 if (0 != k)
00107 {
00108 #ifdef DEBUG
00109
00110
00111 #endif
00112 return(0);
00113 }
00114 else
00115 {
00116 #ifdef DEBUG
00117
00118
00119 #endif
00120 return(1);
00121 }
00122 }
00123 return(log_choose(n, k) + k*log(prob) + (n - k)*log(1 - prob));
00124 }
00125
00126 inline double sum_binomial_probs(int n, int start, int end, double prob)
00127 {
00128 double sum = 0;
00129 for (int i = start; i <= end; i++)
00130 {
00131 sum += exp(log_prob_binomial(n, i, prob));
00132 }
00133 return(sum);
00134 }
00135
00136
00137
00138
00139 inline double sum_binomial_product(int total, int specialSize, int sampleSize,
00140 int specialSizeInSample)
00141 {
00142 int i;
00143 double sum = 0;
00144 for (i = specialSizeInSample; i < sampleSize; i++)
00145
00146 sum += choose(specialSize, i)*choose(total - specialSize, sampleSize - i);
00147
00148 sum = sum/choose(total, sampleSize);
00149 return(sum);
00150 }
00151
00152 #endif // _BINOMIAL_H