1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
20 * This file contains the reimplemented version of the Mersenne Twister
21 * Generator of Matsumoto and Nishimura.
23 * See the appropriate copyright notice below.
25 * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
26 * All rights reserved.
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
32 * 1. Redistributions of source code must retain the above copyright
33 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
39 * 3. The names of its contributors may not be used to endorse or promote
40 * products derived from this software without specific prior written
43 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
45 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
46 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
47 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
48 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54 * OF THE POSSIBILITY OF SUCH DAMAGE.
57 * Any feedback is very welcome.
58 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
59 * email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
62 #ifndef LEMON_RANDOM_H
63 #define LEMON_RANDOM_H
65 #include <lemon/config.h>
73 #include <lemon/math.h>
74 #include <lemon/dim2.h>
79 #include <sys/types.h>
82 #include <lemon/bits/windows.h>
87 ///\brief Mersenne Twister random number generator
91 namespace _random_bits {
93 template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
94 struct RandomTraits {};
96 template <typename _Word>
97 struct RandomTraits<_Word, 32> {
100 static const int bits = 32;
102 static const int length = 624;
103 static const int shift = 397;
105 static const Word mul = 0x6c078965u;
106 static const Word arrayInit = 0x012BD6AAu;
107 static const Word arrayMul1 = 0x0019660Du;
108 static const Word arrayMul2 = 0x5D588B65u;
110 static const Word mask = 0x9908B0DFu;
111 static const Word loMask = (1u << 31) - 1;
112 static const Word hiMask = ~loMask;
115 static Word tempering(Word rnd) {
117 rnd ^= (rnd << 7) & 0x9D2C5680u;
118 rnd ^= (rnd << 15) & 0xEFC60000u;
125 template <typename _Word>
126 struct RandomTraits<_Word, 64> {
129 static const int bits = 64;
131 static const int length = 312;
132 static const int shift = 156;
134 static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
135 static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
136 static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
137 static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
139 static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
140 static const Word loMask = (Word(1u) << 31) - 1;
141 static const Word hiMask = ~loMask;
143 static Word tempering(Word rnd) {
144 rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
145 rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
146 rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u));
153 template <typename _Word>
161 static const int bits = RandomTraits<Word>::bits;
163 static const int length = RandomTraits<Word>::length;
164 static const int shift = RandomTraits<Word>::shift;
169 static const Word seedArray[4] = {
170 0x12345u, 0x23456u, 0x34567u, 0x45678u
173 initState(seedArray, seedArray + 4);
176 void initState(Word seed) {
178 static const Word mul = RandomTraits<Word>::mul;
182 Word *curr = state + length - 1;
183 curr[0] = seed; --curr;
184 for (int i = 1; i < length; ++i) {
185 curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
190 template <typename Iterator>
191 void initState(Iterator begin, Iterator end) {
193 static const Word init = RandomTraits<Word>::arrayInit;
194 static const Word mul1 = RandomTraits<Word>::arrayMul1;
195 static const Word mul2 = RandomTraits<Word>::arrayMul2;
198 Word *curr = state + length - 1; --curr;
199 Iterator it = begin; int cnt = 0;
204 num = static_cast<int>(length > end - begin ? length : end - begin);
206 curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1))
213 curr = state + length - 1; curr[0] = state[0];
218 num = length - 1; cnt = static_cast<int>(length - (curr - state) - 1);
220 curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
224 curr = state + length - 1; curr[0] = state[0]; --curr;
229 state[length - 1] = Word(1) << (bits - 1);
232 void copyState(const RandomCore& other) {
233 std::copy(other.state, other.state + length, state);
234 current = state + (other.current - other.state);
238 if (current == state) fillState();
241 return RandomTraits<Word>::tempering(rnd);
248 static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
249 static const Word loMask = RandomTraits<Word>::loMask;
250 static const Word hiMask = RandomTraits<Word>::hiMask;
252 current = state + length;
254 Word *curr = state + length - 1;
257 num = length - shift;
259 curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
260 curr[- shift] ^ mask[curr[-1] & 1ul];
265 curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
266 curr[length - shift] ^ mask[curr[-1] & 1ul];
269 state[0] = (((state[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
270 curr[length - shift] ^ mask[curr[length - 1] & 1ul];
281 template <typename Result,
282 int shift = (std::numeric_limits<Result>::digits + 1) / 2>
284 static Result mask(const Result& result) {
285 return Masker<Result, (shift + 1) / 2>::
286 mask(static_cast<Result>(result | (result >> shift)));
290 template <typename Result>
291 struct Masker<Result, 1> {
292 static Result mask(const Result& result) {
293 return static_cast<Result>(result | (result >> 1));
297 template <typename Result, typename Word,
298 int rest = std::numeric_limits<Result>::digits, int shift = 0,
299 bool last = (rest <= std::numeric_limits<Word>::digits)>
300 struct IntConversion {
301 static const int bits = std::numeric_limits<Word>::digits;
303 static Result convert(RandomCore<Word>& rnd) {
304 return static_cast<Result>(rnd() >> (bits - rest)) << shift;
309 template <typename Result, typename Word, int rest, int shift>
310 struct IntConversion<Result, Word, rest, shift, false> {
311 static const int bits = std::numeric_limits<Word>::digits;
313 static Result convert(RandomCore<Word>& rnd) {
314 return (static_cast<Result>(rnd()) << shift) |
315 IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
320 template <typename Result, typename Word,
321 bool one_word = (std::numeric_limits<Word>::digits <
322 std::numeric_limits<Result>::digits) >
324 static Result map(RandomCore<Word>& rnd, const Result& bound) {
325 Word max = Word(bound - 1);
326 Result mask = Masker<Result>::mask(bound - 1);
329 num = IntConversion<Result, Word>::convert(rnd) & mask;
335 template <typename Result, typename Word>
336 struct Mapping<Result, Word, false> {
337 static Result map(RandomCore<Word>& rnd, const Result& bound) {
338 Word max = Word(bound - 1);
339 Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
349 template <typename Result, int exp>
350 struct ShiftMultiplier {
351 static const Result multiplier() {
352 Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
354 if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
359 template <typename Result>
360 struct ShiftMultiplier<Result, 0> {
361 static const Result multiplier() {
362 return static_cast<Result>(1.0);
366 template <typename Result>
367 struct ShiftMultiplier<Result, 20> {
368 static const Result multiplier() {
369 return static_cast<Result>(1.0/1048576.0);
373 template <typename Result>
374 struct ShiftMultiplier<Result, 32> {
375 static const Result multiplier() {
376 return static_cast<Result>(1.0/4294967296.0);
380 template <typename Result>
381 struct ShiftMultiplier<Result, 53> {
382 static const Result multiplier() {
383 return static_cast<Result>(1.0/9007199254740992.0);
387 template <typename Result>
388 struct ShiftMultiplier<Result, 64> {
389 static const Result multiplier() {
390 return static_cast<Result>(1.0/18446744073709551616.0);
394 template <typename Result, int exp>
396 static Result shift(const Result& result) {
397 return result * ShiftMultiplier<Result, exp>::multiplier();
401 template <typename Result, typename Word,
402 int rest = std::numeric_limits<Result>::digits, int shift = 0,
403 bool last = rest <= std::numeric_limits<Word>::digits>
404 struct RealConversion{
405 static const int bits = std::numeric_limits<Word>::digits;
407 static Result convert(RandomCore<Word>& rnd) {
408 return Shifting<Result, shift + rest>::
409 shift(static_cast<Result>(rnd() >> (bits - rest)));
413 template <typename Result, typename Word, int rest, int shift>
414 struct RealConversion<Result, Word, rest, shift, false> {
415 static const int bits = std::numeric_limits<Word>::digits;
417 static Result convert(RandomCore<Word>& rnd) {
418 return Shifting<Result, shift + bits>::
419 shift(static_cast<Result>(rnd())) +
420 RealConversion<Result, Word, rest-bits, shift + bits>::
425 template <typename Result, typename Word>
428 template <typename Iterator>
429 static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
430 std::vector<Word> ws;
431 for (Iterator it = begin; it != end; ++it) {
432 ws.push_back(Word(*it));
434 rnd.initState(ws.begin(), ws.end());
437 static void init(RandomCore<Word>& rnd, Result seed) {
442 template <typename Word>
443 struct BoolConversion {
444 static bool convert(RandomCore<Word>& rnd) {
445 return (rnd() & 1) == 1;
449 template <typename Word>
450 struct BoolProducer {
454 BoolProducer() : num(0) {}
456 bool convert(RandomCore<Word>& rnd) {
459 num = RandomTraits<Word>::bits;
461 bool r = (buffer & 1);
470 /// \brief Mersenne Twister random number generator
472 /// The Mersenne Twister is a twisted generalized feedback
473 /// shift-register generator of Matsumoto and Nishimura. The period
474 /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
475 /// equi-distributed in 623 dimensions for 32-bit numbers. The time
476 /// performance of this generator is comparable to the commonly used
479 /// This is a template version implementation both 32-bit and
480 /// 64-bit architecture optimized versions. The generators differ
481 /// sligthly in the initialization and generation phase so they
482 /// produce two completly different sequences.
484 /// \alert Do not use this class directly, but instead one of \ref
485 /// Random, \ref Random32 or \ref Random64.
487 /// The generator gives back random numbers of serveral types. To
488 /// get a random number from a range of a floating point type you
489 /// can use one form of the \c operator() or the \c real() member
490 /// function. If you want to get random number from the {0, 1, ...,
491 /// n-1} integer range use the \c operator[] or the \c integer()
492 /// method. And to get random number from the whole range of an
493 /// integer type you can use the argumentless \c integer() or \c
494 /// uinteger() functions. After all you can get random bool with
495 /// equal chance of true and false or given probability of true
496 /// result with the \c boolean() member functions.
499 /// // The commented code is identical to the other
500 /// double a = rnd(); // [0.0, 1.0)
501 /// // double a = rnd.real(); // [0.0, 1.0)
502 /// double b = rnd(100.0); // [0.0, 100.0)
503 /// // double b = rnd.real(100.0); // [0.0, 100.0)
504 /// double c = rnd(1.0, 2.0); // [1.0, 2.0)
505 /// // double c = rnd.real(1.0, 2.0); // [1.0, 2.0)
506 /// int d = rnd[100000]; // 0..99999
507 /// // int d = rnd.integer(100000); // 0..99999
508 /// int e = rnd[6] + 1; // 1..6
509 /// // int e = rnd.integer(1, 1 + 6); // 1..6
510 /// int b = rnd.uinteger<int>(); // 0 .. 2^31 - 1
511 /// int c = rnd.integer<int>(); // - 2^31 .. 2^31 - 1
512 /// bool g = rnd.boolean(); // P(g = true) = 0.5
513 /// bool h = rnd.boolean(0.8); // P(h = true) = 0.8
516 /// LEMON provides a global instance of the random number
517 /// generator which name is \ref lemon::rnd "rnd". Usually it is a
518 /// good programming convenience to use this global generator to get
521 /// \sa \ref Random, \ref Random32 or \ref Random64.
527 _random_bits::RandomCore<Word> core;
528 _random_bits::BoolProducer<Word> bool_producer;
533 ///\name Initialization
537 /// \brief Default constructor
539 /// Constructor with constant seeding.
540 Random() { core.initState(); }
542 /// \brief Constructor with seed
544 /// Constructor with seed. The current number type will be converted
545 /// to the architecture word type.
546 template <typename Number>
547 Random(Number seed) {
548 _random_bits::Initializer<Number, Word>::init(core, seed);
551 /// \brief Constructor with array seeding
553 /// Constructor with array seeding. The given range should contain
554 /// any number type and the numbers will be converted to the
555 /// architecture word type.
556 template <typename Iterator>
557 Random(Iterator begin, Iterator end) {
558 typedef typename std::iterator_traits<Iterator>::value_type Number;
559 _random_bits::Initializer<Number, Word>::init(core, begin, end);
562 /// \brief Copy constructor
564 /// Copy constructor. The generated sequence will be identical to
565 /// the other sequence. It can be used to save the current state
566 /// of the generator and later use it to generate the same
568 Random(const Random& other) {
569 core.copyState(other.core);
572 /// \brief Assign operator
574 /// Assign operator. The generated sequence will be identical to
575 /// the other sequence. It can be used to save the current state
576 /// of the generator and later use it to generate the same
578 Random& operator=(const Random& other) {
579 if (&other != this) {
580 core.copyState(other.core);
585 /// \brief Seeding random sequence
587 /// Seeding the random sequence. The current number type will be
588 /// converted to the architecture word type.
589 template <typename Number>
590 void seed(Number seed) {
591 _random_bits::Initializer<Number, Word>::init(core, seed);
594 /// \brief Seeding random sequence
596 /// Seeding the random sequence. The given range should contain
597 /// any number type and the numbers will be converted to the
598 /// architecture word type.
599 template <typename Iterator>
600 void seed(Iterator begin, Iterator end) {
601 typedef typename std::iterator_traits<Iterator>::value_type Number;
602 _random_bits::Initializer<Number, Word>::init(core, begin, end);
605 /// \brief Seeding from file or from process id and time
607 /// By default, this function calls the \c seedFromFile() member
608 /// function with the <tt>/dev/urandom</tt> file. If it does not success,
609 /// it uses the \c seedFromTime().
610 /// \return Currently always \c true.
613 if (seedFromFile("/dev/urandom", 0)) return true;
615 if (seedFromTime()) return true;
619 /// \brief Seeding from file
621 /// Seeding the random sequence from file. The linux kernel has two
622 /// devices, <tt>/dev/random</tt> and <tt>/dev/urandom</tt> which
623 /// could give good seed values for pseudo random generators (The
624 /// difference between two devices is that the <tt>random</tt> may
625 /// block the reading operation while the kernel can give good
626 /// source of randomness, while the <tt>urandom</tt> does not
627 /// block the input, but it could give back bytes with worse
629 /// \param file The source file
630 /// \param offset The offset, from the file read.
631 /// \return \c true when the seeding successes.
633 bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0)
635 bool seedFromFile(const std::string& file = "", int offset = 0)
638 std::ifstream rs(file.c_str());
641 if (offset != 0 && !rs.seekg(offset)) return false;
642 if (!rs.read(reinterpret_cast<char*>(buf), sizeof(buf))) return false;
643 seed(buf, buf + size);
647 /// \brief Seding from process id and time
649 /// Seding from process id and time. This function uses the
650 /// current process id and the current time for initialize the
652 /// \return Currently always \c true.
653 bool seedFromTime() {
656 gettimeofday(&tv, 0);
657 seed(getpid() + tv.tv_sec + tv.tv_usec);
659 seed(bits::getWinRndSeed());
666 ///\name Uniform Distributions
670 /// \brief Returns a random real number from the range [0, 1)
672 /// It returns a random real number from the range [0, 1). The
673 /// default Number type is \c double.
674 template <typename Number>
676 return _random_bits::RealConversion<Number, Word>::convert(core);
680 return real<double>();
683 /// \brief Returns a random real number from the range [0, 1)
685 /// It returns a random double from the range [0, 1).
686 double operator()() {
687 return real<double>();
690 /// \brief Returns a random real number from the range [0, b)
692 /// It returns a random real number from the range [0, b).
693 double operator()(double b) {
694 return real<double>() * b;
697 /// \brief Returns a random real number from the range [a, b)
699 /// It returns a random real number from the range [a, b).
700 double operator()(double a, double b) {
701 return real<double>() * (b - a) + a;
704 /// \brief Returns a random integer from a range
706 /// It returns a random integer from the range {0, 1, ..., b - 1}.
707 template <typename Number>
708 Number integer(Number b) {
709 return _random_bits::Mapping<Number, Word>::map(core, b);
712 /// \brief Returns a random integer from a range
714 /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
715 template <typename Number>
716 Number integer(Number a, Number b) {
717 return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
720 /// \brief Returns a random integer from a range
722 /// It returns a random integer from the range {0, 1, ..., b - 1}.
723 template <typename Number>
724 Number operator[](Number b) {
725 return _random_bits::Mapping<Number, Word>::map(core, b);
728 /// \brief Returns a random non-negative integer
730 /// It returns a random non-negative integer uniformly from the
731 /// whole range of the current \c Number type. The default result
732 /// type of this function is <tt>unsigned int</tt>.
733 template <typename Number>
735 return _random_bits::IntConversion<Number, Word>::convert(core);
738 unsigned int uinteger() {
739 return uinteger<unsigned int>();
742 /// \brief Returns a random integer
744 /// It returns a random integer uniformly from the whole range of
745 /// the current \c Number type. The default result type of this
746 /// function is \c int.
747 template <typename Number>
749 static const int nb = std::numeric_limits<Number>::digits +
750 (std::numeric_limits<Number>::is_signed ? 1 : 0);
751 return _random_bits::IntConversion<Number, Word, nb>::convert(core);
755 return integer<int>();
758 /// \brief Returns a random bool
760 /// It returns a random bool. The generator holds a buffer for
761 /// random bits. Every time when it become empty the generator makes
762 /// a new random word and fill the buffer up.
764 return bool_producer.convert(core);
769 ///\name Non-uniform Distributions
773 /// \brief Returns a random bool with given probability of true result.
775 /// It returns a random bool with given probability of true result.
776 bool boolean(double p) {
777 return operator()() < p;
780 /// Standard normal (Gauss) distribution
782 /// Standard normal (Gauss) distribution.
783 /// \note The Cartesian form of the Box-Muller
784 /// transformation is used to generate a random normal distribution.
789 V1=2*real<double>()-1;
790 V2=2*real<double>()-1;
793 return std::sqrt(-2*std::log(S)/S)*V1;
795 /// Normal (Gauss) distribution with given mean and standard deviation
797 /// Normal (Gauss) distribution with given mean and standard deviation.
799 double gauss(double mean,double std_dev)
801 return gauss()*std_dev+mean;
804 /// Lognormal distribution
806 /// Lognormal distribution. The parameters are the mean and the standard
807 /// deviation of <tt>exp(X)</tt>.
809 double lognormal(double n_mean,double n_std_dev)
811 return std::exp(gauss(n_mean,n_std_dev));
813 /// Lognormal distribution
815 /// Lognormal distribution. The parameter is an <tt>std::pair</tt> of
816 /// the mean and the standard deviation of <tt>exp(X)</tt>.
818 double lognormal(const std::pair<double,double> ¶ms)
820 return std::exp(gauss(params.first,params.second));
822 /// Compute the lognormal parameters from mean and standard deviation
824 /// This function computes the lognormal parameters from mean and
825 /// standard deviation. The return value can direcly be passed to
827 std::pair<double,double> lognormalParamsFromMD(double mean,
830 double fr=std_dev/mean;
832 double lg=std::log(1+fr);
833 return std::pair<double,double>(std::log(mean)-lg/2.0,std::sqrt(lg));
835 /// Lognormal distribution with given mean and standard deviation
837 /// Lognormal distribution with given mean and standard deviation.
839 double lognormalMD(double mean,double std_dev)
841 return lognormal(lognormalParamsFromMD(mean,std_dev));
844 /// Exponential distribution with given mean
846 /// This function generates an exponential distribution random number
847 /// with mean <tt>1/lambda</tt>.
849 double exponential(double lambda=1.0)
851 return -std::log(1.0-real<double>())/lambda;
854 /// Gamma distribution with given integer shape
856 /// This function generates a gamma distribution random number.
858 ///\param k shape parameter (<tt>k>0</tt> integer)
862 for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
866 /// Gamma distribution with given shape and scale parameter
868 /// This function generates a gamma distribution random number.
870 ///\param k shape parameter (<tt>k>0</tt>)
871 ///\param theta scale parameter
873 double gamma(double k,double theta=1.0)
876 const double delta = k-std::floor(k);
877 const double v0=E/(E-delta);
879 double V0=1.0-real<double>();
880 double V1=1.0-real<double>();
881 double V2=1.0-real<double>();
884 xi=std::pow(V1,1.0/delta);
885 nu=V0*std::pow(xi,delta-1.0);
892 } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
893 return theta*(xi+gamma(int(std::floor(k))));
896 /// Weibull distribution
898 /// This function generates a Weibull distribution random number.
900 ///\param k shape parameter (<tt>k>0</tt>)
901 ///\param lambda scale parameter (<tt>lambda>0</tt>)
903 double weibull(double k,double lambda)
905 return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
908 /// Pareto distribution
910 /// This function generates a Pareto distribution random number.
912 ///\param k shape parameter (<tt>k>0</tt>)
913 ///\param x_min location parameter (<tt>x_min>0</tt>)
915 double pareto(double k,double x_min)
917 return exponential(gamma(k,1.0/x_min))+x_min;
920 /// Poisson distribution
922 /// This function generates a Poisson distribution random number with
923 /// parameter \c lambda.
925 /// The probability mass function of this distribusion is
926 /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f]
927 /// \note The algorithm is taken from the book of Donald E. Knuth titled
928 /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the
931 int poisson(double lambda)
933 const double l = std::exp(-lambda);
945 ///\name Two Dimensional Distributions
949 /// Uniform distribution on the full unit circle
951 /// Uniform distribution on the full unit circle.
953 dim2::Point<double> disc()
957 V1=2*real<double>()-1;
958 V2=2*real<double>()-1;
960 } while(V1*V1+V2*V2>=1);
961 return dim2::Point<double>(V1,V2);
963 /// A kind of two dimensional normal (Gauss) distribution
965 /// This function provides a turning symmetric two-dimensional distribution.
966 /// Both coordinates are of standard normal distribution, but they are not
969 /// \note The coordinates are the two random variables provided by
970 /// the Box-Muller method.
971 dim2::Point<double> gauss2()
975 V1=2*real<double>()-1;
976 V2=2*real<double>()-1;
979 double W=std::sqrt(-2*std::log(S)/S);
980 return dim2::Point<double>(W*V1,W*V2);
982 /// A kind of two dimensional exponential distribution
984 /// This function provides a turning symmetric two-dimensional distribution.
985 /// The x-coordinate is of conditionally exponential distribution
986 /// with the condition that x is positive and y=0. If x is negative and
987 /// y=0 then, -x is of exponential distribution. The same is true for the
989 dim2::Point<double> exponential2()
993 V1=2*real<double>()-1;
994 V2=2*real<double>()-1;
997 double W=-std::log(S)/S;
998 return dim2::Point<double>(W*V1,W*V2);
1009 /// \brief Mersenne Twister random number generator
1011 /// This class implements either the 32 bit or the 64 bit version of
1012 /// the Mersenne Twister random number generator algorithm
1013 /// depending the the system architecture.
1015 /// For the API description, see its base class \ref
1016 /// _random_bits::Random
1018 /// \sa \ref _random_bits::Random
1019 typedef _random_bits::Random<unsigned long> Random;
1022 /// \brief Mersenne Twister random number generator (32 bit version)
1024 /// This class implements the 32 bit version of the Mersenne Twister
1025 /// random number generator algorithm. It is recommended to be used
1026 /// when someone wants to make sure that the \e same pseudo random
1027 /// sequence will be generated on every platfrom.
1029 /// For the API description, see its base class \ref
1030 /// _random_bits::Random
1032 /// \sa \ref _random_bits::Random
1034 typedef _random_bits::Random<unsigned int> Random32;
1037 /// \brief Mersenne Twister random number generator (64 bit version)
1039 /// This class implements the 64 bit version of the Mersenne Twister
1040 /// random number generator algorithm. (Even though it will run
1041 /// on 32 bit architectures, too.) It is recommended to ber used when
1042 /// someone wants to make sure that the \e same pseudo random sequence
1043 /// will be generated on every platfrom.
1045 /// For the API description, see its base class \ref
1046 /// _random_bits::Random
1048 /// \sa \ref _random_bits::Random
1049 typedef _random_bits::Random<unsigned long long> Random64;