CLHEP VERSION Reference Documentation
   
CLHEP Home Page     CLHEP Documentation     CLHEP Bug Reports

RandBinomial.cc

Go to the documentation of this file.
00001 // $Id: RandBinomial.cc,v 1.5 2010/06/16 17:24:53 garren Exp $
00002 // -*- C++ -*-
00003 //
00004 // -----------------------------------------------------------------------
00005 //                             HEP Random
00006 //                        --- RandBinomial ---
00007 //                      class implementation file
00008 // -----------------------------------------------------------------------
00009 
00010 // =======================================================================
00011 // John Marraffino - Created: 12th May 1998
00012 // M Fischler     - put and get to/from streams 12/10/04
00013 // M Fischler         - put/get to/from streams uses pairs of ulongs when
00014 //                      + storing doubles avoid problems with precision 
00015 //                      4/14/05
00016 //
00017 // =======================================================================
00018 
00019 #include "CLHEP/Random/RandBinomial.h"
00020 #include "CLHEP/Random/defs.h"
00021 #include "CLHEP/Random/DoubConv.hh"
00022 #include <algorithm>    // for min() and max()
00023 #include <cmath>        // for exp()
00024 
00025 namespace CLHEP {
00026 
00027 std::string RandBinomial::name() const {return "RandBinomial";}
00028 HepRandomEngine & RandBinomial::engine() {return *localEngine;}
00029 
00030 RandBinomial::~RandBinomial() {
00031 }
00032 
00033 double RandBinomial::shoot( HepRandomEngine *anEngine, long n,
00034                                                           double p ) {
00035   return genBinomial( anEngine, n, p );
00036 }
00037 
00038 double RandBinomial::shoot( long n, double p ) {
00039   HepRandomEngine *anEngine = HepRandom::getTheEngine();
00040   return genBinomial( anEngine, n, p );
00041 }
00042 
00043 double RandBinomial::fire( long n, double p ) {
00044   return genBinomial( localEngine.get(), n, p );
00045 }
00046 
00047 void RandBinomial::shootArray( const int size, double* vect,
00048                             long n, double p )
00049 {
00050   for( double* v = vect; v != vect+size; ++v )
00051     *v = shoot(n,p);
00052 }
00053 
00054 void RandBinomial::shootArray( HepRandomEngine* anEngine,
00055                             const int size, double* vect,
00056                             long n, double p )
00057 {
00058   for( double* v = vect; v != vect+size; ++v )
00059     *v = shoot(anEngine,n,p);
00060 }
00061 
00062 void RandBinomial::fireArray( const int size, double* vect)
00063 {
00064   for( double* v = vect; v != vect+size; ++v )
00065     *v = fire(defaultN,defaultP);
00066 }
00067 
00068 void RandBinomial::fireArray( const int size, double* vect,
00069                            long n, double p )
00070 {
00071   for( double* v = vect; v != vect+size; ++v )
00072     *v = fire(n,p);
00073 }
00074 
00075 /*************************************************************************
00076  *                                                                       *
00077  *  StirlingCorrection()                                                 *
00078  *                                                                       *
00079  *  Correction term of the Stirling approximation for std::log(k!)            *
00080  *  (series in 1/k, or table values for small k)                         *
00081  *  with long int parameter k                                            *
00082  *                                                                       *
00083  *************************************************************************
00084  *                                                                       *
00085  * log k! = (k + 1/2)log(k + 1) - (k + 1) + (1/2)log(2Pi) +              *
00086  *          StirlingCorrection(k + 1)                                    *
00087  *                                                                       *
00088  * log k! = (k + 1/2)log(k)     -  k      + (1/2)log(2Pi) +              *
00089  *          StirlingCorrection(k)                                        *
00090  *                                                                       *
00091  *************************************************************************/
00092 
00093 static double StirlingCorrection(long int k)
00094 {
00095   #define   C1               8.33333333333333333e-02     //  +1/12 
00096   #define   C3              -2.77777777777777778e-03     //  -1/360
00097   #define   C5               7.93650793650793651e-04     //  +1/1260
00098   #define   C7              -5.95238095238095238e-04     //  -1/1680
00099 
00100   static double  c[31] = {   0.0,
00101                              8.106146679532726e-02, 4.134069595540929e-02,
00102                              2.767792568499834e-02, 2.079067210376509e-02,
00103                              1.664469118982119e-02, 1.387612882307075e-02,
00104                              1.189670994589177e-02, 1.041126526197209e-02,
00105                              9.255462182712733e-03, 8.330563433362871e-03,
00106                              7.573675487951841e-03, 6.942840107209530e-03,
00107                              6.408994188004207e-03, 5.951370112758848e-03,
00108                              5.554733551962801e-03, 5.207655919609640e-03,
00109                              4.901395948434738e-03, 4.629153749334029e-03,
00110                              4.385560249232324e-03, 4.166319691996922e-03,
00111                              3.967954218640860e-03, 3.787618068444430e-03,
00112                              3.622960224683090e-03, 3.472021382978770e-03,
00113                              3.333155636728090e-03, 3.204970228055040e-03,
00114                              3.086278682608780e-03, 2.976063983550410e-03,
00115                              2.873449362352470e-03, 2.777674929752690e-03,
00116   };
00117   double    r, rr;
00118 
00119   if (k > 30L) {
00120     r = 1.0 / (double) k;  rr = r * r;
00121     return(r*(C1 + rr*(C3 + rr*(C5 + rr*C7))));
00122         }
00123         else  return(c[k]);
00124 }
00125 
00126 double RandBinomial::genBinomial( HepRandomEngine *anEngine, long n, double p )
00127 {
00128 /******************************************************************
00129  *                                                                *
00130  *     Binomial-Distribution - Acceptance Rejection/Inversion     *
00131  *                                                                *
00132  ******************************************************************
00133  *                                                                *
00134  * Acceptance Rejection method combined with Inversion for        *
00135  * generating Binomial random numbers with parameters             *
00136  * n (number of trials) and p (probability of success).           *
00137  * For  min(n*p,n*(1-p)) < 10  the Inversion method is applied:   *
00138  * The random numbers are generated via sequential search,        *
00139  * starting at the lowest index k=0. The cumulative probabilities *
00140  * are avoided by using the technique of chop-down.               *
00141  * For  min(n*p,n*(1-p)) >= 10  Acceptance Rejection is used:     *
00142  * The algorithm is based on a hat-function which is uniform in   *
00143  * the centre region and exponential in the tails.                *
00144  * A triangular immediate acceptance region in the centre speeds  *
00145  * up the generation of binomial variates.                        *
00146  * If candidate k is near the mode, f(k) is computed recursively  *
00147  * starting at the mode m.                                        *
00148  * The acceptance test by Stirling's formula is modified          *
00149  * according to W. Hoermann (1992): The generation of binomial    *
00150  * random variates, to appear in J. Statist. Comput. Simul.       *
00151  * If  p < .5  the algorithm is applied to parameters n, p.       *
00152  * Otherwise p is replaced by 1-p, and k is replaced by n - k.    *
00153  *                                                                *
00154  ******************************************************************
00155  *                                                                *
00156  * FUNCTION:    - btpec samples a random number from the binomial *
00157  *                distribution with parameters n and p  and is    *
00158  *                valid for  n*min(p,1-p)  >  0.                  *
00159  * REFERENCE:   - V. Kachitvichyanukul, B.W. Schmeiser (1988):    *
00160  *                Binomial random variate generation,             *
00161  *                Communications of the ACM 31, 216-222.          *
00162  * SUBPROGRAMS: - StirlingCorrection()                            *
00163  *                            ... Correction term of the Stirling *
00164  *                                approximation for std::log(k!)       *
00165  *                                (series in 1/k or table values  *
00166  *                                for small k) with long int k    *
00167  *              - anEngine    ... Pointer to a (0,1)-Uniform      * 
00168  *                                engine                          *
00169  *                                                                *
00170  * Implemented by H. Zechner and P. Busswald, September 1992      *
00171  ******************************************************************/
00172 
00173 #define C1_3     0.33333333333333333
00174 #define C5_8     0.62500000000000000
00175 #define C1_6     0.16666666666666667
00176 #define DMAX_KM  20L
00177 
00178   static long int      n_last = -1L,  n_prev = -1L;
00179   static double        par,np,p0,q,p_last = -1.0, p_prev = -1.0;
00180   static long          b,m,nm;
00181   static double        pq, rc, ss, xm, xl, xr, ll, lr, c,
00182                                  p1, p2, p3, p4, ch;
00183 
00184   long                 bh,i, K, Km, nK;
00185   double               f, rm, U, V, X, T, E;
00186 
00187   if (n != n_last || p != p_last)                 // set-up 
00188         {
00189          n_last = n;
00190          p_last = p;
00191          par=std::min(p,1.0-p);
00192          q=1.0-par;
00193          np = n*par;
00194 
00195 // Check for invalid input values
00196 
00197          if( np <= 0.0 ) return (-1.0);
00198 
00199          rm = np + par;
00200          m  = (long int) rm;                      // mode, integer 
00201          if (np<10)
00202         {
00203          p0=std::exp(n*std::log(q));                        // Chop-down
00204          bh=(long int)(np+10.0*std::sqrt(np*q));
00205          b=std::min(n,bh);
00206         }
00207          else
00208                  {
00209         rc = (n + 1.0) * (pq = par / q);          // recurr. relat.
00210         ss = np * q;                              // variance  
00211         i  = (long int) (2.195*std::sqrt(ss) - 4.6*q); // i = p1 - 0.5
00212         xm = m + 0.5;
00213         xl = (double) (m - i);                    // limit left 
00214         xr = (double) (m + i + 1L);               // limit right
00215         f  = (rm - xl) / (rm - xl*par);  ll = f * (1.0 + 0.5*f);
00216         f  = (xr - rm) / (xr * q);     lr = f * (1.0 + 0.5*f);
00217         c  = 0.134 + 20.5/(15.3 + (double) m);    // parallelogram
00218                                                   // height
00219         p1 = i + 0.5;
00220         p2 = p1 * (1.0 + c + c);                  // probabilities
00221         p3 = p2 + c/ll;                           // of regions 1-4
00222         p4 = p3 + c/lr;
00223                  }
00224   }
00225   if (np<10)                                      //Inversion Chop-down
00226          {
00227           double pk;
00228 
00229           K=0;
00230           pk=p0;
00231           U=anEngine->flat();
00232           while (U>pk)
00233                 {
00234                  ++K;
00235                  if (K>b)
00236                          {
00237                 U=anEngine->flat();
00238                 K=0;
00239                 pk=p0;
00240                          }
00241                  else
00242                          {
00243                 U-=pk;
00244                 pk=(double)(((n-K+1)*par*pk)/(K*q));
00245                          }
00246                 }
00247           return ((p>0.5) ? (double)(n-K):(double)K);
00248          }
00249 
00250   for (;;)
00251         {
00252          V = anEngine->flat();
00253          if ((U = anEngine->flat() * p4) <= p1)  // triangular region
00254                 {
00255                  K=(long int) (xm - U + p1*V);
00256         return ((p>0.5) ? (double)(n-K):(double)K);  // immediate accept
00257                 }
00258          if (U <= p2)                                // parallelogram
00259                 {
00260                  X = xl + (U - p1)/c;
00261                  if ((V = V*c + 1.0 - std::fabs(xm - X)/p1) >= 1.0)  continue;
00262                  K = (long int) X;
00263                 }
00264          else if (U <= p3)                           // left tail
00265                 {
00266                  if ((X = xl + std::log(V)/ll) < 0.0)  continue;
00267                  K = (long int) X;
00268                  V *= (U - p2) * ll;
00269                 }
00270          else                                         // right tail
00271                 {
00272                  if ((K = (long int) (xr - std::log(V)/lr)) > n)  continue;
00273                  V *= (U - p3) * lr;
00274                 }
00275 
00276  // acceptance test :  two cases, depending on |K - m|
00277          if ((Km = labs(K - m)) <= DMAX_KM || Km + Km + 2L >= ss)
00278           {
00279 
00280  // computation of p(K) via recurrence relationship from the mode
00281                 f = 1.0;                              // f(m)
00282                 if (m < K)
00283          {
00284           for (i = m; i < K; )
00285                 {
00286                 if ((f *= (rc / ++i - pq)) < V)  break;  // multiply  f
00287                 }
00288          }
00289                 else
00290          {
00291           for (i = K; i < m; )
00292                  {
00293                   if ((V *= (rc / ++i - pq)) > f)  break; // multiply  V
00294                  }
00295          }
00296                 if (V <= f)  break;                       // acceptance test
00297          }
00298   else
00299          {
00300 
00301  // lower and upper squeeze tests, based on lower bounds for log p(K)
00302                 V = std::log(V);
00303                 T = - Km * Km / (ss + ss);
00304                 E =  (Km / ss) * ((Km * (Km * C1_3 + C5_8) + C1_6) / ss + 0.5);
00305                 if (V <= T - E)  break;
00306                 if (V <= T + E)
00307                  {
00308         if (n != n_prev || par != p_prev)
00309          {
00310           n_prev = n;
00311           p_prev = par;
00312 
00313           nm = n - m + 1L;
00314           ch = xm * std::log((m + 1.0)/(pq * nm)) +
00315                StirlingCorrection(m + 1L) + StirlingCorrection(nm);
00316          }
00317         nK = n - K + 1L;
00318 
00319  // computation of log f(K) via Stirling's formula
00320  // final acceptance-rejection test
00321         if (V <= ch + (n + 1.0)*std::log((double) nm / (double) nK) +
00322                  (K + 0.5)*std::log(nK * pq / (K + 1.0)) -
00323                  StirlingCorrection(K + 1L) - StirlingCorrection(nK))  break;
00324                 }
00325          }
00326   }
00327   return ((p>0.5) ? (double)(n-K):(double)K);
00328 }
00329 
00330 std::ostream & RandBinomial::put ( std::ostream & os ) const {
00331   int pr=os.precision(20);
00332   std::vector<unsigned long> t(2);
00333   os << " " << name() << "\n";
00334   os << "Uvec" << "\n";
00335   t = DoubConv::dto2longs(defaultP);
00336   os << defaultN << " " << defaultP << " " << t[0] << " " << t[1] << "\n";
00337   os.precision(pr);
00338   return os;
00339 #ifdef REMOVED
00340   int pr=os.precision(20);
00341   os << " " << name() << "\n";
00342   os << defaultN << " " << defaultP << "\n";
00343   os.precision(pr);
00344   return os;
00345 #endif
00346 }
00347 
00348 std::istream & RandBinomial::get ( std::istream & is ) {
00349   std::string inName;
00350   is >> inName;
00351   if (inName != name()) {
00352     is.clear(std::ios::badbit | is.rdstate());
00353     std::cerr << "Mismatch when expecting to read state of a "
00354               << name() << " distribution\n"
00355               << "Name found was " << inName
00356               << "\nistream is left in the badbit state\n";
00357     return is;
00358   }
00359   if (possibleKeywordInput(is, "Uvec", defaultN)) {
00360     std::vector<unsigned long> t(2);
00361     is >> defaultN >> defaultP;
00362     is >> t[0] >> t[1]; defaultP = DoubConv::longs2double(t); 
00363     return is;
00364   }
00365   // is >> defaultN encompassed by possibleKeywordInput
00366   is >> defaultP;
00367   return is;
00368 }
00369 
00370 
00371 }  // namespace CLHEP

Generated on 15 Nov 2012 for CLHEP by  doxygen 1.4.7