lemon/random.h
author deba
Sun, 05 Oct 2008 20:08:13 +0000
changeset 2622 fa2877651022
parent 2608 207efbaea269
permissions -rw-r--r--
Fix _setCoeff
     1 /* -*- C++ -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library
     4  *
     5  * Copyright (C) 2003-2008
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     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.
    12  *
    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
    15  * purpose.
    16  *
    17  */
    18 
    19 /*
    20  * This file contains the reimplemented version of the Mersenne Twister
    21  * Generator of Matsumoto and Nishimura.
    22  *
    23  * See the appropriate copyright notice below.
    24  * 
    25  * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
    26  * All rights reserved.                          
    27  *
    28  * Redistribution and use in source and binary forms, with or without
    29  * modification, are permitted provided that the following conditions
    30  * are met:
    31  *
    32  * 1. Redistributions of source code must retain the above copyright
    33  *    notice, this list of conditions and the following disclaimer.
    34  *
    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.
    38  *
    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 
    41  *    permission.
    42  *
    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.
    55  *
    56  *
    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)
    60  */
    61 
    62 #ifndef LEMON_RANDOM_H
    63 #define LEMON_RANDOM_H
    64 
    65 #include <algorithm>
    66 #include <iterator>
    67 #include <vector>
    68 
    69 #include <ctime>
    70 #include <limits>
    71 
    72 #include <lemon/math.h>
    73 #include <lemon/dim2.h>
    74 ///\ingroup misc
    75 ///\file
    76 ///\brief Mersenne Twister random number generator
    77 ///
    78 ///\author Balazs Dezso
    79 
    80 namespace lemon {
    81 
    82   namespace _random_bits {
    83     
    84     template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
    85     struct RandomTraits {};
    86 
    87     template <typename _Word>
    88     struct RandomTraits<_Word, 32> {
    89 
    90       typedef _Word Word;
    91       static const int bits = 32;
    92 
    93       static const int length = 624;
    94       static const int shift = 397;
    95       
    96       static const Word mul = 0x6c078965u;
    97       static const Word arrayInit = 0x012BD6AAu;
    98       static const Word arrayMul1 = 0x0019660Du;
    99       static const Word arrayMul2 = 0x5D588B65u;
   100 
   101       static const Word mask = 0x9908B0DFu;
   102       static const Word loMask = (1u << 31) - 1;
   103       static const Word hiMask = ~loMask;
   104 
   105 
   106       static Word tempering(Word rnd) {
   107         rnd ^= (rnd >> 11);
   108         rnd ^= (rnd << 7) & 0x9D2C5680u;
   109         rnd ^= (rnd << 15) & 0xEFC60000u;
   110         rnd ^= (rnd >> 18);
   111         return rnd;
   112       }
   113 
   114     };
   115 
   116     template <typename _Word>
   117     struct RandomTraits<_Word, 64> {
   118 
   119       typedef _Word Word;
   120       static const int bits = 64;
   121 
   122       static const int length = 312;
   123       static const int shift = 156;
   124 
   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);
   129 
   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;
   133 
   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));
   138         rnd ^= (rnd >> 43);
   139         return rnd;
   140       }
   141 
   142     };
   143 
   144     template <typename _Word>
   145     class RandomCore {
   146     public:
   147 
   148       typedef _Word Word;
   149 
   150     private:
   151 
   152       static const int bits = RandomTraits<Word>::bits;
   153 
   154       static const int length = RandomTraits<Word>::length;
   155       static const int shift = RandomTraits<Word>::shift;
   156 
   157     public:
   158 
   159       void initState() {
   160         static const Word seedArray[4] = {
   161           0x12345u, 0x23456u, 0x34567u, 0x45678u
   162         };
   163     
   164         initState(seedArray, seedArray + 4);
   165       }
   166 
   167       void initState(Word seed) {
   168 
   169         static const Word mul = RandomTraits<Word>::mul;
   170 
   171         current = state; 
   172 
   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);
   177           --curr;
   178         }
   179       }
   180 
   181       template <typename Iterator>
   182       void initState(Iterator begin, Iterator end) {
   183 
   184         static const Word init = RandomTraits<Word>::arrayInit;
   185         static const Word mul1 = RandomTraits<Word>::arrayMul1;
   186         static const Word mul2 = RandomTraits<Word>::arrayMul2;
   187 
   188 
   189         Word *curr = state + length - 1; --curr;
   190         Iterator it = begin; int cnt = 0;
   191         int num;
   192 
   193         initState(init);
   194 
   195         num = length > end - begin ? length : end - begin;
   196         while (num--) {
   197           curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 
   198             + *it + cnt;
   199           ++it; ++cnt;
   200           if (it == end) {
   201             it = begin; cnt = 0;
   202           }
   203           if (curr == state) {
   204             curr = state + length - 1; curr[0] = state[0];
   205           }
   206           --curr;
   207         }
   208 
   209         num = length - 1; cnt = length - (curr - state) - 1;
   210         while (num--) {
   211           curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
   212             - cnt;
   213           --curr; ++cnt;
   214           if (curr == state) {
   215             curr = state + length - 1; curr[0] = state[0]; --curr;
   216             cnt = 1;
   217           }
   218         }
   219         
   220         state[length - 1] = Word(1) << (bits - 1);
   221       }
   222       
   223       void copyState(const RandomCore& other) {
   224         std::copy(other.state, other.state + length, state);
   225         current = state + (other.current - other.state);
   226       }
   227 
   228       Word operator()() {
   229         if (current == state) fillState();
   230         --current;
   231         Word rnd = *current;
   232         return RandomTraits<Word>::tempering(rnd);
   233       }
   234 
   235     private:
   236 
   237   
   238       void fillState() {
   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;
   242 
   243         current = state + length; 
   244 
   245         register Word *curr = state + length - 1;
   246         register long num;
   247       
   248         num = length - shift;
   249         while (num--) {
   250           curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
   251             curr[- shift] ^ mask[curr[-1] & 1ul];
   252           --curr;
   253         }
   254         num = shift - 1;
   255         while (num--) {
   256           curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
   257             curr[length - shift] ^ mask[curr[-1] & 1ul];
   258           --curr;
   259         }
   260         state[0] = (((state[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
   261           curr[length - shift] ^ mask[int(curr[length - 1] & 1ul)];
   262 
   263       }
   264 
   265   
   266       Word *current;
   267       Word state[length];
   268       
   269     };
   270 
   271 
   272     template <typename Result, 
   273               int shift = (std::numeric_limits<Result>::digits + 1) / 2>
   274     struct Masker {
   275       static Result mask(const Result& result) {
   276         return Masker<Result, (shift + 1) / 2>::
   277           mask(static_cast<Result>(result | (result >> shift)));
   278       }
   279     };
   280     
   281     template <typename Result>
   282     struct Masker<Result, 1> {
   283       static Result mask(const Result& result) {
   284         return static_cast<Result>(result | (result >> 1));
   285       }
   286     };
   287 
   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;
   293     
   294       static Result convert(RandomCore<Word>& rnd) {
   295         return static_cast<Result>(rnd() >> (bits - rest)) << shift;
   296       }
   297       
   298     }; 
   299 
   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;
   303 
   304       static Result convert(RandomCore<Word>& rnd) {
   305         return (static_cast<Result>(rnd()) << shift) | 
   306           IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
   307       }
   308     };
   309 
   310 
   311     template <typename Result, typename Word,
   312               bool one_word = (std::numeric_limits<Word>::digits < 
   313 			       std::numeric_limits<Result>::digits) >
   314     struct Mapping {
   315       static Result map(RandomCore<Word>& rnd, const Result& bound) {
   316         Word max = Word(bound - 1);
   317         Result mask = Masker<Result>::mask(bound - 1);
   318         Result num;
   319         do {
   320           num = IntConversion<Result, Word>::convert(rnd) & mask; 
   321         } while (num > max);
   322         return num;
   323       }
   324     };
   325 
   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>
   331           ::mask(max);
   332         Word num;
   333         do {
   334           num = rnd() & mask;
   335         } while (num > max);
   336         return num;
   337       }
   338     };
   339 
   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();
   344         res *= res;
   345         if ((exp & 1) == 1) res *= static_cast<Result>(2.0);
   346         return res; 
   347       }
   348     };
   349 
   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();
   354         res *= res;
   355         if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
   356         return res; 
   357       }
   358     };
   359 
   360     template <typename Result>
   361     struct ShiftMultiplier<Result, 0, true> {
   362       static const Result multiplier() {
   363         return static_cast<Result>(1.0); 
   364       }
   365     };
   366 
   367     template <typename Result>
   368     struct ShiftMultiplier<Result, -20, true> {
   369       static const Result multiplier() {
   370         return static_cast<Result>(1.0/1048576.0); 
   371       }
   372     };
   373     
   374     template <typename Result>
   375     struct ShiftMultiplier<Result, -32, true> {
   376       static const Result multiplier() {
   377         return static_cast<Result>(1.0/424967296.0); 
   378       }
   379     };
   380 
   381     template <typename Result>
   382     struct ShiftMultiplier<Result, -53, true> {
   383       static const Result multiplier() {
   384         return static_cast<Result>(1.0/9007199254740992.0); 
   385       }
   386     };
   387 
   388     template <typename Result>
   389     struct ShiftMultiplier<Result, -64, true> {
   390       static const Result multiplier() {
   391         return static_cast<Result>(1.0/18446744073709551616.0); 
   392       }
   393     };
   394 
   395     template <typename Result, int exp>
   396     struct Shifting {
   397       static Result shift(const Result& result) {
   398         return result * ShiftMultiplier<Result, exp>::multiplier();
   399       }
   400     };
   401 
   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;
   407 
   408       static Result convert(RandomCore<Word>& rnd) {
   409         return Shifting<Result, - shift - rest>::
   410           shift(static_cast<Result>(rnd() >> (bits - rest)));
   411       }
   412     };
   413 
   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;
   417 
   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>::
   422           convert(rnd);
   423       }
   424     };
   425 
   426     template <typename Result, typename Word>
   427     struct Initializer {
   428 
   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));
   434         }
   435         rnd.initState(ws.begin(), ws.end());
   436       }
   437 
   438       static void init(RandomCore<Word>& rnd, Result seed) {
   439         rnd.initState(seed);
   440       }
   441     };
   442 
   443     template <typename Word>
   444     struct BoolConversion {
   445       static bool convert(RandomCore<Word>& rnd) {
   446         return (rnd() & 1) == 1;
   447       }
   448     };
   449 
   450     template <typename Word>
   451     struct BoolProducer {
   452       Word buffer;
   453       int num;
   454       
   455       BoolProducer() : num(0) {}
   456 
   457       bool convert(RandomCore<Word>& rnd) {
   458         if (num == 0) {
   459           buffer = rnd();
   460           num = RandomTraits<Word>::bits;
   461         }
   462         bool r = (buffer & 1);
   463         buffer >>= 1;
   464         --num;
   465         return r;
   466       }
   467     };
   468 
   469   }
   470 
   471   /// \ingroup misc
   472   ///
   473   /// \brief Mersenne Twister random number generator
   474   ///
   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
   480   /// generators.
   481   ///
   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.
   486   ///
   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.
   497   ///
   498   ///\code
   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
   514   ///\endcode
   515   ///
   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
   519   /// random numbers.
   520   ///
   521   /// \author Balazs Dezso
   522   class Random {
   523   private:
   524 
   525     // architecture word
   526     typedef unsigned long Word;
   527     
   528     _random_bits::RandomCore<Word> core;
   529     _random_bits::BoolProducer<Word> bool_producer;
   530     
   531 
   532   public:
   533 
   534     /// \brief Constructor
   535     ///
   536     /// Constructor with constant seeding.
   537     Random() { core.initState(); }
   538 
   539     /// \brief Constructor
   540     ///
   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);
   546     }
   547 
   548     /// \brief Constructor
   549     ///
   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);
   557     }
   558 
   559     /// \brief Copy constructor
   560     ///
   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
   564     /// sequence.
   565     Random(const Random& other) {
   566       core.copyState(other.core);
   567     }
   568 
   569     /// \brief Assign operator
   570     ///
   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
   574     /// sequence.
   575     Random& operator=(const Random& other) {
   576       if (&other != this) {
   577         core.copyState(other.core);
   578       }
   579       return *this;
   580     }
   581 
   582     /// \brief Seeding random sequence
   583     ///
   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);
   589     }
   590 
   591     /// \brief Seeding random sequence
   592     ///
   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);
   600     }
   601 
   602     /// \brief Returns a random real number from the range [0, 1)
   603     ///
   604     /// It returns a random real number from the range [0, 1). The
   605     /// default Number type is double.
   606     template <typename Number>
   607     Number real() {
   608       return _random_bits::RealConversion<Number, Word>::convert(core);
   609     }
   610 
   611     double real() {
   612       return real<double>();
   613     }
   614 
   615     /// \brief Returns a random real number the range [0, b)
   616     ///
   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; 
   621     }
   622 
   623     /// \brief Returns a random real number from the range [a, b)
   624     ///
   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; 
   629     }
   630 
   631     /// \brief Returns a random real number from the range [0, 1)
   632     ///
   633     /// It returns a random double from the range [0, 1).
   634     double operator()() {
   635       return real<double>();
   636     }
   637 
   638     /// \brief Returns a random real number from the range [0, b)
   639     ///
   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; 
   644     }
   645 
   646     /// \brief Returns a random real number from the range [a, b)
   647     ///
   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; 
   652     }
   653 
   654     /// \brief Returns a random integer from a range
   655     ///
   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);
   660     }
   661 
   662     /// \brief Returns a random integer from a range
   663     ///
   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;
   668     }
   669 
   670     /// \brief Returns a random integer from a range
   671     ///
   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);
   676     }
   677 
   678     /// \brief Returns a random non-negative integer
   679     ///
   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>
   684     Number uinteger() {
   685       return _random_bits::IntConversion<Number, Word>::convert(core);
   686     }
   687 
   688     unsigned int uinteger() {
   689       return uinteger<unsigned int>();
   690     }
   691 
   692     /// \brief Returns a random integer
   693     ///
   694     /// It returns a random integer uniformly from the whole range of
   695     /// the current \c Number type. The default result type of this
   696     /// function is int.
   697     template <typename Number>
   698     Number integer() {
   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);
   702     }
   703 
   704     int integer() {
   705       return integer<int>();
   706     }
   707     
   708     /// \brief Returns a random bool
   709     ///
   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.
   713     bool boolean() {
   714       return bool_producer.convert(core);
   715     }
   716 
   717     ///\name Nonuniform distributions
   718     ///
   719     
   720     ///@{
   721     
   722     /// \brief Returns a random bool
   723     ///
   724     /// It returns a random bool with given probability of true result
   725     bool boolean(double p) {
   726       return operator()() < p;
   727     }
   728 
   729     /// Standard Gauss distribution
   730 
   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.
   735     double gauss() 
   736     {
   737       double V1,V2,S;
   738       do {
   739 	V1=2*real<double>()-1;
   740 	V2=2*real<double>()-1;
   741 	S=V1*V1+V2*V2;
   742       } while(S>=1);
   743       return std::sqrt(-2*std::log(S)/S)*V1;
   744     }
   745     /// Gauss distribution with given standard deviation and mean 0
   746 
   747     /// \sa gauss()
   748     ///
   749     double gauss(double std_dev) 
   750     {
   751       return gauss()*std_dev;
   752     }
   753     /// Gauss distribution with given mean and standard deviation
   754 
   755     /// \sa gauss()
   756     ///
   757     double gauss(double mean,double std_dev)
   758     {
   759       return gauss()*std_dev+mean;
   760     }
   761 
   762     /// Exponential distribution with given mean
   763 
   764     /// This function generates an exponential distribution random number
   765     /// with mean <tt>1/lambda</tt>.
   766     ///
   767     double exponential(double lambda=1.0)
   768     {
   769       return -std::log(real<double>())/lambda;
   770     }
   771 
   772     double gamma(int k) 
   773     {
   774       double s = 0;
   775       for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
   776       return s;
   777     }
   778     
   779     /// Gamma distribution with given shape and scale parameter
   780 
   781     /// This function generates a gamma distribution random number.
   782     /// 
   783     ///\param k shape parameter (<tt>k>0</tt>)
   784     ///\param theta scale parameter
   785     ///
   786     double gamma(double k,double theta=1.0)
   787     {
   788       double xi,nu;
   789       const double delta = k-std::floor(k);
   790       const double v0=E/(E-delta);
   791       do {
   792 	double V0=1.0-real<double>();
   793 	double V1=1.0-real<double>();
   794 	double V2=1.0-real<double>();
   795 	if(V2<=v0) 
   796 	  {
   797 	    xi=std::pow(V1,1.0/delta);
   798 	    nu=V0*std::pow(xi,delta-1.0);
   799 	  }
   800 	else 
   801 	  {
   802 	    xi=1.0-std::log(V1);
   803 	    nu=V0*std::exp(-xi);
   804 	  }
   805       } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
   806       return theta*(xi+gamma(int(std::floor(k))));
   807     }
   808     
   809       
   810     ///@}
   811     
   812     ///\name Two dimensional distributions
   813     ///
   814 
   815     ///@{
   816     
   817     /// Uniform distribution on the full unit circle.
   818     dim2::Point<double> disc() 
   819     {
   820       double V1,V2;
   821       do {
   822 	V1=2*real<double>()-1;
   823 	V2=2*real<double>()-1;
   824 	
   825       } while(V1*V1+V2*V2>=1);
   826       return dim2::Point<double>(V1,V2);
   827     }
   828     /// A kind of two dimensional Gauss distribution
   829 
   830     /// This function provides a turning symmetric two-dimensional distribution.
   831     /// Both coordinates are of standard normal distribution, but they are not
   832     /// independent.
   833     ///
   834     /// \note The coordinates are the two random variables provided by
   835     /// the Box-Muller method.
   836     dim2::Point<double> gauss2()
   837     {
   838       double V1,V2,S;
   839       do {
   840 	V1=2*real<double>()-1;
   841 	V2=2*real<double>()-1;
   842 	S=V1*V1+V2*V2;
   843       } while(S>=1);
   844       double W=std::sqrt(-2*std::log(S)/S);
   845       return dim2::Point<double>(W*V1,W*V2);
   846     }
   847     /// A kind of two dimensional exponential distribution
   848 
   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
   853     /// y-coordinate.
   854     dim2::Point<double> exponential2() 
   855     {
   856       double V1,V2,S;
   857       do {
   858 	V1=2*real<double>()-1;
   859 	V2=2*real<double>()-1;
   860 	S=V1*V1+V2*V2;
   861       } while(S>=1);
   862       double W=-std::log(S)/S;
   863       return dim2::Point<double>(W*V1,W*V2);
   864     }
   865 
   866     ///@}    
   867   };
   868 
   869 
   870   extern Random rnd;
   871 
   872 }
   873 
   874 #endif