3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
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
72 #include <lemon/math.h>
73 #include <lemon/dim2.h>
76 ///\brief Mersenne Twister random number generator
78 ///\author Balazs Dezso
82 namespace _random_bits {
84 template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
85 struct RandomTraits {};
87 template <typename _Word>
88 struct RandomTraits<_Word, 32> {
91 static const int bits = 32;
93 static const int length = 624;
94 static const int shift = 397;
96 static const Word mul = 0x6c078965u;
97 static const Word arrayInit = 0x012BD6AAu;
98 static const Word arrayMul1 = 0x0019660Du;
99 static const Word arrayMul2 = 0x5D588B65u;
101 static const Word mask = 0x9908B0DFu;
102 static const Word loMask = (1u << 31) - 1;
103 static const Word hiMask = ~loMask;
106 static Word tempering(Word rnd) {
108 rnd ^= (rnd << 7) & 0x9D2C5680u;
109 rnd ^= (rnd << 15) & 0xEFC60000u;
116 template <typename _Word>
117 struct RandomTraits<_Word, 64> {
120 static const int bits = 64;
122 static const int length = 312;
123 static const int shift = 156;
125 static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
126 static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
127 static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
128 static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
130 static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
131 static const Word loMask = (Word(1u) << 31) - 1;
132 static const Word hiMask = ~loMask;
134 static Word tempering(Word rnd) {
135 rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
136 rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
137 rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u));
144 template <typename _Word>
152 static const int bits = RandomTraits<Word>::bits;
154 static const int length = RandomTraits<Word>::length;
155 static const int shift = RandomTraits<Word>::shift;
160 static const Word seedArray[4] = {
161 0x12345u, 0x23456u, 0x34567u, 0x45678u
164 initState(seedArray, seedArray + 4);
167 void initState(Word seed) {
169 static const Word mul = RandomTraits<Word>::mul;
173 Word *curr = state + length - 1;
174 curr[0] = seed; --curr;
175 for (int i = 1; i < length; ++i) {
176 curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
181 template <typename Iterator>
182 void initState(Iterator begin, Iterator end) {
184 static const Word init = RandomTraits<Word>::arrayInit;
185 static const Word mul1 = RandomTraits<Word>::arrayMul1;
186 static const Word mul2 = RandomTraits<Word>::arrayMul2;
189 Word *curr = state + length - 1; --curr;
190 Iterator it = begin; int cnt = 0;
195 num = length > end - begin ? length : end - begin;
197 curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1))
204 curr = state + length - 1; curr[0] = state[0];
209 num = length - 1; cnt = length - (curr - state) - 1;
211 curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
215 curr = state + length - 1; curr[0] = state[0]; --curr;
220 state[length - 1] = Word(1) << (bits - 1);
223 void copyState(const RandomCore& other) {
224 std::copy(other.state, other.state + length, state);
225 current = state + (other.current - other.state);
229 if (current == state) fillState();
232 return RandomTraits<Word>::tempering(rnd);
239 static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
240 static const Word loMask = RandomTraits<Word>::loMask;
241 static const Word hiMask = RandomTraits<Word>::hiMask;
243 current = state + length;
245 register Word *curr = state + length - 1;
248 num = length - shift;
250 curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
251 curr[- shift] ^ mask[curr[-1] & 1ul];
256 curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
257 curr[length - shift] ^ mask[curr[-1] & 1ul];
260 state[0] = (((state[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
261 curr[length - shift] ^ mask[int(curr[length - 1] & 1ul)];
272 template <typename Result,
273 int shift = (std::numeric_limits<Result>::digits + 1) / 2>
275 static Result mask(const Result& result) {
276 return Masker<Result, (shift + 1) / 2>::
277 mask(static_cast<Result>(result | (result >> shift)));
281 template <typename Result>
282 struct Masker<Result, 1> {
283 static Result mask(const Result& result) {
284 return static_cast<Result>(result | (result >> 1));
288 template <typename Result, typename Word,
289 int rest = std::numeric_limits<Result>::digits, int shift = 0,
290 bool last = rest <= std::numeric_limits<Word>::digits>
291 struct IntConversion {
292 static const int bits = std::numeric_limits<Word>::digits;
294 static Result convert(RandomCore<Word>& rnd) {
295 return static_cast<Result>(rnd() >> (bits - rest)) << shift;
300 template <typename Result, typename Word, int rest, int shift>
301 struct IntConversion<Result, Word, rest, shift, false> {
302 static const int bits = std::numeric_limits<Word>::digits;
304 static Result convert(RandomCore<Word>& rnd) {
305 return (static_cast<Result>(rnd()) << shift) |
306 IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
311 template <typename Result, typename Word,
312 bool one_word = (std::numeric_limits<Word>::digits <
313 std::numeric_limits<Result>::digits) >
315 static Result map(RandomCore<Word>& rnd, const Result& bound) {
316 Word max = Word(bound - 1);
317 Result mask = Masker<Result>::mask(bound - 1);
320 num = IntConversion<Result, Word>::convert(rnd) & mask;
326 template <typename Result, typename Word>
327 struct Mapping<Result, Word, false> {
328 static Result map(RandomCore<Word>& rnd, const Result& bound) {
329 Word max = Word(bound - 1);
330 Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
340 template <typename Result, int exp, bool pos = (exp >= 0)>
341 struct ShiftMultiplier {
342 static const Result multiplier() {
343 Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
345 if ((exp & 1) == 1) res *= static_cast<Result>(2.0);
350 template <typename Result, int exp>
351 struct ShiftMultiplier<Result, exp, false> {
352 static const Result multiplier() {
353 Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
355 if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
360 template <typename Result>
361 struct ShiftMultiplier<Result, 0, true> {
362 static const Result multiplier() {
363 return static_cast<Result>(1.0);
367 template <typename Result>
368 struct ShiftMultiplier<Result, -20, true> {
369 static const Result multiplier() {
370 return static_cast<Result>(1.0/1048576.0);
374 template <typename Result>
375 struct ShiftMultiplier<Result, -32, true> {
376 static const Result multiplier() {
377 return static_cast<Result>(1.0/424967296.0);
381 template <typename Result>
382 struct ShiftMultiplier<Result, -53, true> {
383 static const Result multiplier() {
384 return static_cast<Result>(1.0/9007199254740992.0);
388 template <typename Result>
389 struct ShiftMultiplier<Result, -64, true> {
390 static const Result multiplier() {
391 return static_cast<Result>(1.0/18446744073709551616.0);
395 template <typename Result, int exp>
397 static Result shift(const Result& result) {
398 return result * ShiftMultiplier<Result, exp>::multiplier();
402 template <typename Result, typename Word,
403 int rest = std::numeric_limits<Result>::digits, int shift = 0,
404 bool last = rest <= std::numeric_limits<Word>::digits>
405 struct RealConversion{
406 static const int bits = std::numeric_limits<Word>::digits;
408 static Result convert(RandomCore<Word>& rnd) {
409 return Shifting<Result, - shift - rest>::
410 shift(static_cast<Result>(rnd() >> (bits - rest)));
414 template <typename Result, typename Word, int rest, int shift>
415 struct RealConversion<Result, Word, rest, shift, false> {
416 static const int bits = std::numeric_limits<Word>::digits;
418 static Result convert(RandomCore<Word>& rnd) {
419 return Shifting<Result, - shift - bits>::
420 shift(static_cast<Result>(rnd())) +
421 RealConversion<Result, Word, rest-bits, shift + bits>::
426 template <typename Result, typename Word>
429 template <typename Iterator>
430 static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
431 std::vector<Word> ws;
432 for (Iterator it = begin; it != end; ++it) {
433 ws.push_back(Word(*it));
435 rnd.initState(ws.begin(), ws.end());
438 static void init(RandomCore<Word>& rnd, Result seed) {
443 template <typename Word>
444 struct BoolConversion {
445 static bool convert(RandomCore<Word>& rnd) {
446 return (rnd() & 1) == 1;
450 template <typename Word>
451 struct BoolProducer {
455 BoolProducer() : num(0) {}
457 bool convert(RandomCore<Word>& rnd) {
460 num = RandomTraits<Word>::bits;
462 bool r = (buffer & 1);
473 /// \brief Mersenne Twister random number generator
475 /// The Mersenne Twister is a twisted generalized feedback
476 /// shift-register generator of Matsumoto and Nishimura. The period
477 /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
478 /// equi-distributed in 623 dimensions for 32-bit numbers. The time
479 /// performance of this generator is comparable to the commonly used
482 /// This implementation is specialized for both 32-bit and 64-bit
483 /// architectures. The generators differ sligthly in the
484 /// initialization and generation phase so they produce two
485 /// completly different sequences.
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 /// The 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 /// \author Balazs Dezso
526 typedef unsigned long Word;
528 _random_bits::RandomCore<Word> core;
529 _random_bits::BoolProducer<Word> bool_producer;
534 /// \brief Constructor
536 /// Constructor with constant seeding.
537 Random() { core.initState(); }
539 /// \brief Constructor
541 /// Constructor with seed. The current number type will be converted
542 /// to the architecture word type.
543 template <typename Number>
544 Random(Number seed) {
545 _random_bits::Initializer<Number, Word>::init(core, seed);
548 /// \brief Constructor
550 /// Constructor with array seeding. The given range should contain
551 /// any number type and the numbers will be converted to the
552 /// architecture word type.
553 template <typename Iterator>
554 Random(Iterator begin, Iterator end) {
555 typedef typename std::iterator_traits<Iterator>::value_type Number;
556 _random_bits::Initializer<Number, Word>::init(core, begin, end);
559 /// \brief Copy constructor
561 /// Copy constructor. The generated sequence will be identical to
562 /// the other sequence. It can be used to save the current state
563 /// of the generator and later use it to generate the same
565 Random(const Random& other) {
566 core.copyState(other.core);
569 /// \brief Assign operator
571 /// Assign operator. The generated sequence will be identical to
572 /// the other sequence. It can be used to save the current state
573 /// of the generator and later use it to generate the same
575 Random& operator=(const Random& other) {
576 if (&other != this) {
577 core.copyState(other.core);
582 /// \brief Seeding random sequence
584 /// Seeding the random sequence. The current number type will be
585 /// converted to the architecture word type.
586 template <typename Number>
587 void seed(Number seed) {
588 _random_bits::Initializer<Number, Word>::init(core, seed);
591 /// \brief Seeding random sequence
593 /// Seeding the random sequence. The given range should contain
594 /// any number type and the numbers will be converted to the
595 /// architecture word type.
596 template <typename Iterator>
597 void seed(Iterator begin, Iterator end) {
598 typedef typename std::iterator_traits<Iterator>::value_type Number;
599 _random_bits::Initializer<Number, Word>::init(core, begin, end);
602 /// \brief Returns a random real number from the range [0, 1)
604 /// It returns a random real number from the range [0, 1). The
605 /// default Number type is double.
606 template <typename Number>
608 return _random_bits::RealConversion<Number, Word>::convert(core);
612 return real<double>();
615 /// \brief Returns a random real number the range [0, b)
617 /// It returns a random real number from the range [0, b).
618 template <typename Number>
619 Number real(Number b) {
620 return real<Number>() * b;
623 /// \brief Returns a random real number from the range [a, b)
625 /// It returns a random real number from the range [a, b).
626 template <typename Number>
627 Number real(Number a, Number b) {
628 return real<Number>() * (b - a) + a;
631 /// \brief Returns a random real number from the range [0, 1)
633 /// It returns a random double from the range [0, 1).
634 double operator()() {
635 return real<double>();
638 /// \brief Returns a random real number from the range [0, b)
640 /// It returns a random real number from the range [0, b).
641 template <typename Number>
642 Number operator()(Number b) {
643 return real<Number>() * b;
646 /// \brief Returns a random real number from the range [a, b)
648 /// It returns a random real number from the range [a, b).
649 template <typename Number>
650 Number operator()(Number a, Number b) {
651 return real<Number>() * (b - a) + a;
654 /// \brief Returns a random integer from a range
656 /// It returns a random integer from the range {0, 1, ..., b - 1}.
657 template <typename Number>
658 Number integer(Number b) {
659 return _random_bits::Mapping<Number, Word>::map(core, b);
662 /// \brief Returns a random integer from a range
664 /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
665 template <typename Number>
666 Number integer(Number a, Number b) {
667 return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
670 /// \brief Returns a random integer from a range
672 /// It returns a random integer from the range {0, 1, ..., b - 1}.
673 template <typename Number>
674 Number operator[](Number b) {
675 return _random_bits::Mapping<Number, Word>::map(core, b);
678 /// \brief Returns a random non-negative integer
680 /// It returns a random non-negative integer uniformly from the
681 /// whole range of the current \c Number type. The default result
682 /// type of this function is unsigned int.
683 template <typename Number>
685 return _random_bits::IntConversion<Number, Word>::convert(core);
688 unsigned int uinteger() {
689 return uinteger<unsigned int>();
692 /// \brief Returns a random integer
694 /// It returns a random integer uniformly from the whole range of
695 /// the current \c Number type. The default result type of this
697 template <typename Number>
699 static const int nb = std::numeric_limits<Number>::digits +
700 (std::numeric_limits<Number>::is_signed ? 1 : 0);
701 return _random_bits::IntConversion<Number, Word, nb>::convert(core);
705 return integer<int>();
708 /// \brief Returns a random bool
710 /// It returns a random bool. The generator holds a buffer for
711 /// random bits. Every time when it become empty the generator makes
712 /// a new random word and fill the buffer up.
714 return bool_producer.convert(core);
717 ///\name Nonuniform distributions
722 /// \brief Returns a random bool
724 /// It returns a random bool with given probability of true result
725 bool boolean(double p) {
726 return operator()() < p;
729 /// Standard Gauss distribution
731 /// Standard Gauss distribution.
732 /// \note The Cartesian form of the Box-Muller
733 /// transformation is used to generate a random normal distribution.
734 /// \todo Consider using the "ziggurat" method instead.
739 V1=2*real<double>()-1;
740 V2=2*real<double>()-1;
743 return std::sqrt(-2*std::log(S)/S)*V1;
745 /// Gauss distribution with given standard deviation and mean 0
749 double gauss(double std_dev)
751 return gauss()*std_dev;
753 /// Gauss distribution with given mean and standard deviation
757 double gauss(double mean,double std_dev)
759 return gauss()*std_dev+mean;
762 /// Exponential distribution with given mean
764 /// This function generates an exponential distribution random number
765 /// with mean <tt>1/lambda</tt>.
767 double exponential(double lambda=1.0)
769 return -std::log(real<double>())/lambda;
775 for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
779 /// Gamma distribution with given shape and scale parameter
781 /// This function generates a gamma distribution random number.
783 ///\param k shape parameter (<tt>k>0</tt>)
784 ///\param theta scale parameter
786 double gamma(double k,double theta=1.0)
789 const double delta = k-std::floor(k);
790 const double v0=E/(E-delta);
792 double V0=1.0-real<double>();
793 double V1=1.0-real<double>();
794 double V2=1.0-real<double>();
797 xi=std::pow(V1,1.0/delta);
798 nu=V0*std::pow(xi,delta-1.0);
805 } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
806 return theta*(xi+gamma(int(std::floor(k))));
812 ///\name Two dimensional distributions
817 /// Uniform distribution on the full unit circle.
818 dim2::Point<double> disc()
822 V1=2*real<double>()-1;
823 V2=2*real<double>()-1;
825 } while(V1*V1+V2*V2>=1);
826 return dim2::Point<double>(V1,V2);
828 /// A kind of two dimensional Gauss distribution
830 /// This function provides a turning symmetric two-dimensional distribution.
831 /// Both coordinates are of standard normal distribution, but they are not
834 /// \note The coordinates are the two random variables provided by
835 /// the Box-Muller method.
836 dim2::Point<double> gauss2()
840 V1=2*real<double>()-1;
841 V2=2*real<double>()-1;
844 double W=std::sqrt(-2*std::log(S)/S);
845 return dim2::Point<double>(W*V1,W*V2);
847 /// A kind of two dimensional exponential distribution
849 /// This function provides a turning symmetric two-dimensional distribution.
850 /// The x-coordinate is of conditionally exponential distribution
851 /// with the condition that x is positive and y=0. If x is negative and
852 /// y=0 then, -x is of exponential distribution. The same is true for the
854 dim2::Point<double> exponential2()
858 V1=2*real<double>()-1;
859 V2=2*real<double>()-1;
862 double W=-std::log(S)/S;
863 return dim2::Point<double>(W*V1,W*V2);