Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TRandom.cxx
Go to the documentation of this file.
1// @(#)root/mathcore:$Id$
2// Author: Rene Brun, Lorenzo Moneta 15/12/95
3
4/*************************************************************************
5 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12/**
13
14\class TRandom
15
16@ingroup Random
17
18This is the base class for the ROOT Random number generators.
19This class defines the ROOT Random number interface and it should not be instantiated directly but used via its derived
20classes. The generator provided in TRandom itself is a LCG (Linear Congruential Generator), the <a
21href="https://www.gnu.org/software/gsl/manual/html_node/Unix-random-number-generators.html">BSD `rand` generator</a>,
22that it should not be used because its period is only 2**31, i.e. approximately 2 billion events, that can be generated
23in just few seconds.
24
25To generate random numbers, one should use one of the derived classes, which are:
26- TRandom3: it is based on the "Mersenne Twister generator",
27it is fast and a very long period of about \f$10^{6000}\f$. However it fails some of the most stringent tests of the
28<a href="http://simul.iro.umontreal.ca/testu01/tu01.html">TestU01 suite</a>.
29In addition this generator provide only numbers with 32 random bits, which might be not sufficient for some application
30based on double or extended precision. This generator is however used in ROOT used to instantiate the global pointer to
31the ROOT generator, *gRandom*.
32- ::TRandomRanluxpp : New implementation of the Ranlux generator algorithm based on a fast modular multiplication of
33576 bits. This new implementation is built on the idea and the original code of Alexei Sibidanov, described in his
34<a href="https://arxiv.org/abs/1705.03123">paper </a>. It generates random numbers with 52 bit precision (double
35precision) and it has an higher luxury level than the original Ranlux generator (`p = 2048` instead of `p=794`).
36- ::TRandomMixMax: Generator based on the family of the MIXMAX matrix generators (see the
37<a href="https://mixmax.hepforge.org">MIXMAX HEPFORGE Web page</a> and the documentation of the class
38ROOT::Math::MixMaxEngine for more information), that are base on the Asanov dynamical C systems. This generator has a
39state of N=240 64 bit integers, proof random properties, it provides 61 random bits and it has a very large period
40(\f$10^{4839}\f$). Furthermore, it provides the capability to be seeded with the guarantee that, for each given
41different seed, a different sequence of random numbers will be generated. The only drawback is that the seeding time is
42time consuming, of the order of 0.1 ms, while the time to generate a number is few ns (more than 10000 faster).
43- ::TRandomMixMax17: Another MixMax generator, but with a smaller state, N=17, and this results in a smaller entropy
44than the generator with N=240. However, it has the same seeding capabilities, with a much faster seeding time (about 200
45times less than TRandomMixMax240 and comparable to TRandom3).
46- ::TRandomMixMax256 : A variant of the MIXMAX generators, based on a state of N=256, and described in the
47 <a href="http://arxiv.org/abs/1403.5355">2015 paper</a>. This implementation has been modified with respect to
48the paper, by skipping 2 internal iterations, to provide improved random properties.
49- ::TRandomMT64 : Generator based on a the Mersenne-Twister generator with 64 bits,
50 using the implementation provided by the standard library ( <a
51href="http://www.cplusplus.com/reference/random/mt19937_64/">std::mt19937_64</a> )
52- TRandom1 based on the RANLUX algorithm, has mathematically proven random proprieties
53 and a period of about \f$10{171}\f$. It is however much slower than the others and it has only 24 random bits. It can
54be constructed with different luxury levels.
55- ::TRandomRanlux48 : Generator based on a the RanLux generator with 48 bits and highest luxury level
56 using the implementation provided by the standard library (<a
57href="http://www.cplusplus.com/reference/random/ranlux48/">std::ranlux48</a>). The drawback of this generator is its
58slow generation time.
59- TRandom2 is based on the Tausworthe generator of L'Ecuyer, and it has the advantage
60of being fast and using only 3 words (of 32 bits) for the state. The period however is not impressively long, it is
6110**26.
62
63Using the template TRandomGen class (template on the contained Engine type), it is possible to add any generator based
64on the standard C++ random library (see the C++ <a href="http://www.cplusplus.com/reference/random/">random</a>
65documentation.) or different variants of the MIXMAX generator using the ROOT::Math::MixMaxEngine. Some of the listed
66generator above (e.g. TRandomMixMax256 or TRandomMT64) are convenient typedef's of generator built using the template
67TRandomGen class.
68
69Please note also that this class (TRandom) implements also a very simple generator (linear congruential) with period =
70\f$10^9\f$, known to have defects (the lower random bits are correlated) and it is failing the majority of the random
71number generator tests. Therefore it should NOT be used in any statistical study.
72
73The following table shows some timings (in nanoseconds/call)
74for the random numbers obtained using a macbookpro 2.6 GHz Intel Core i7 CPU:
75
76
77- TRandom 3 ns/call (but this is a very BAD Generator, not to be used)
78- TRandom2 5 ns/call
79- TRandom3 5 ns/call
80- ::TRandomMixMax 6 ns/call
81- ::TRandomMixMax17 6 ns/call
82- ::TRandomMT64 9 ns/call
83- ::TRandomMixMax256 10 ns/call
84- ::TRandomRanluxpp 14 ns/call
85- ::TRandom1 80 ns/call
86- ::TRandomRanlux48 250 ns/call
87
88The following methods are provided to generate random numbers distributed according to some basic distributions:
89
90- Exp(Double_t tau)
91- Integer(UInt_t imax)
92- Gaus(Double_t mean, Double_t sigma)
93- Rndm()
94- Uniform(Double_t)
95- Landau(Double_t mean, Double_t sigma)
96- Poisson(Double_t mean)
97- Binomial(Int_t ntot, Double_t prob)
98
99Random numbers distributed according to 1-d, 2-d or 3-d distributions contained in TF1, TF2 or TF3 objects can also be
100generated. For example, to get a random number distributed following abs(sin(x)/x)*sqrt(x) you can do : \code{.cpp} TF1
101*f1 = new TF1("f1","abs(sin(x)/x)*sqrt(x)",0,10); double r = f1->GetRandom(); \endcode or you can use the UNURAN
102package. You need in this case to initialize UNURAN to the function you would like to generate. \code{.cpp} TUnuran u;
103 u.Init(TUnuranDistrCont(f1));
104 double r = u.Sample();
105\endcode
106
107The techniques of using directly a TF1,2 or 3 function is powerful and
108can be used to generate numbers in the defined range of the function.
109Getting a number from a TF1,2,3 function is also quite fast.
110UNURAN is a powerful and flexible tool which contains various methods for
111generate random numbers for continuous distributions of one and multi-dimension.
112It requires some set-up (initialization) phase and can be very fast when the distribution
113parameters are not changed for every call.
114
115The following table shows some timings (in nanosecond/call)
116for basic functions, TF1 functions and using UNURAN obtained running
117the tutorial math/testrandom.C
118Numbers have been obtained on an Intel Xeon Quad-core Harpertown (E5410) 2.33 GHz running
119Linux SLC4 64 bit and compiled with gcc 3.4
120
121~~~~
122Distribution nanoseconds/call
123 TRandom TRandom1 TRandom2 TRandom3
124Rndm.............. 5.000 105.000 7.000 10.000
125RndmArray......... 4.000 104.000 6.000 9.000
126Gaus.............. 36.000 180.000 40.000 48.000
127Rannor............ 118.000 220.000 120.000 124.000
128Landau............ 22.000 123.000 26.000 31.000
129Exponential....... 93.000 198.000 98.000 104.000
130Binomial(5,0.5)... 30.000 548.000 46.000 65.000
131Binomial(15,0.5).. 75.000 1615.000 125.000 178.000
132Poisson(3)........ 96.000 494.000 109.000 125.000
133Poisson(10)....... 138.000 1236.000 165.000 203.000
134Poisson(70)....... 818.000 1195.000 835.000 844.000
135Poisson(100)...... 837.000 1218.000 849.000 864.000
136GausTF1........... 83.000 180.000 87.000 88.000
137LandauTF1......... 80.000 180.000 83.000 86.000
138GausUNURAN........ 40.000 139.000 41.000 44.000
139PoissonUNURAN(10). 85.000 271.000 92.000 102.000
140PoissonUNURAN(100) 62.000 256.000 69.000 78.000
141~~~~
142
143Note that the time to generate a number from an arbitrary TF1 function
144using TF1::GetRandom or using TUnuran is independent of the complexity of the function.
145
146TH1::FillRandom(TH1 *) or TH1::FillRandom(const char *tf1name)
147can be used to fill an histogram (1-d, 2-d, 3-d from an existing histogram
148or from an existing function.
149
150Note this interesting feature when working with objects.
151 You can use several TRandom objects, each with their "independent"
152 random sequence. For example, one can imagine
153~~~~
154 TRandom *eventGenerator = new TRandom();
155 TRandom *tracking = new TRandom();
156~~~~
157 `eventGenerator` can be used to generate the event kinematics.
158 tracking can be used to track the generated particles with random numbers
159 independent from eventGenerator.
160 This very interesting feature gives the possibility to work with simple
161 and very fast random number generators without worrying about
162 random number periodicity as it was the case with Fortran.
163 One can use TRandom::SetSeed to modify the seed of one generator.
164
165A TRandom object may be written to a Root file
166
167- as part of another object
168- or with its own key (example: `gRandom->Write("Random")` ) ;
169
170*/
171
172#include "TROOT.h"
173#include "TMath.h"
174#include "TRandom.h"
175#include "TRandom3.h"
176#include "TSystem.h"
177#include "TDirectory.h"
179#include "TUUID.h"
180#include "TError.h"
181
183
184////////////////////////////////////////////////////////////////////////////////
185/// Default constructor. For seed see SetSeed().
186
187TRandom::TRandom(UInt_t seed): TNamed("Random","Default Random number generator")
188{
189 SetSeed(seed);
190}
191
192////////////////////////////////////////////////////////////////////////////////
193/// Default destructor. Can reset gRandom to 0 if gRandom points to this
194/// generator.
195
197{
198 if (gRandom == this) gRandom = nullptr;
199}
200
201////////////////////////////////////////////////////////////////////////////////
202/// Generates a random integer N according to the binomial law.
203/// Coded from Los Alamos report LA-5061-MS.
204///
205/// N is binomially distributed between 0 and ntot inclusive
206/// with mean prob*ntot and prob is between 0 and 1.
207///
208/// Note: This function should not be used when ntot is large (say >100).
209/// The normal approximation is then recommended instead
210/// (with mean =*ntot+0.5 and standard deviation sqrt(ntot*prob*(1-prob)).
211
213{
214 if (prob < 0 || prob > 1) return 0;
215 Int_t n = 0;
216 for (Int_t i=0;i<ntot;i++) {
217 if (Rndm() > prob) continue;
218 n++;
219 }
220 return n;
221}
222
223////////////////////////////////////////////////////////////////////////////////
224/// Return a number distributed following a BreitWigner function with mean and gamma.
225
227{
228 Double_t rval, displ;
229 rval = 2*Rndm() - 1;
230 displ = 0.5*gamma*TMath::Tan(rval*TMath::PiOver2());
231
232 return (mean+displ);
233}
234
235////////////////////////////////////////////////////////////////////////////////
236/// Generates random vectors, uniformly distributed over a circle of given radius.
237/// Input : r = circle radius
238/// Output: x,y a random 2-d vector of length r
239
241{
242 Double_t phi = Uniform(0,TMath::TwoPi());
243 x = r*TMath::Cos(phi);
244 y = r*TMath::Sin(phi);
245}
246
247////////////////////////////////////////////////////////////////////////////////
248/// Returns an exponential deviate.
249///
250/// exp( -t/tau )
251
253{
254 Double_t x = Rndm(); // uniform on ] 0, 1 ]
255 Double_t t = -tau * TMath::Log( x ); // convert to exponential distribution
256 return t;
257}
258
259////////////////////////////////////////////////////////////////////////////////
260/// Samples a random number from the standard Normal (Gaussian) Distribution
261/// with the given mean and sigma.
262/// Uses the Acceptance-complement ratio from W. Hoermann and G. Derflinger
263/// This is one of the fastest existing method for generating normal random variables.
264/// It is a factor 2/3 faster than the polar (Box-Muller) method used in the previous
265/// version of TRandom::Gaus. The speed is comparable to the Ziggurat method (from Marsaglia)
266/// implemented for example in GSL and available in the MathMore library.
267///
268/// REFERENCE: - W. Hoermann and G. Derflinger (1990):
269/// The ACR Method for generating normal random variables,
270/// OR Spektrum 12 (1990), 181-185.
271///
272/// Implementation taken from
273/// UNURAN (c) 2000 W. Hoermann & J. Leydold, Institut f. Statistik, WU Wien
274
276{
277 const Double_t kC1 = 1.448242853;
278 const Double_t kC2 = 3.307147487;
279 const Double_t kC3 = 1.46754004;
280 const Double_t kD1 = 1.036467755;
281 const Double_t kD2 = 5.295844968;
282 const Double_t kD3 = 3.631288474;
283 const Double_t kHm = 0.483941449;
284 const Double_t kZm = 0.107981933;
285 const Double_t kHp = 4.132731354;
286 const Double_t kZp = 18.52161694;
287 const Double_t kPhln = 0.4515827053;
288 const Double_t kHm1 = 0.516058551;
289 const Double_t kHp1 = 3.132731354;
290 const Double_t kHzm = 0.375959516;
291 const Double_t kHzmp = 0.591923442;
292 /*zhm 0.967882898*/
293
294 const Double_t kAs = 0.8853395638;
295 const Double_t kBs = 0.2452635696;
296 const Double_t kCs = 0.2770276848;
297 const Double_t kB = 0.5029324303;
298 const Double_t kX0 = 0.4571828819;
299 const Double_t kYm = 0.187308492 ;
300 const Double_t kS = 0.7270572718 ;
301 const Double_t kT = 0.03895759111;
302
304 Double_t rn,x,y,z;
305
306 do {
307 y = Rndm();
308
309 if (y>kHm1) {
310 result = kHp*y-kHp1; break; }
311
312 else if (y<kZm) {
313 rn = kZp*y-1;
314 result = (rn>0) ? (1+rn) : (-1+rn);
315 break;
316 }
317
318 else if (y<kHm) {
319 rn = Rndm();
320 rn = rn-1+rn;
321 z = (rn>0) ? 2-rn : -2-rn;
322 if ((kC1-y)*(kC3+TMath::Abs(z))<kC2) {
323 result = z; break; }
324 else {
325 x = rn*rn;
326 if ((y+kD1)*(kD3+x)<kD2) {
327 result = rn; break; }
328 else if (kHzmp-y<exp(-(z*z+kPhln)/2)) {
329 result = z; break; }
330 else if (y+kHzm<exp(-(x+kPhln)/2)) {
331 result = rn; break; }
332 }
333 }
334
335 while (true) {
336 x = Rndm();
337 y = kYm * Rndm();
338 z = kX0 - kS*x - y;
339 if (z>0)
340 rn = 2+y/x;
341 else {
342 x = 1-x;
343 y = kYm-y;
344 rn = -(2+y/x);
345 }
346 if ((y-kAs+x)*(kCs+x)+kBs<0) {
347 result = rn; break; }
348 else if (y<x+kT)
349 if (rn*rn<4*(kB-log(x))) {
350 result = rn; break; }
351 }
352 } while(false);
353
354 return mean + sigma * result;
355}
356
357////////////////////////////////////////////////////////////////////////////////
358/// Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
359/// Note that the interval contains the values of 0 and imax-1 but not imax.
360
362{
363 UInt_t ui;
364 ui = (UInt_t)(imax*Rndm());
365 return ui;
366}
367
368////////////////////////////////////////////////////////////////////////////////
369/// Generate a random number following a Landau distribution
370/// with location parameter mu and scale parameter sigma:
371/// Landau( (x-mu)/sigma )
372/// Note that mu is not the mpv(most probable value) of the Landa distribution
373/// and sigma is not the standard deviation of the distribution which is not defined.
374/// For mu =0 and sigma=1, the mpv = -0.22278
375///
376/// The Landau random number generation is implemented using the
377/// function landau_quantile(x,sigma), which provides
378/// the inverse of the landau cumulative distribution.
379/// landau_quantile has been converted from CERNLIB ranlan(G110).
380
382{
383 if (sigma <= 0) return 0;
384 Double_t x = Rndm();
386 return res;
387}
388
389////////////////////////////////////////////////////////////////////////////////
390/// Generates a random integer N according to a Poisson law.
391/// Prob(N) = exp(-mean)*mean^N/Factorial(N)
392///
393/// Use a different procedure according to the mean value.
394/// The algorithm is the same used by CLHEP.
395/// For lower value (mean < 25) use the rejection method based on
396/// the exponential.
397/// For higher values use a rejection method comparing with a Lorentzian
398/// distribution, as suggested by several authors.
399/// This routine returns now an unsigned 64 bit integer
400/// For large values, larger than 1.84e+19, we print an error message
401/// advising to use the Trandom::PoissonD for such large values,
402/// and return the max value UINT64_MAX
403
405{
406 ULong64_t n;
407 if (mean <= 0) return 0;
408 if (mean < 25) {
409 Double_t expmean = TMath::Exp(-mean);
410 Double_t pir = 1;
411 n = -1;
412 while(true) {
413 n++;
414 pir *= Rndm();
415 if (pir <= expmean) break;
416 }
417 return n;
418 }
419 // for large value we use inversion method
420 else if (mean < 1E9) {
421 Double_t em, t, y;
422 Double_t sq, alxm, g;
423 Double_t pi = TMath::Pi();
424
425 sq = TMath::Sqrt(2.0*mean);
426 alxm = TMath::Log(mean);
427 g = mean*alxm - TMath::LnGamma(mean + 1.0);
428
429 do {
430 do {
431 y = TMath::Tan(pi*Rndm());
432 em = sq*y + mean;
433 } while( em < 0.0 );
434
435 em = TMath::Floor(em);
436 t = 0.9*(1.0 + y*y)* TMath::Exp(em*alxm - TMath::LnGamma(em + 1.0) - g);
437 } while( Rndm() > t );
438
439 return static_cast<ULong64_t>(em);
440
441 }
442 else {
443 // use Gaussian approximation for very large values
444 Double_t x = Gaus(0, 1) * TMath::Sqrt(mean) + mean + 0.5;
446 Error("Poisson", "Overflow in return value. Use PoissonD instead.");
448 }
449 n = static_cast<ULong64_t>(x);
450 return n;
451 }
452}
453
454////////////////////////////////////////////////////////////////////////////////
455/// Generates a random number according to a Poisson law.
456/// Prob(N) = exp(-mean)*mean^N/Factorial(N)
457///
458/// This function is a variant of TRandom::Poisson returning a double
459/// instead of an integer.
460
462{
463 Int_t n;
464 if (mean <= 0) return 0;
465 if (mean < 25) {
466 Double_t expmean = TMath::Exp(-mean);
467 Double_t pir = 1;
468 n = -1;
469 while(true) {
470 n++;
471 pir *= Rndm();
472 if (pir <= expmean) break;
473 }
474 return static_cast<Double_t>(n);
475 }
476 // for large value we use inversion method
477 else if (mean < 1E9) {
478 Double_t em, t, y;
479 Double_t sq, alxm, g;
480 Double_t pi = TMath::Pi();
481
482 sq = TMath::Sqrt(2.0*mean);
483 alxm = TMath::Log(mean);
484 g = mean*alxm - TMath::LnGamma(mean + 1.0);
485
486 do {
487 do {
488 y = TMath::Tan(pi*Rndm());
489 em = sq*y + mean;
490 } while( em < 0.0 );
491
492 em = TMath::Floor(em);
493 t = 0.9*(1.0 + y*y)* TMath::Exp(em*alxm - TMath::LnGamma(em + 1.0) - g);
494 } while( Rndm() > t );
495
496 return em;
497
498 } else {
499 // use Gaussian approximation for very large values
500 return Gaus(0,1)*TMath::Sqrt(mean) + mean +0.5;
501 }
502}
503
504////////////////////////////////////////////////////////////////////////////////
505/// Return 2 numbers distributed following a gaussian with mean=0 and sigma=1.
506
508{
509 Double_t r, x, y, z;
510
511 y = Rndm();
512 z = Rndm();
513 x = z * 6.28318530717958623;
514 r = TMath::Sqrt(-2*TMath::Log(y));
515 a = (Float_t)(r * TMath::Sin(x));
516 b = (Float_t)(r * TMath::Cos(x));
517}
518
519////////////////////////////////////////////////////////////////////////////////
520/// Return 2 numbers distributed following a gaussian with mean=0 and sigma=1.
521
523{
524 Double_t r, x, y, z;
525
526 y = Rndm();
527 z = Rndm();
528 x = z * 6.28318530717958623;
529 r = TMath::Sqrt(-2*TMath::Log(y));
530 a = r * TMath::Sin(x);
531 b = r * TMath::Cos(x);
532}
533
534////////////////////////////////////////////////////////////////////////////////
535/// Reads saved random generator status from filename.
536
538{
539 if (!gDirectory) return;
540 char *fntmp = gSystem->ExpandPathName(filename);
541 TDirectory *file = (TDirectory*)gROOT->ProcessLine(Form("TFile::Open(\"%s\");",fntmp));
542 delete [] fntmp;
543 if(file && file->GetFile()) {
545 delete file;
546 }
547}
548
549////////////////////////////////////////////////////////////////////////////////
550/// Machine independent random number generator.
551/// Based on the BSD Unix (Rand) Linear congruential generator.
552/// Produces uniformly-distributed floating points between 0 and 1.
553/// Identical sequence on all machines of >= 32 bits.
554/// Periodicity = 2**31, generates a number in (0,1).
555/// Note that this is a generator which is known to have defects
556/// (the lower random bits are correlated) and therefore should NOT be
557/// used in any statistical study).
558
560{
561#ifdef OLD_TRANDOM_IMPL
562 const Double_t kCONS = 4.6566128730774E-10;
563 const Int_t kMASK24 = 2147483392;
564
565 fSeed *= 69069;
566 UInt_t jy = (fSeed&kMASK24); // Set lower 8 bits to zero to assure exact float
567 if (jy) return kCONS*jy;
568 return Rndm();
569#endif
570
571 // kCONS = 1./2147483648 = 1./(RAND_MAX+1) and RAND_MAX= 0x7fffffffUL
572 const Double_t kCONS = 4.6566128730774E-10; // (1/pow(2,31)
573 fSeed = (1103515245 * fSeed + 12345) & 0x7fffffffUL;
574
575 if (fSeed) return kCONS*fSeed;
576 return Rndm();
577}
578
579////////////////////////////////////////////////////////////////////////////////
580/// Return an array of n random numbers uniformly distributed in ]0,1].
581
583{
584 const Double_t kCONS = 4.6566128730774E-10; // (1/pow(2,31))
585 Int_t i=0;
586 while (i<n) {
587 fSeed = (1103515245 * fSeed + 12345) & 0x7fffffffUL;
588 if (fSeed) {array[i] = kCONS*fSeed; i++;}
589 }
590}
591
592////////////////////////////////////////////////////////////////////////////////
593/// Return an array of n random numbers uniformly distributed in ]0,1].
594
596{
597 const Double_t kCONS = 4.6566128730774E-10; // (1/pow(2,31))
598 Int_t i=0;
599 while (i<n) {
600 fSeed = (1103515245 * fSeed + 12345) & 0x7fffffffUL;
601 if (fSeed) {array[i] = Float_t(kCONS*fSeed); i++;}
602 }
603}
604
605////////////////////////////////////////////////////////////////////////////////
606/// Set the random generator seed. Note that default value is zero, which is
607/// different than the default value used when constructing the class.
608/// If the seed is zero the seed is set to a random value
609/// which in case of TRandom depends on the lowest 4 bytes of TUUID
610/// The UUID will be identical if SetSeed(0) is called with time smaller than 100 ns
611/// Instead if a different generator implementation is used (TRandom1, 2 or 3)
612/// the seed is generated using a 128 bit UUID. This results in different seeds
613/// and then random sequence for every SetSeed(0) call.
614
616{
617 if( seed==0 ) {
618 TUUID u;
619 UChar_t uuid[16];
620 u.GetUUID(uuid);
621 fSeed = UInt_t(uuid[3])*16777216 + UInt_t(uuid[2])*65536 + UInt_t(uuid[1])*256 + UInt_t(uuid[0]);
622 } else {
623 fSeed = seed;
624 }
625}
626
627////////////////////////////////////////////////////////////////////////////////
628/// \brief Get the random generator seed.
629///
630/// \warning Might not be the initial seed!
631///
632/// Note that this function returns the given seed only when using
633/// as random generator engine TRandom itself, which is an LCG generator
634/// and it has as seed (state) only one 32 bit word.
635/// In case of the other generators GetSeed will return one of the state elements and not the
636/// given seed. See the documentation of the corresponding generator used
637/// (for example TRandom3::GetSeed() when using TRandom3 or gRandom.
638/// If one needs to save the generator seed in order to be used later for obtaining reproducible
639/// numbers, one should store the full generator, either in a file or in memory in a separate TRandom
640/// object. Here is an example on how to store reproducible states:
641/// ```
642/// // set a unique seed
643/// gRandom->SetSeed(0);
644/// // save generator state in a different TRandom instance
645/// TRandom* rngSaved = static_cast<TRandom*>(gRandom->Clone());
646/// // now both rngSaved and gRandom will produce the same sequence of numbers
647/// for (int i = 0; i < 10; ++i )
648/// std::cout << "generated number from gRandom : " << gRandom->Rndm() << " from saved generator " <<
649/// rngSaved->Rndm() << std::endl;
650/// ```
652{
653 return fSeed;
654}
655
656////////////////////////////////////////////////////////////////////////////////
657/// Generates random vectors, uniformly distributed over the surface
658/// of a sphere of given radius.
659/// Input : r = sphere radius
660/// Output: x,y,z a random 3-d vector of length r
661/// Method: (based on algorithm suggested by Knuth and attributed to Robert E Knop)
662/// which uses less random numbers than the CERNLIB RN23DIM algorithm
663
665{
666 Double_t a=0,b=0,r2=1;
667 while (r2 > 0.25) {
668 a = Rndm() - 0.5;
669 b = Rndm() - 0.5;
670 r2 = a*a + b*b;
671 }
672 z = r* ( -1. + 8.0 * r2 );
673
674 Double_t scale = 8.0 * r * TMath::Sqrt(0.25 - r2);
675 x = a*scale;
676 y = b*scale;
677}
678
679////////////////////////////////////////////////////////////////////////////////
680/// Returns a uniform deviate on the interval (0, x1).
681
683{
684 Double_t ans = Rndm();
685 return x1*ans;
686}
687
688////////////////////////////////////////////////////////////////////////////////
689/// Returns a uniform deviate on the interval (x1, x2).
690
692{
693 Double_t ans= Rndm();
694 return x1 + (x2-x1)*ans;
695}
696
697////////////////////////////////////////////////////////////////////////////////
698/// Writes random generator status to filename.
699
700void TRandom::WriteRandom(const char *filename) const
701{
702 if (!gDirectory) return;
703 char *fntmp = gSystem->ExpandPathName(filename);
704 TDirectory *file = (TDirectory*)gROOT->ProcessLine(Form("TFile::Open(\"%s\",\"recreate\");",fntmp));
705 delete [] fntmp;
706 if(file && file->GetFile()) {
708 delete file;
709 }
710}
#define b(i)
Definition RSha256.hxx:100
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
unsigned char UChar_t
Definition RtypesCore.h:38
unsigned long ULong_t
Definition RtypesCore.h:55
unsigned int UInt_t
Definition RtypesCore.h:46
float Float_t
Definition RtypesCore.h:57
unsigned long long ULong64_t
Definition RtypesCore.h:81
#define ClassImp(name)
Definition Rtypes.h:377
#define gDirectory
Definition TDirectory.h:384
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char x2
Option_t Option_t TPoint TPoint const char x1
#define gROOT
Definition TROOT.h:406
R__EXTERN TRandom * gRandom
Definition TRandom.h:62
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
R__EXTERN TSystem * gSystem
Definition TSystem.h:555
Describe directory structure in memory.
Definition TDirectory.h:45
virtual Int_t WriteTObject(const TObject *obj, const char *name=nullptr, Option_t *="", Int_t=0)
Write an object with proper type checking.
virtual TFile * GetFile() const
Definition TDirectory.h:220
virtual Int_t ReadTObject(TObject *, const char *)
Definition TDirectory.h:249
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:987
This is the base class for the ROOT Random number generators.
Definition TRandom.h:27
virtual Double_t Gaus(Double_t mean=0, Double_t sigma=1)
Samples a random number from the standard Normal (Gaussian) Distribution with the given mean and sigm...
Definition TRandom.cxx:275
virtual void RndmArray(Int_t n, Float_t *array)
Return an array of n random numbers uniformly distributed in ]0,1].
Definition TRandom.cxx:595
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
Definition TRandom.cxx:615
virtual void WriteRandom(const char *filename) const
Writes random generator status to filename.
Definition TRandom.cxx:700
Double_t Rndm() override
Machine independent random number generator.
Definition TRandom.cxx:559
UInt_t fSeed
Definition TRandom.h:30
virtual void Rannor(Float_t &a, Float_t &b)
Return 2 numbers distributed following a gaussian with mean=0 and sigma=1.
Definition TRandom.cxx:507
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition TRandom.cxx:461
virtual void ReadRandom(const char *filename)
Reads saved random generator status from filename.
Definition TRandom.cxx:537
virtual UInt_t GetSeed() const
Get the random generator seed.
Definition TRandom.cxx:651
virtual ULong64_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition TRandom.cxx:404
virtual Double_t Exp(Double_t tau)
Returns an exponential deviate.
Definition TRandom.cxx:252
virtual void Circle(Double_t &x, Double_t &y, Double_t r)
Generates random vectors, uniformly distributed over a circle of given radius.
Definition TRandom.cxx:240
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
Definition TRandom.cxx:682
virtual void Sphere(Double_t &x, Double_t &y, Double_t &z, Double_t r)
Generates random vectors, uniformly distributed over the surface of a sphere of given radius.
Definition TRandom.cxx:664
virtual Double_t Landau(Double_t mean=0, Double_t sigma=1)
Generate a random number following a Landau distribution with location parameter mu and scale paramet...
Definition TRandom.cxx:381
TRandom(UInt_t seed=65539)
Default constructor. For seed see SetSeed().
Definition TRandom.cxx:187
virtual Int_t Binomial(Int_t ntot, Double_t prob)
Generates a random integer N according to the binomial law.
Definition TRandom.cxx:212
virtual Double_t BreitWigner(Double_t mean=0, Double_t gamma=1)
Return a number distributed following a BreitWigner function with mean and gamma.
Definition TRandom.cxx:226
~TRandom() override
Default destructor.
Definition TRandom.cxx:196
virtual UInt_t Integer(UInt_t imax)
Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
Definition TRandom.cxx:361
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1274
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
void GetUUID(UChar_t uuid[16]) const
Return uuid in specified buffer (16 byte = 128 bits).
Definition TUUID.cxx:695
double landau_quantile(double z, double xi=1)
Inverse ( ) of the cumulative distribution function of the lower tail of the Landau distribution (lan...
const Double_t sigma
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
Double_t Exp(Double_t x)
Returns the base-e exponential function of x, which is e raised to the power x.
Definition TMath.h:709
Double_t Floor(Double_t x)
Rounds x downward, returning the largest integral value that is not greater than x.
Definition TMath.h:680
constexpr Double_t PiOver2()
Definition TMath.h:51
Double_t Log(Double_t x)
Returns the natural logarithm of x.
Definition TMath.h:756
Double_t Sqrt(Double_t x)
Returns the square root of x.
Definition TMath.h:662
Double_t Cos(Double_t)
Returns the cosine of an angle of x radians.
Definition TMath.h:594
constexpr Double_t Pi()
Definition TMath.h:37
Double_t LnGamma(Double_t z)
Computation of ln[gamma(z)] for all z.
Definition TMath.cxx:509
Double_t Sin(Double_t)
Returns the sine of an angle of x radians.
Definition TMath.h:588
Double_t Tan(Double_t)
Returns the tangent of an angle of x radians.
Definition TMath.h:600
Short_t Abs(Short_t d)
Returns the absolute value of parameter Short_t d.
Definition TMathBase.h:123
constexpr Double_t TwoPi()
Definition TMath.h:44
static T Max()
Returns minimum double representation.
Definition TMath.h:933