CLHEP 2.4.6.4
C++ Class Library for High Energy Physics
Loading...
Searching...
No Matches
RandBinomial.cc
Go to the documentation of this file.
1//
2// -*- C++ -*-
3//
4// -----------------------------------------------------------------------
5// HEP Random
6// --- RandBinomial ---
7// class implementation file
8// -----------------------------------------------------------------------
9
10// =======================================================================
11// John Marraffino - Created: 12th May 1998
12// M Fischler - put and get to/from streams 12/10/04
13// M Fischler - put/get to/from streams uses pairs of ulongs when
14// + storing doubles avoid problems with precision
15// 4/14/05
16//
17// =======================================================================
18
19#include "CLHEP/Random/RandBinomial.h"
20#include "CLHEP/Random/defs.h"
21#include "CLHEP/Random/DoubConv.h"
22#include "CLHEP/Utility/thread_local.h"
23#include <algorithm> // for min() and max()
24#include <cmath> // for exp()
25#include <iostream>
26#include <vector>
27
28namespace CLHEP {
29
30std::string RandBinomial::name() const {return "RandBinomial";}
31HepRandomEngine & RandBinomial::engine() {return *localEngine;}
32
34}
35
36double RandBinomial::shoot( HepRandomEngine *anEngine, long n,
37 double p ) {
38 return genBinomial( anEngine, n, p );
39}
40
41double RandBinomial::shoot( long n, double p ) {
43 return genBinomial( anEngine, n, p );
44}
45
46double RandBinomial::fire( long n, double p ) {
47 return genBinomial( localEngine.get(), n, p );
48}
49
50void RandBinomial::shootArray( const int size, double* vect,
51 long n, double p )
52{
53 for( double* v = vect; v != vect+size; ++v )
54 *v = shoot(n,p);
55}
56
58 const int size, double* vect,
59 long n, double p )
60{
61 for( double* v = vect; v != vect+size; ++v )
62 *v = shoot(anEngine,n,p);
63}
64
65void RandBinomial::fireArray( const int size, double* vect)
66{
67 for( double* v = vect; v != vect+size; ++v )
68 *v = fire(defaultN,defaultP);
69}
70
71void RandBinomial::fireArray( const int size, double* vect,
72 long n, double p )
73{
74 for( double* v = vect; v != vect+size; ++v )
75 *v = fire(n,p);
76}
77
78/*************************************************************************
79 * *
80 * StirlingCorrection() *
81 * *
82 * Correction term of the Stirling approximation for log(k!) *
83 * (series in 1/k, or table values for small k) *
84 * with long int parameter k *
85 * *
86 *************************************************************************
87 * *
88 * log k! = (k + 1/2)log(k + 1) - (k + 1) + (1/2)log(2Pi) + *
89 * StirlingCorrection(k + 1) *
90 * *
91 * log k! = (k + 1/2)log(k) - k + (1/2)log(2Pi) + *
92 * StirlingCorrection(k) *
93 * *
94 *************************************************************************/
95
96static double StirlingCorrection(long int k)
97{
98 #define C1 8.33333333333333333e-02 // +1/12
99 #define C3 -2.77777777777777778e-03 // -1/360
100 #define C5 7.93650793650793651e-04 // +1/1260
101 #define C7 -5.95238095238095238e-04 // -1/1680
102
103 static const double c[31] = { 0.0,
104 8.106146679532726e-02, 4.134069595540929e-02,
105 2.767792568499834e-02, 2.079067210376509e-02,
106 1.664469118982119e-02, 1.387612882307075e-02,
107 1.189670994589177e-02, 1.041126526197209e-02,
108 9.255462182712733e-03, 8.330563433362871e-03,
109 7.573675487951841e-03, 6.942840107209530e-03,
110 6.408994188004207e-03, 5.951370112758848e-03,
111 5.554733551962801e-03, 5.207655919609640e-03,
112 4.901395948434738e-03, 4.629153749334029e-03,
113 4.385560249232324e-03, 4.166319691996922e-03,
114 3.967954218640860e-03, 3.787618068444430e-03,
115 3.622960224683090e-03, 3.472021382978770e-03,
116 3.333155636728090e-03, 3.204970228055040e-03,
117 3.086278682608780e-03, 2.976063983550410e-03,
118 2.873449362352470e-03, 2.777674929752690e-03,
119 };
120 double r, rr;
121
122 if (k > 30L) {
123 r = 1.0 / (double) k; rr = r * r;
124 return(r*(C1 + rr*(C3 + rr*(C5 + rr*C7))));
125 }
126 else return(c[k]);
127}
128
129double RandBinomial::genBinomial( HepRandomEngine *anEngine, long n, double p )
130{
131/******************************************************************
132 * *
133 * Binomial-Distribution - Acceptance Rejection/Inversion *
134 * *
135 ******************************************************************
136 * *
137 * Acceptance Rejection method combined with Inversion for *
138 * generating Binomial random numbers with parameters *
139 * n (number of trials) and p (probability of success). *
140 * For min(n*p,n*(1-p)) < 10 the Inversion method is applied: *
141 * The random numbers are generated via sequential search, *
142 * starting at the lowest index k=0. The cumulative probabilities *
143 * are avoided by using the technique of chop-down. *
144 * For min(n*p,n*(1-p)) >= 10 Acceptance Rejection is used: *
145 * The algorithm is based on a hat-function which is uniform in *
146 * the centre region and exponential in the tails. *
147 * A triangular immediate acceptance region in the centre speeds *
148 * up the generation of binomial variates. *
149 * If candidate k is near the mode, f(k) is computed recursively *
150 * starting at the mode m. *
151 * The acceptance test by Stirling's formula is modified *
152 * according to W. Hoermann (1992): The generation of binomial *
153 * random variates, to appear in J. Statist. Comput. Simul. *
154 * If p < .5 the algorithm is applied to parameters n, p. *
155 * Otherwise p is replaced by 1-p, and k is replaced by n - k. *
156 * *
157 ******************************************************************
158 * *
159 * FUNCTION: - btpec samples a random number from the binomial *
160 * distribution with parameters n and p and is *
161 * valid for n*min(p,1-p) > 0. *
162 * REFERENCE: - V. Kachitvichyanukul, B.W. Schmeiser (1988): *
163 * Binomial random variate generation, *
164 * Communications of the ACM 31, 216-222. *
165 * SUBPROGRAMS: - StirlingCorrection() *
166 * ... Correction term of the Stirling *
167 * approximation for log(k!) *
168 * (series in 1/k or table values *
169 * for small k) with long int k *
170 * - anEngine ... Pointer to a (0,1)-Uniform *
171 * engine *
172 * *
173 * Implemented by H. Zechner and P. Busswald, September 1992 *
174 ******************************************************************/
175
176#define C1_3 0.33333333333333333
177#define C5_8 0.62500000000000000
178#define C1_6 0.16666666666666667
179#define DMAX_KM 20L
180
181 static CLHEP_THREAD_LOCAL long int n_last = -1L, n_prev = -1L;
182 static CLHEP_THREAD_LOCAL double par,np,p0,q,p_last = -1.0, p_prev = -1.0;
183 static CLHEP_THREAD_LOCAL long b,m,nm;
184 static CLHEP_THREAD_LOCAL double pq, rc, ss, xm, xl, xr, ll, lr, c,
185 p1, p2, p3, p4, ch;
186
187 long bh,i, K, Km, nK;
188 double f, rm, U, V, X, T, E;
189
190 if (n != n_last || p != p_last) // set-up
191 {
192 n_last = n;
193 p_last = p;
194 par=std::min(p,1.0-p);
195 q=1.0-par;
196 np = n*par;
197
198// Check for invalid input values
199
200 if( np <= 0.0 ) return (-1.0);
201
202 rm = np + par;
203 m = (long int) rm; // mode, integer
204 if (np<10)
205 {
206 p0=std::exp(n*std::log(q)); // Chop-down
207 bh=(long int)(np+10.0*std::sqrt(np*q));
208 b=std::min(n,bh);
209 }
210 else
211 {
212 rc = (n + 1.0) * (pq = par / q); // recurr. relat.
213 ss = np * q; // variance
214 i = (long int) (2.195*std::sqrt(ss) - 4.6*q); // i = p1 - 0.5
215 xm = m + 0.5;
216 xl = (double) (m - i); // limit left
217 xr = (double) (m + i + 1L); // limit right
218 f = (rm - xl) / (rm - xl*par); ll = f * (1.0 + 0.5*f);
219 f = (xr - rm) / (xr * q); lr = f * (1.0 + 0.5*f);
220 c = 0.134 + 20.5/(15.3 + (double) m); // parallelogram
221 // height
222 p1 = i + 0.5;
223 p2 = p1 * (1.0 + c + c); // probabilities
224 p3 = p2 + c/ll; // of regions 1-4
225 p4 = p3 + c/lr;
226 }
227 }
228 if( np <= 0.0 ) return (-1.0);
229 if (np<10) //Inversion Chop-down
230 {
231 double pk;
232
233 K=0;
234 pk=p0;
235 U=anEngine->flat();
236 while (U>pk)
237 {
238 ++K;
239 if (K>b)
240 {
241 U=anEngine->flat();
242 K=0;
243 pk=p0;
244 }
245 else
246 {
247 U-=pk;
248 pk=(double)(((n-K+1)*par*pk)/(K*q));
249 }
250 }
251 return ((p>0.5) ? (double)(n-K):(double)K);
252 }
253
254 for (;;)
255 {
256 V = anEngine->flat();
257 if ((U = anEngine->flat() * p4) <= p1) // triangular region
258 {
259 K=(long int) (xm - U + p1*V);
260 return ((p>0.5) ? (double)(n-K):(double)K); // immediate accept
261 }
262 if (U <= p2) // parallelogram
263 {
264 X = xl + (U - p1)/c;
265 if ((V = V*c + 1.0 - std::fabs(xm - X)/p1) >= 1.0) continue;
266 K = (long int) X;
267 }
268 else if (U <= p3) // left tail
269 {
270 if ((X = xl + std::log(V)/ll) < 0.0) continue;
271 K = (long int) X;
272 V *= (U - p2) * ll;
273 }
274 else // right tail
275 {
276 if ((K = (long int) (xr - std::log(V)/lr)) > n) continue;
277 V *= (U - p3) * lr;
278 }
279
280 // acceptance test : two cases, depending on |K - m|
281 if ((Km = std::labs(K - m)) <= DMAX_KM || Km + Km + 2L >= ss)
282 {
283
284 // computation of p(K) via recurrence relationship from the mode
285 f = 1.0; // f(m)
286 if (m < K)
287 {
288 for (i = m; i < K; )
289 {
290 if ((f *= (rc / ++i - pq)) < V) break; // multiply f
291 }
292 }
293 else
294 {
295 for (i = K; i < m; )
296 {
297 if ((V *= (rc / ++i - pq)) > f) break; // multiply V
298 }
299 }
300 if (V <= f) break; // acceptance test
301 }
302 else
303 {
304
305 // lower and upper squeeze tests, based on lower bounds for log p(K)
306 V = std::log(V);
307 T = - Km * Km / (ss + ss);
308 E = (Km / ss) * ((Km * (Km * C1_3 + C5_8) + C1_6) / ss + 0.5);
309 if (V <= T - E) break;
310 if (V <= T + E)
311 {
312 if (n != n_prev || par != p_prev)
313 {
314 n_prev = n;
315 p_prev = par;
316
317 nm = n - m + 1L;
318 ch = xm * std::log((m + 1.0)/(pq * nm)) +
319 StirlingCorrection(m + 1L) + StirlingCorrection(nm);
320 }
321 nK = n - K + 1L;
322
323 // computation of log f(K) via Stirling's formula
324 // final acceptance-rejection test
325 if (V <= ch + (n + 1.0)*std::log((double) nm / (double) nK) +
326 (K + 0.5)*std::log(nK * pq / (K + 1.0)) -
327 StirlingCorrection(K + 1L) - StirlingCorrection(nK)) break;
328 }
329 }
330 }
331 return ((p>0.5) ? (double)(n-K):(double)K);
332}
333
334std::ostream & RandBinomial::put ( std::ostream & os ) const {
335 long pr=os.precision(20);
336 std::vector<unsigned long> t(2);
337 os << " " << name() << "\n";
338 os << "Uvec" << "\n";
339 t = DoubConv::dto2longs(defaultP);
340 os << defaultN << " " << defaultP << " " << t[0] << " " << t[1] << "\n";
341 os.precision(pr);
342 return os;
343#ifdef REMOVED
344 long pr=os.precision(20);
345 os << " " << name() << "\n";
346 os << defaultN << " " << defaultP << "\n";
347 os.precision(pr);
348 return os;
349#endif
350}
351
352std::istream & RandBinomial::get ( std::istream & is ) {
353 std::string inName;
354 is >> inName;
355 if (inName != name()) {
356 is.clear(std::ios::badbit | is.rdstate());
357 std::cerr << "Mismatch when expecting to read state of a "
358 << name() << " distribution\n"
359 << "Name found was " << inName
360 << "\nistream is left in the badbit state\n";
361 return is;
362 }
363 if (possibleKeywordInput(is, "Uvec", defaultN)) {
364 std::vector<unsigned long> t(2);
365 is >> defaultN >> defaultP;
366 is >> t[0] >> t[1]; defaultP = DoubConv::longs2double(t);
367 return is;
368 }
369 // is >> defaultN encompassed by possibleKeywordInput
370 is >> defaultP;
371 return is;
372}
373
374
375} // namespace CLHEP
#define C5_8
#define C5
#define C1
#define C1_6
#define C3
#define C1_3
#define DMAX_KM
#define C7
static double longs2double(const std::vector< unsigned long > &v)
Definition: DoubConv.cc:110
static std::vector< unsigned long > dto2longs(double d)
Definition: DoubConv.cc:94
static HepRandomEngine * getTheEngine()
Definition: Random.cc:270
std::string name() const
Definition: RandBinomial.cc:30
HepRandomEngine & engine()
Definition: RandBinomial.cc:31
static double shoot()
void fireArray(const int size, double *vect)
Definition: RandBinomial.cc:65
static void shootArray(const int size, double *vect, long n=1, double p=0.5)
Definition: RandBinomial.cc:50
virtual ~RandBinomial()
Definition: RandBinomial.cc:33
std::ostream & put(std::ostream &os) const
std::istream & get(std::istream &is)
#define double(obj)
Definition: excDblThrow.cc:32
void f(void g())
Definition: excDblThrow.cc:38
bool possibleKeywordInput(IS &is, const std::string &key, T &t)
Definition: RandomEngine.h:168