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
182
183////////////////////////////////////////////////////////////////////////////////
184/// Default constructor. For seed see SetSeed().
185
186TRandom::TRandom(UInt_t seed): TNamed("Random","Default Random number generator")
187{
188 SetSeed(seed);
189}
190
191////////////////////////////////////////////////////////////////////////////////
192/// Default destructor. Can reset gRandom to 0 if gRandom points to this
193/// generator.
194
196{
197 if (gRandom == this) gRandom = nullptr;
198}
199
200////////////////////////////////////////////////////////////////////////////////
201/// Generates a random integer N according to the binomial law.
202/// Coded from Los Alamos report LA-5061-MS.
203///
204/// N is binomially distributed between 0 and ntot inclusive
205/// with mean prob*ntot and prob is between 0 and 1.
206///
207/// Note: This function should not be used when ntot is large (say >100).
208/// The normal approximation is then recommended instead
209/// (with mean =*ntot+0.5 and standard deviation sqrt(ntot*prob*(1-prob)).
210
212{
213 if (prob < 0 || prob > 1) return 0;
214 Int_t n = 0;
215 for (Int_t i=0;i<ntot;i++) {
216 if (Rndm() > prob) continue;
217 n++;
218 }
219 return n;
220}
221
222////////////////////////////////////////////////////////////////////////////////
223/// Return a number distributed following a BreitWigner function with mean and gamma.
224
226{
228 rval = 2*Rndm() - 1;
229 displ = 0.5*gamma*TMath::Tan(rval*TMath::PiOver2());
230
231 return (mean+displ);
232}
233
234////////////////////////////////////////////////////////////////////////////////
235/// Generates random vectors, uniformly distributed over a circle of given radius.
236/// Input : r = circle radius
237/// Output: x,y a random 2-d vector of length r
238
240{
241 Double_t phi = Uniform(0,TMath::TwoPi());
242 x = r*TMath::Cos(phi);
243 y = r*TMath::Sin(phi);
244}
245
246////////////////////////////////////////////////////////////////////////////////
247/// Returns an exponential deviate.
248///
249/// exp( -t/tau )
250
252{
253 Double_t x = Rndm(); // uniform on ]0, 1[
254 Double_t t = -tau * TMath::Log( x ); // convert to exponential distribution
255 return t;
256}
257
258////////////////////////////////////////////////////////////////////////////////
259/// Samples a random number from the standard Normal (Gaussian) Distribution
260/// with the given mean and sigma.
261/// Uses the Acceptance-complement ratio from W. Hoermann and G. Derflinger
262/// This is one of the fastest existing method for generating normal random variables.
263/// It is a factor 2/3 faster than the polar (Box-Muller) method used in the previous
264/// version of TRandom::Gaus. The speed is comparable to the Ziggurat method (from Marsaglia)
265/// implemented for example in GSL and available in the MathMore library.
266///
267/// REFERENCE: - W. Hoermann and G. Derflinger (1990):
268/// The ACR Method for generating normal random variables,
269/// OR Spektrum 12 (1990), 181-185.
270///
271/// Implementation taken from
272/// UNURAN (c) 2000 W. Hoermann & J. Leydold, Institut f. Statistik, WU Wien
273
275{
276 const Double_t kC1 = 1.448242853;
277 const Double_t kC2 = 3.307147487;
278 const Double_t kC3 = 1.46754004;
279 const Double_t kD1 = 1.036467755;
280 const Double_t kD2 = 5.295844968;
281 const Double_t kD3 = 3.631288474;
282 const Double_t kHm = 0.483941449;
283 const Double_t kZm = 0.107981933;
284 const Double_t kHp = 4.132731354;
285 const Double_t kZp = 18.52161694;
286 const Double_t kPhln = 0.4515827053;
287 const Double_t kHm1 = 0.516058551;
288 const Double_t kHp1 = 3.132731354;
289 const Double_t kHzm = 0.375959516;
290 const Double_t kHzmp = 0.591923442;
291 /*zhm 0.967882898*/
292
293 const Double_t kAs = 0.8853395638;
294 const Double_t kBs = 0.2452635696;
295 const Double_t kCs = 0.2770276848;
296 const Double_t kB = 0.5029324303;
297 const Double_t kX0 = 0.4571828819;
298 const Double_t kYm = 0.187308492 ;
299 const Double_t kS = 0.7270572718 ;
300 const Double_t kT = 0.03895759111;
301
303 Double_t rn,x,y,z;
304
305 do {
306 y = Rndm();
307
308 if (y>kHm1) {
309 result = kHp*y-kHp1; break; }
310
311 else if (y<kZm) {
312 rn = kZp*y-1;
313 result = (rn>0) ? (1+rn) : (-1+rn);
314 break;
315 }
316
317 else if (y<kHm) {
318 rn = Rndm();
319 rn = rn-1+rn;
320 z = (rn>0) ? 2-rn : -2-rn;
321 if ((kC1-y)*(kC3+TMath::Abs(z))<kC2) {
322 result = z; break; }
323 else {
324 x = rn*rn;
325 if ((y+kD1)*(kD3+x)<kD2) {
326 result = rn; break; }
327 else if (kHzmp-y<exp(-(z*z+kPhln)/2)) {
328 result = z; break; }
329 else if (y+kHzm<exp(-(x+kPhln)/2)) {
330 result = rn; break; }
331 }
332 }
333
334 while (true) {
335 x = Rndm();
336 y = kYm * Rndm();
337 z = kX0 - kS*x - y;
338 if (z>0)
339 rn = 2+y/x;
340 else {
341 x = 1-x;
342 y = kYm-y;
343 rn = -(2+y/x);
344 }
345 if ((y-kAs+x)*(kCs+x)+kBs<0) {
346 result = rn; break; }
347 else if (y<x+kT)
348 if (rn*rn<4*(kB-log(x))) {
349 result = rn; break; }
350 }
351 } while(false);
352
353 return mean + sigma * result;
354}
355
356////////////////////////////////////////////////////////////////////////////////
357/// Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
358/// Note that the interval contains the values of 0 and imax-1 but not imax.
359
361{
362 UInt_t ui;
363 ui = (UInt_t)(imax*Rndm());
364 return ui;
365}
366
367////////////////////////////////////////////////////////////////////////////////
368/// Generate a random number following a Landau distribution
369/// with location parameter mu and scale parameter sigma:
370/// Landau( (x-mu)/sigma )
371/// Note that mu is not the mpv(most probable value) of the Landa distribution
372/// and sigma is not the standard deviation of the distribution which is not defined.
373/// For mu =0 and sigma=1, the mpv = -0.22278
374///
375/// The Landau random number generation is implemented using the
376/// function landau_quantile(x,sigma), which provides
377/// the inverse of the landau cumulative distribution.
378/// landau_quantile has been converted from CERNLIB ranlan(G110).
379
381{
382 if (sigma <= 0) return 0;
383 Double_t x = Rndm();
385 return res;
386}
387
388////////////////////////////////////////////////////////////////////////////////
389/// Generates a random integer N according to a Poisson law.
390/// Prob(N) = exp(-mean)*mean^N/Factorial(N)
391///
392/// Use a different procedure according to the mean value.
393/// The algorithm is the same used by CLHEP.
394/// For lower value (mean < 25) use the rejection method based on
395/// the exponential.
396/// For higher values use a rejection method comparing with a Lorentzian
397/// distribution, as suggested by several authors.
398/// This routine returns now an unsigned 64 bit integer
399/// For large values, larger than 1.84e+19, we print an error message
400/// advising to use the Trandom::PoissonD for such large values,
401/// and return the max value UINT64_MAX
402
404{
405 ULong64_t n;
406 if (mean <= 0) return 0;
407 if (mean < 25) {
408 Double_t expmean = TMath::Exp(-mean);
409 Double_t pir = 1;
410 n = -1;
411 while(true) {
412 n++;
413 pir *= Rndm();
414 if (pir <= expmean) break;
415 }
416 return n;
417 }
418 // for large value we use inversion method
419 else if (mean < 1E9) {
420 Double_t em, t, y;
421 Double_t sq, alxm, g;
422 Double_t pi = TMath::Pi();
423
424 sq = TMath::Sqrt(2.0*mean);
425 alxm = TMath::Log(mean);
426 g = mean*alxm - TMath::LnGamma(mean + 1.0);
427
428 do {
429 do {
430 y = TMath::Tan(pi*Rndm());
431 em = sq*y + mean;
432 } while( em < 0.0 );
433
434 em = TMath::Floor(em);
435 t = 0.9*(1.0 + y*y)* TMath::Exp(em*alxm - TMath::LnGamma(em + 1.0) - g);
436 } while( Rndm() > t );
437
438 return static_cast<ULong64_t>(em);
439
440 }
441 else {
442 // use Gaussian approximation for very large values
443 Double_t x = Gaus(0, 1) * TMath::Sqrt(mean) + mean + 0.5;
445 Error("Poisson", "Overflow in return value. Use PoissonD instead.");
447 }
448 n = static_cast<ULong64_t>(x);
449 return n;
450 }
451}
452
453////////////////////////////////////////////////////////////////////////////////
454/// Generates a random number according to a Poisson law.
455/// Prob(N) = exp(-mean)*mean^N/Factorial(N)
456///
457/// This function is a variant of TRandom::Poisson returning a double
458/// instead of an integer.
459
461{
462 Int_t n;
463 if (mean <= 0) return 0;
464 if (mean < 25) {
465 Double_t expmean = TMath::Exp(-mean);
466 Double_t pir = 1;
467 n = -1;
468 while(true) {
469 n++;
470 pir *= Rndm();
471 if (pir <= expmean) break;
472 }
473 return static_cast<Double_t>(n);
474 }
475 // for large value we use inversion method
476 else if (mean < 1E9) {
477 Double_t em, t, y;
478 Double_t sq, alxm, g;
479 Double_t pi = TMath::Pi();
480
481 sq = TMath::Sqrt(2.0*mean);
482 alxm = TMath::Log(mean);
483 g = mean*alxm - TMath::LnGamma(mean + 1.0);
484
485 do {
486 do {
487 y = TMath::Tan(pi*Rndm());
488 em = sq*y + mean;
489 } while( em < 0.0 );
490
491 em = TMath::Floor(em);
492 t = 0.9*(1.0 + y*y)* TMath::Exp(em*alxm - TMath::LnGamma(em + 1.0) - g);
493 } while( Rndm() > t );
494
495 return em;
496
497 } else {
498 // use Gaussian approximation for very large values
499 return Gaus(0,1)*TMath::Sqrt(mean) + mean +0.5;
500 }
501}
502
503////////////////////////////////////////////////////////////////////////////////
504/// Return 2 numbers distributed following a gaussian with mean=0 and sigma=1.
505
507{
508 Double_t r, x, y, z;
509
510 y = Rndm();
511 z = Rndm();
512 x = z * 6.28318530717958623;
513 r = TMath::Sqrt(-2*TMath::Log(y));
514 a = (Float_t)(r * TMath::Sin(x));
515 b = (Float_t)(r * TMath::Cos(x));
516}
517
518////////////////////////////////////////////////////////////////////////////////
519/// Return 2 numbers distributed following a gaussian with mean=0 and sigma=1.
520
522{
523 Double_t r, x, y, z;
524
525 y = Rndm();
526 z = Rndm();
527 x = z * 6.28318530717958623;
528 r = TMath::Sqrt(-2*TMath::Log(y));
529 a = r * TMath::Sin(x);
530 b = r * TMath::Cos(x);
531}
532
533////////////////////////////////////////////////////////////////////////////////
534/// Reads saved random generator status from filename.
535
537{
538 if (!gDirectory) return;
540 TDirectory *file = (TDirectory*)gROOT->ProcessLine(Form("TFile::Open(\"%s\");",fntmp));
541 delete [] fntmp;
542 if(file && file->GetFile()) {
544 delete file;
545 }
546}
547
548////////////////////////////////////////////////////////////////////////////////
549/// Machine independent random number generator.
550/// Based on the BSD Unix (Rand) Linear congruential generator.
551/// Produces uniformly-distributed floating points between 0 and 1.
552/// Identical sequence on all machines of >= 32 bits.
553/// Periodicity = 2**31, generates a number in (0,1).
554/// Note that this is a generator which is known to have defects
555/// (the lower random bits are correlated) and therefore should NOT be
556/// used in any statistical study).
557
559{
560#ifdef OLD_TRANDOM_IMPL
561 const Double_t kCONS = 4.6566128730774E-10;
562 const Int_t kMASK24 = 2147483392;
563
564 fSeed *= 69069;
565 UInt_t jy = (fSeed&kMASK24); // Set lower 8 bits to zero to assure exact float
566 if (jy) return kCONS*jy;
567 return Rndm();
568#endif
569
570 // kCONS = 1./2147483648 = 1./(RAND_MAX+1) and RAND_MAX= 0x7fffffffUL
571 const Double_t kCONS = 4.6566128730774E-10; // (1/pow(2,31)
572 fSeed = (1103515245 * fSeed + 12345) & 0x7fffffffUL;
573
574 if (fSeed) return kCONS*fSeed;
575 return Rndm();
576}
577
578////////////////////////////////////////////////////////////////////////////////
579/// Return an array of n random numbers uniformly distributed in ]0,1[.
580
582{
583 const Double_t kCONS = 4.6566128730774E-10; // (1/pow(2,31))
584 Int_t i=0;
585 while (i<n) {
586 fSeed = (1103515245 * fSeed + 12345) & 0x7fffffffUL;
587 if (fSeed) {array[i] = kCONS*fSeed; i++;}
588 }
589}
590
591////////////////////////////////////////////////////////////////////////////////
592/// Return an array of n random numbers uniformly distributed in ]0,1[.
593
595{
596 const Double_t kCONS = 4.6566128730774E-10; // (1/pow(2,31))
597 Int_t i=0;
598 while (i<n) {
599 fSeed = (1103515245 * fSeed + 12345) & 0x7fffffffUL;
600 if (fSeed) {array[i] = Float_t(kCONS*fSeed); i++;}
601 }
602}
603
604////////////////////////////////////////////////////////////////////////////////
605/// Set the random generator seed. Note that default value is zero, which is
606/// different than the default value used when constructing the class.
607/// If the seed is zero the seed is set to a random value
608/// which in case of TRandom depends on the lowest 4 bytes of TUUID
609/// The UUID will be identical if SetSeed(0) is called with time smaller than 100 ns
610/// Instead if a different generator implementation is used (TRandom1, 2 or 3)
611/// the seed is generated using a 128 bit UUID. This results in different seeds
612/// and then random sequence for every SetSeed(0) call.
613
615{
616 if( seed==0 ) {
617 TUUID u;
618 UChar_t uuid[16];
619 u.GetUUID(uuid);
620 fSeed = UInt_t(uuid[3])*16777216 + UInt_t(uuid[2])*65536 + UInt_t(uuid[1])*256 + UInt_t(uuid[0]);
621 } else {
622 fSeed = seed;
623 }
624}
625
626////////////////////////////////////////////////////////////////////////////////
627/// \brief Get the random generator seed.
628///
629/// \warning Might not be the initial seed!
630///
631/// Note that this function returns the given seed only when using
632/// as random generator engine TRandom itself, which is an LCG generator
633/// and it has as seed (state) only one 32 bit word.
634/// In case of the other generators GetSeed will return one of the state elements and not the
635/// given seed. See the documentation of the corresponding generator used
636/// (for example TRandom3::GetSeed() when using TRandom3 or gRandom.
637/// If one needs to save the generator seed in order to be used later for obtaining reproducible
638/// numbers, one should store the full generator, either in a file or in memory in a separate TRandom
639/// object. Here is an example on how to store reproducible states:
640/// ```
641/// // set a unique seed
642/// gRandom->SetSeed(0);
643/// // save generator state in a different TRandom instance
644/// TRandom* rngSaved = static_cast<TRandom*>(gRandom->Clone());
645/// // now both rngSaved and gRandom will produce the same sequence of numbers
646/// for (int i = 0; i < 10; ++i )
647/// std::cout << "generated number from gRandom : " << gRandom->Rndm() << " from saved generator " <<
648/// rngSaved->Rndm() << std::endl;
649/// ```
651{
652 return fSeed;
653}
654
655////////////////////////////////////////////////////////////////////////////////
656/// Generates random vectors, uniformly distributed over the surface
657/// of a sphere of given radius.
658/// Input : r = sphere radius
659/// Output: x,y,z a random 3-d vector of length r
660/// Method: (based on algorithm suggested by Knuth and attributed to Robert E Knop)
661/// which uses less random numbers than the CERNLIB RN23DIM algorithm
662
664{
665 Double_t a=0,b=0,r2=1;
666 while (r2 > 0.25) {
667 a = Rndm() - 0.5;
668 b = Rndm() - 0.5;
669 r2 = a*a + b*b;
670 }
671 z = r* ( -1. + 8.0 * r2 );
672
673 Double_t scale = 8.0 * r * TMath::Sqrt(0.25 - r2);
674 x = a*scale;
675 y = b*scale;
676}
677
678////////////////////////////////////////////////////////////////////////////////
679/// Returns a uniform deviate on the interval (0, x1).
680
682{
683 Double_t ans = Rndm();
684 return x1*ans;
685}
686
687////////////////////////////////////////////////////////////////////////////////
688/// Returns a uniform deviate on the interval (x1, x2).
689
691{
692 Double_t ans= Rndm();
693 return x1 + (x2-x1)*ans;
694}
695
696////////////////////////////////////////////////////////////////////////////////
697/// Writes random generator status to filename.
698
699void TRandom::WriteRandom(const char *filename) const
700{
701 if (!gDirectory) return;
703 TDirectory *file = (TDirectory*)gROOT->ProcessLine(Form("TFile::Open(\"%s\",\"recreate\");",fntmp));
704 delete [] fntmp;
705 if(file && file->GetFile()) {
707 delete file;
708 }
709}
#define b(i)
Definition RSha256.hxx:100
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
unsigned long ULong_t
Unsigned long integer 4 bytes (unsigned long). Size depends on architecture.
Definition RtypesCore.h:69
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:60
float Float_t
Float 4 bytes (float)
Definition RtypesCore.h:71
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define gDirectory
Definition TDirectory.h:385
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:411
R__EXTERN TRandom * gRandom
Definition TRandom.h:62
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2495
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
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:221
virtual Int_t ReadTObject(TObject *, const char *)
Definition TDirectory.h:250
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:49
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1071
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:274
virtual void RndmArray(Int_t n, Float_t *array)
Return an array of n random numbers uniformly distributed in ]0,1[.
Definition TRandom.cxx:594
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
Definition TRandom.cxx:614
virtual void WriteRandom(const char *filename) const
Writes random generator status to filename.
Definition TRandom.cxx:699
Double_t Rndm() override
Machine independent random number generator.
Definition TRandom.cxx:558
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:506
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition TRandom.cxx:460
virtual void ReadRandom(const char *filename)
Reads saved random generator status from filename.
Definition TRandom.cxx:536
virtual UInt_t GetSeed() const
Get the random generator seed.
Definition TRandom.cxx:650
virtual ULong64_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition TRandom.cxx:403
virtual Double_t Exp(Double_t tau)
Returns an exponential deviate.
Definition TRandom.cxx:251
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:239
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
Definition TRandom.cxx:681
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:663
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:380
TRandom(UInt_t seed=65539)
Default constructor. For seed see SetSeed().
Definition TRandom.cxx:186
virtual Int_t Binomial(Int_t ntot, Double_t prob)
Generates a random integer N according to the binomial law.
Definition TRandom.cxx:211
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:225
~TRandom() override
Default destructor.
Definition TRandom.cxx:195
virtual UInt_t Integer(UInt_t imax)
Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
Definition TRandom.cxx:360
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1285
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
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:720
Double_t Floor(Double_t x)
Rounds x downward, returning the largest integral value that is not greater than x.
Definition TMath.h:691
constexpr Double_t PiOver2()
Definition TMath.h:54
Double_t Log(Double_t x)
Returns the natural logarithm of x.
Definition TMath.h:767
Double_t Sqrt(Double_t x)
Returns the square root of x.
Definition TMath.h:673
Double_t Cos(Double_t)
Returns the cosine of an angle of x radians.
Definition TMath.h:605
constexpr Double_t Pi()
Definition TMath.h:40
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:599
Double_t Tan(Double_t)
Returns the tangent of an angle of x radians.
Definition TMath.h:611
Short_t Abs(Short_t d)
Returns the absolute value of parameter Short_t d.
Definition TMathBase.h:124
constexpr Double_t TwoPi()
Definition TMath.h:47
static T Max()
Returns minimum double representation.
Definition TMath.h:944