lemon/random.h
author Peter Kovacs <kpeter@inf.elte.hu>
Wed, 02 Jan 2008 03:55:00 +0100
changeset 14 8685efdef52f
parent 11 ea5945b2da9c
child 16 22696f89d183
permissions -rw-r--r--
Translated Hungarian varible names, improved messages.
alpar@10
     1
/* -*- C++ -*-
alpar@10
     2
 *
alpar@10
     3
 * This file is a part of LEMON, a generic C++ optimization library
alpar@10
     4
 *
alpar@10
     5
 * Copyright (C) 2003-2007
alpar@10
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@10
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@10
     8
 *
alpar@10
     9
 * Permission to use, modify and distribute this software is granted
alpar@10
    10
 * provided that this copyright notice appears in all copies. For
alpar@10
    11
 * precise terms see the accompanying LICENSE file.
alpar@10
    12
 *
alpar@10
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@10
    14
 * express or implied, and with no claim as to its suitability for any
alpar@10
    15
 * purpose.
alpar@10
    16
 *
alpar@10
    17
 */
alpar@10
    18
alpar@10
    19
/*
alpar@10
    20
 * This file contains the reimplemented version of the Mersenne Twister
alpar@10
    21
 * Generator of Matsumoto and Nishimura.
alpar@10
    22
 *
alpar@10
    23
 * See the appropriate copyright notice below.
alpar@10
    24
 * 
alpar@10
    25
 * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
alpar@10
    26
 * All rights reserved.                          
alpar@10
    27
 *
alpar@10
    28
 * Redistribution and use in source and binary forms, with or without
alpar@10
    29
 * modification, are permitted provided that the following conditions
alpar@10
    30
 * are met:
alpar@10
    31
 *
alpar@10
    32
 * 1. Redistributions of source code must retain the above copyright
alpar@10
    33
 *    notice, this list of conditions and the following disclaimer.
alpar@10
    34
 *
alpar@10
    35
 * 2. Redistributions in binary form must reproduce the above copyright
alpar@10
    36
 *    notice, this list of conditions and the following disclaimer in the
alpar@10
    37
 *    documentation and/or other materials provided with the distribution.
alpar@10
    38
 *
alpar@10
    39
 * 3. The names of its contributors may not be used to endorse or promote 
alpar@10
    40
 *    products derived from this software without specific prior written 
alpar@10
    41
 *    permission.
alpar@10
    42
 *
alpar@10
    43
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
alpar@10
    44
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
alpar@10
    45
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
alpar@10
    46
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
alpar@10
    47
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
alpar@10
    48
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
alpar@10
    49
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
alpar@10
    50
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
alpar@10
    51
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
alpar@10
    52
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
alpar@10
    53
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
alpar@10
    54
 * OF THE POSSIBILITY OF SUCH DAMAGE.
alpar@10
    55
 *
alpar@10
    56
 *
alpar@10
    57
 * Any feedback is very welcome.
alpar@10
    58
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
alpar@10
    59
 * email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
alpar@10
    60
 */
alpar@10
    61
alpar@10
    62
#ifndef LEMON_RANDOM_H
alpar@10
    63
#define LEMON_RANDOM_H
alpar@10
    64
alpar@10
    65
#include <algorithm>
alpar@10
    66
#include <iterator>
alpar@10
    67
#include <vector>
alpar@10
    68
alpar@10
    69
#include <ctime>
alpar@10
    70
#include <cmath>
alpar@10
    71
alpar@10
    72
#include <lemon/dim2.h>
alpar@10
    73
///\ingroup misc
alpar@10
    74
///\file
alpar@10
    75
///\brief Mersenne Twister random number generator
alpar@10
    76
///
alpar@10
    77
///\author Balazs Dezso
alpar@10
    78
alpar@10
    79
namespace lemon {
alpar@10
    80
alpar@10
    81
  namespace _random_bits {
alpar@10
    82
    
alpar@10
    83
    template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
alpar@10
    84
    struct RandomTraits {};
alpar@10
    85
alpar@10
    86
    template <typename _Word>
alpar@10
    87
    struct RandomTraits<_Word, 32> {
alpar@10
    88
alpar@10
    89
      typedef _Word Word;
alpar@10
    90
      static const int bits = 32;
alpar@10
    91
alpar@10
    92
      static const int length = 624;
alpar@10
    93
      static const int shift = 397;
alpar@10
    94
      
alpar@10
    95
      static const Word mul = 0x6c078965u;
alpar@10
    96
      static const Word arrayInit = 0x012BD6AAu;
alpar@10
    97
      static const Word arrayMul1 = 0x0019660Du;
alpar@10
    98
      static const Word arrayMul2 = 0x5D588B65u;
alpar@10
    99
alpar@10
   100
      static const Word mask = 0x9908B0DFu;
alpar@10
   101
      static const Word loMask = (1u << 31) - 1;
alpar@10
   102
      static const Word hiMask = ~loMask;
alpar@10
   103
alpar@10
   104
alpar@10
   105
      static Word tempering(Word rnd) {
alpar@10
   106
        rnd ^= (rnd >> 11);
alpar@10
   107
        rnd ^= (rnd << 7) & 0x9D2C5680u;
alpar@10
   108
        rnd ^= (rnd << 15) & 0xEFC60000u;
alpar@10
   109
        rnd ^= (rnd >> 18);
alpar@10
   110
        return rnd;
alpar@10
   111
      }
alpar@10
   112
alpar@10
   113
    };
alpar@10
   114
alpar@10
   115
    template <typename _Word>
alpar@10
   116
    struct RandomTraits<_Word, 64> {
alpar@10
   117
alpar@10
   118
      typedef _Word Word;
alpar@10
   119
      static const int bits = 64;
alpar@10
   120
alpar@10
   121
      static const int length = 312;
alpar@10
   122
      static const int shift = 156;
alpar@10
   123
alpar@10
   124
      static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
alpar@10
   125
      static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
alpar@10
   126
      static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
alpar@10
   127
      static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
alpar@10
   128
alpar@10
   129
      static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
alpar@10
   130
      static const Word loMask = (Word(1u) << 31) - 1;
alpar@10
   131
      static const Word hiMask = ~loMask;
alpar@10
   132
alpar@10
   133
      static Word tempering(Word rnd) {
alpar@10
   134
        rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
alpar@10
   135
        rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
alpar@10
   136
        rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u));
alpar@10
   137
        rnd ^= (rnd >> 43);
alpar@10
   138
        return rnd;
alpar@10
   139
      }
alpar@10
   140
alpar@10
   141
    };
alpar@10
   142
alpar@10
   143
    template <typename _Word>
alpar@10
   144
    class RandomCore {
alpar@10
   145
    public:
alpar@10
   146
alpar@10
   147
      typedef _Word Word;
alpar@10
   148
alpar@10
   149
    private:
alpar@10
   150
alpar@10
   151
      static const int bits = RandomTraits<Word>::bits;
alpar@10
   152
alpar@10
   153
      static const int length = RandomTraits<Word>::length;
alpar@10
   154
      static const int shift = RandomTraits<Word>::shift;
alpar@10
   155
alpar@10
   156
    public:
alpar@10
   157
alpar@10
   158
      void initState() {
alpar@10
   159
        static const Word seedArray[4] = {
alpar@10
   160
          0x12345u, 0x23456u, 0x34567u, 0x45678u
alpar@10
   161
        };
alpar@10
   162
    
alpar@10
   163
        initState(seedArray, seedArray + 4);
alpar@10
   164
      }
alpar@10
   165
alpar@10
   166
      void initState(Word seed) {
alpar@10
   167
alpar@10
   168
        static const Word mul = RandomTraits<Word>::mul;
alpar@10
   169
alpar@10
   170
        current = state; 
alpar@10
   171
alpar@10
   172
        Word *curr = state + length - 1;
alpar@10
   173
        curr[0] = seed; --curr;
alpar@10
   174
        for (int i = 1; i < length; ++i) {
alpar@10
   175
          curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
alpar@10
   176
          --curr;
alpar@10
   177
        }
alpar@10
   178
      }
alpar@10
   179
alpar@10
   180
      template <typename Iterator>
alpar@10
   181
      void initState(Iterator begin, Iterator end) {
alpar@10
   182
alpar@10
   183
        static const Word init = RandomTraits<Word>::arrayInit;
alpar@10
   184
        static const Word mul1 = RandomTraits<Word>::arrayMul1;
alpar@10
   185
        static const Word mul2 = RandomTraits<Word>::arrayMul2;
alpar@10
   186
alpar@10
   187
alpar@10
   188
        Word *curr = state + length - 1; --curr;
alpar@10
   189
        Iterator it = begin; int cnt = 0;
alpar@10
   190
        int num;
alpar@10
   191
alpar@10
   192
        initState(init);
alpar@10
   193
alpar@10
   194
        num = length > end - begin ? length : end - begin;
alpar@10
   195
        while (num--) {
alpar@10
   196
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 
alpar@10
   197
            + *it + cnt;
alpar@10
   198
          ++it; ++cnt;
alpar@10
   199
          if (it == end) {
alpar@10
   200
            it = begin; cnt = 0;
alpar@10
   201
          }
alpar@10
   202
          if (curr == state) {
alpar@10
   203
            curr = state + length - 1; curr[0] = state[0];
alpar@10
   204
          }
alpar@10
   205
          --curr;
alpar@10
   206
        }
alpar@10
   207
alpar@10
   208
        num = length - 1; cnt = length - (curr - state) - 1;
alpar@10
   209
        while (num--) {
alpar@10
   210
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
alpar@10
   211
            - cnt;
alpar@10
   212
          --curr; ++cnt;
alpar@10
   213
          if (curr == state) {
alpar@10
   214
            curr = state + length - 1; curr[0] = state[0]; --curr;
alpar@10
   215
            cnt = 1;
alpar@10
   216
          }
alpar@10
   217
        }
alpar@10
   218
        
alpar@10
   219
        state[length - 1] = Word(1) << (bits - 1);
alpar@10
   220
      }
alpar@10
   221
      
alpar@10
   222
      void copyState(const RandomCore& other) {
alpar@10
   223
        std::copy(other.state, other.state + length, state);
alpar@10
   224
        current = state + (other.current - other.state);
alpar@10
   225
      }
alpar@10
   226
alpar@10
   227
      Word operator()() {
alpar@10
   228
        if (current == state) fillState();
alpar@10
   229
        --current;
alpar@10
   230
        Word rnd = *current;
alpar@10
   231
        return RandomTraits<Word>::tempering(rnd);
alpar@10
   232
      }
alpar@10
   233
alpar@10
   234
    private:
alpar@10
   235
alpar@10
   236
  
alpar@10
   237
      void fillState() {
alpar@10
   238
        static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
alpar@10
   239
        static const Word loMask = RandomTraits<Word>::loMask;
alpar@10
   240
        static const Word hiMask = RandomTraits<Word>::hiMask;
alpar@10
   241
alpar@10
   242
        current = state + length; 
alpar@10
   243
alpar@10
   244
        register Word *curr = state + length - 1;
alpar@10
   245
        register long num;
alpar@10
   246
      
alpar@10
   247
        num = length - shift;
alpar@10
   248
        while (num--) {
alpar@10
   249
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
alpar@10
   250
            curr[- shift] ^ mask[curr[-1] & 1ul];
alpar@10
   251
          --curr;
alpar@10
   252
        }
alpar@10
   253
        num = shift - 1;
alpar@10
   254
        while (num--) {
alpar@10
   255
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
alpar@10
   256
            curr[length - shift] ^ mask[curr[-1] & 1ul];
alpar@10
   257
          --curr;
alpar@10
   258
        }
alpar@10
   259
        curr[0] = (((curr[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
alpar@10
   260
          curr[length - shift] ^ mask[curr[length - 1] & 1ul];
alpar@10
   261
alpar@10
   262
      }
alpar@10
   263
alpar@10
   264
  
alpar@10
   265
      Word *current;
alpar@10
   266
      Word state[length];
alpar@10
   267
      
alpar@10
   268
    };
alpar@10
   269
alpar@10
   270
alpar@10
   271
    template <typename Result, 
alpar@10
   272
              int shift = (std::numeric_limits<Result>::digits + 1) / 2>
alpar@10
   273
    struct Masker {
alpar@10
   274
      static Result mask(const Result& result) {
alpar@10
   275
        return Masker<Result, (shift + 1) / 2>::
alpar@10
   276
          mask(static_cast<Result>(result | (result >> shift)));
alpar@10
   277
      }
alpar@10
   278
    };
alpar@10
   279
    
alpar@10
   280
    template <typename Result>
alpar@10
   281
    struct Masker<Result, 1> {
alpar@10
   282
      static Result mask(const Result& result) {
alpar@10
   283
        return static_cast<Result>(result | (result >> 1));
alpar@10
   284
      }
alpar@10
   285
    };
alpar@10
   286
alpar@10
   287
    template <typename Result, typename Word, 
alpar@10
   288
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
alpar@10
   289
              bool last = rest <= std::numeric_limits<Word>::digits>
alpar@10
   290
    struct IntConversion {
alpar@10
   291
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   292
    
alpar@10
   293
      static Result convert(RandomCore<Word>& rnd) {
alpar@10
   294
        return static_cast<Result>(rnd() >> (bits - rest)) << shift;
alpar@10
   295
      }
alpar@10
   296
      
alpar@10
   297
    }; 
alpar@10
   298
alpar@10
   299
    template <typename Result, typename Word, int rest, int shift> 
alpar@10
   300
    struct IntConversion<Result, Word, rest, shift, false> {
alpar@10
   301
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   302
alpar@10
   303
      static Result convert(RandomCore<Word>& rnd) {
alpar@10
   304
        return (static_cast<Result>(rnd()) << shift) | 
alpar@10
   305
          IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
alpar@10
   306
      }
alpar@10
   307
    };
alpar@10
   308
alpar@10
   309
alpar@10
   310
    template <typename Result, typename Word,
alpar@10
   311
              bool one_word = (std::numeric_limits<Word>::digits < 
alpar@10
   312
			       std::numeric_limits<Result>::digits) >
alpar@10
   313
    struct Mapping {
alpar@10
   314
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
alpar@10
   315
        Word max = Word(bound - 1);
alpar@10
   316
        Result mask = Masker<Result>::mask(bound - 1);
alpar@10
   317
        Result num;
alpar@10
   318
        do {
alpar@10
   319
          num = IntConversion<Result, Word>::convert(rnd) & mask; 
alpar@10
   320
        } while (num > max);
alpar@10
   321
        return num;
alpar@10
   322
      }
alpar@10
   323
    };
alpar@10
   324
alpar@10
   325
    template <typename Result, typename Word>
alpar@10
   326
    struct Mapping<Result, Word, false> {
alpar@10
   327
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
alpar@10
   328
        Word max = Word(bound - 1);
alpar@10
   329
        Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
alpar@10
   330
          ::mask(max);
alpar@10
   331
        Word num;
alpar@10
   332
        do {
alpar@10
   333
          num = rnd() & mask;
alpar@10
   334
        } while (num > max);
alpar@10
   335
        return num;
alpar@10
   336
      }
alpar@10
   337
    };
alpar@10
   338
alpar@10
   339
    template <typename Result, int exp, bool pos = (exp >= 0)>
alpar@10
   340
    struct ShiftMultiplier {
alpar@10
   341
      static const Result multiplier() {
alpar@10
   342
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
alpar@10
   343
        res *= res;
alpar@10
   344
        if ((exp & 1) == 1) res *= static_cast<Result>(2.0);
alpar@10
   345
        return res; 
alpar@10
   346
      }
alpar@10
   347
    };
alpar@10
   348
alpar@10
   349
    template <typename Result, int exp>
alpar@10
   350
    struct ShiftMultiplier<Result, exp, false> {
alpar@10
   351
      static const Result multiplier() {
alpar@10
   352
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
alpar@10
   353
        res *= res;
alpar@10
   354
        if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
alpar@10
   355
        return res; 
alpar@10
   356
      }
alpar@10
   357
    };
alpar@10
   358
alpar@10
   359
    template <typename Result>
alpar@10
   360
    struct ShiftMultiplier<Result, 0, true> {
alpar@10
   361
      static const Result multiplier() {
alpar@10
   362
        return static_cast<Result>(1.0); 
alpar@10
   363
      }
alpar@10
   364
    };
alpar@10
   365
alpar@10
   366
    template <typename Result>
alpar@10
   367
    struct ShiftMultiplier<Result, -20, true> {
alpar@10
   368
      static const Result multiplier() {
alpar@10
   369
        return static_cast<Result>(1.0/1048576.0); 
alpar@10
   370
      }
alpar@10
   371
    };
alpar@10
   372
    
alpar@10
   373
    template <typename Result>
alpar@10
   374
    struct ShiftMultiplier<Result, -32, true> {
alpar@10
   375
      static const Result multiplier() {
alpar@10
   376
        return static_cast<Result>(1.0/424967296.0); 
alpar@10
   377
      }
alpar@10
   378
    };
alpar@10
   379
alpar@10
   380
    template <typename Result>
alpar@10
   381
    struct ShiftMultiplier<Result, -53, true> {
alpar@10
   382
      static const Result multiplier() {
alpar@10
   383
        return static_cast<Result>(1.0/9007199254740992.0); 
alpar@10
   384
      }
alpar@10
   385
    };
alpar@10
   386
alpar@10
   387
    template <typename Result>
alpar@10
   388
    struct ShiftMultiplier<Result, -64, true> {
alpar@10
   389
      static const Result multiplier() {
alpar@10
   390
        return static_cast<Result>(1.0/18446744073709551616.0); 
alpar@10
   391
      }
alpar@10
   392
    };
alpar@10
   393
alpar@10
   394
    template <typename Result, int exp>
alpar@10
   395
    struct Shifting {
alpar@10
   396
      static Result shift(const Result& result) {
alpar@10
   397
        return result * ShiftMultiplier<Result, exp>::multiplier();
alpar@10
   398
      }
alpar@10
   399
    };
alpar@10
   400
alpar@10
   401
    template <typename Result, typename Word,
alpar@10
   402
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
alpar@10
   403
              bool last = rest <= std::numeric_limits<Word>::digits>
alpar@10
   404
    struct RealConversion{ 
alpar@10
   405
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   406
alpar@10
   407
      static Result convert(RandomCore<Word>& rnd) {
alpar@10
   408
        return Shifting<Result, - shift - rest>::
alpar@10
   409
          shift(static_cast<Result>(rnd() >> (bits - rest)));
alpar@10
   410
      }
alpar@10
   411
    };
alpar@10
   412
alpar@10
   413
    template <typename Result, typename Word, int rest, int shift>
alpar@10
   414
    struct RealConversion<Result, Word, rest, shift, false> { 
alpar@10
   415
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   416
alpar@10
   417
      static Result convert(RandomCore<Word>& rnd) {
alpar@10
   418
        return Shifting<Result, - shift - bits>::
alpar@10
   419
          shift(static_cast<Result>(rnd())) +
alpar@10
   420
          RealConversion<Result, Word, rest-bits, shift + bits>::
alpar@10
   421
          convert(rnd);
alpar@10
   422
      }
alpar@10
   423
    };
alpar@10
   424
alpar@10
   425
    template <typename Result, typename Word>
alpar@10
   426
    struct Initializer {
alpar@10
   427
alpar@10
   428
      template <typename Iterator>
alpar@10
   429
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
alpar@10
   430
        std::vector<Word> ws;
alpar@10
   431
        for (Iterator it = begin; it != end; ++it) {
alpar@10
   432
          ws.push_back(Word(*it));
alpar@10
   433
        }
alpar@10
   434
        rnd.initState(ws.begin(), ws.end());
alpar@10
   435
      }
alpar@10
   436
alpar@10
   437
      static void init(RandomCore<Word>& rnd, Result seed) {
alpar@10
   438
        rnd.initState(seed);
alpar@10
   439
      }
alpar@10
   440
    };
alpar@10
   441
alpar@10
   442
    template <typename Word>
alpar@10
   443
    struct BoolConversion {
alpar@10
   444
      static bool convert(RandomCore<Word>& rnd) {
alpar@10
   445
        return (rnd() & 1) == 1;
alpar@10
   446
      }
alpar@10
   447
    };
alpar@10
   448
alpar@10
   449
    template <typename Word>
alpar@10
   450
    struct BoolProducer {
alpar@10
   451
      Word buffer;
alpar@10
   452
      int num;
alpar@10
   453
      
alpar@10
   454
      BoolProducer() : num(0) {}
alpar@10
   455
alpar@10
   456
      bool convert(RandomCore<Word>& rnd) {
alpar@10
   457
        if (num == 0) {
alpar@10
   458
          buffer = rnd();
alpar@10
   459
          num = RandomTraits<Word>::bits;
alpar@10
   460
        }
alpar@10
   461
        bool r = (buffer & 1);
alpar@10
   462
        buffer >>= 1;
alpar@10
   463
        --num;
alpar@10
   464
        return r;
alpar@10
   465
      }
alpar@10
   466
    };
alpar@10
   467
alpar@10
   468
  }
alpar@10
   469
alpar@10
   470
  /// \ingroup misc
alpar@10
   471
  ///
alpar@10
   472
  /// \brief Mersenne Twister random number generator
alpar@10
   473
  ///
alpar@10
   474
  /// The Mersenne Twister is a twisted generalized feedback
alpar@10
   475
  /// shift-register generator of Matsumoto and Nishimura. The period
alpar@10
   476
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
alpar@10
   477
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
alpar@10
   478
  /// performance of this generator is comparable to the commonly used
alpar@10
   479
  /// generators.
alpar@10
   480
  ///
alpar@10
   481
  /// This implementation is specialized for both 32-bit and 64-bit
alpar@10
   482
  /// architectures. The generators differ sligthly in the
alpar@10
   483
  /// initialization and generation phase so they produce two
alpar@10
   484
  /// completly different sequences.
alpar@10
   485
  ///
alpar@10
   486
  /// The generator gives back random numbers of serveral types. To
alpar@10
   487
  /// get a random number from a range of a floating point type you
alpar@10
   488
  /// can use one form of the \c operator() or the \c real() member
alpar@10
   489
  /// function. If you want to get random number from the {0, 1, ...,
alpar@10
   490
  /// n-1} integer range use the \c operator[] or the \c integer()
alpar@10
   491
  /// method. And to get random number from the whole range of an
alpar@10
   492
  /// integer type you can use the argumentless \c integer() or \c
alpar@10
   493
  /// uinteger() functions. After all you can get random bool with
alpar@10
   494
  /// equal chance of true and false or given probability of true
alpar@10
   495
  /// result with the \c boolean() member functions.
alpar@10
   496
  ///
alpar@10
   497
  ///\code
alpar@10
   498
  /// // The commented code is identical to the other
alpar@10
   499
  /// double a = rnd();                     // [0.0, 1.0)
alpar@10
   500
  /// // double a = rnd.real();             // [0.0, 1.0)
alpar@10
   501
  /// double b = rnd(100.0);                // [0.0, 100.0)
alpar@10
   502
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
alpar@10
   503
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
alpar@10
   504
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
alpar@10
   505
  /// int d = rnd[100000];                  // 0..99999
alpar@10
   506
  /// // int d = rnd.integer(100000);       // 0..99999
alpar@10
   507
  /// int e = rnd[6] + 1;                   // 1..6
alpar@10
   508
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
alpar@10
   509
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
alpar@10
   510
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
alpar@10
   511
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
alpar@10
   512
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
alpar@10
   513
  ///\endcode
alpar@10
   514
  ///
alpar@10
   515
  /// The lemon provides a global instance of the random number
alpar@10
   516
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
alpar@10
   517
  /// good programming convenience to use this global generator to get
alpar@10
   518
  /// random numbers.
alpar@10
   519
  ///
alpar@10
   520
  /// \author Balazs Dezso
alpar@10
   521
  class Random {
alpar@10
   522
  private:
alpar@10
   523
alpar@10
   524
    // architecture word
alpar@10
   525
    typedef unsigned long Word;
alpar@10
   526
    
alpar@10
   527
    _random_bits::RandomCore<Word> core;
alpar@10
   528
    _random_bits::BoolProducer<Word> bool_producer;
alpar@10
   529
    
alpar@10
   530
alpar@10
   531
  public:
alpar@10
   532
alpar@10
   533
    /// \brief Constructor
alpar@10
   534
    ///
alpar@10
   535
    /// Constructor with constant seeding.
alpar@10
   536
    Random() { core.initState(); }
alpar@10
   537
alpar@10
   538
    /// \brief Constructor
alpar@10
   539
    ///
alpar@10
   540
    /// Constructor with seed. The current number type will be converted
alpar@10
   541
    /// to the architecture word type.
alpar@10
   542
    template <typename Number>
alpar@10
   543
    Random(Number seed) { 
alpar@10
   544
      _random_bits::Initializer<Number, Word>::init(core, seed);
alpar@10
   545
    }
alpar@10
   546
alpar@10
   547
    /// \brief Constructor
alpar@10
   548
    ///
alpar@10
   549
    /// Constructor with array seeding. The given range should contain
alpar@10
   550
    /// any number type and the numbers will be converted to the
alpar@10
   551
    /// architecture word type.
alpar@10
   552
    template <typename Iterator>
alpar@10
   553
    Random(Iterator begin, Iterator end) { 
alpar@10
   554
      typedef typename std::iterator_traits<Iterator>::value_type Number;
alpar@10
   555
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
alpar@10
   556
    }
alpar@10
   557
alpar@10
   558
    /// \brief Copy constructor
alpar@10
   559
    ///
alpar@10
   560
    /// Copy constructor. The generated sequence will be identical to
alpar@10
   561
    /// the other sequence. It can be used to save the current state
alpar@10
   562
    /// of the generator and later use it to generate the same
alpar@10
   563
    /// sequence.
alpar@10
   564
    Random(const Random& other) {
alpar@10
   565
      core.copyState(other.core);
alpar@10
   566
    }
alpar@10
   567
alpar@10
   568
    /// \brief Assign operator
alpar@10
   569
    ///
alpar@10
   570
    /// Assign operator. The generated sequence will be identical to
alpar@10
   571
    /// the other sequence. It can be used to save the current state
alpar@10
   572
    /// of the generator and later use it to generate the same
alpar@10
   573
    /// sequence.
alpar@10
   574
    Random& operator=(const Random& other) {
alpar@10
   575
      if (&other != this) {
alpar@10
   576
        core.copyState(other.core);
alpar@10
   577
      }
alpar@10
   578
      return *this;
alpar@10
   579
    }
alpar@10
   580
alpar@10
   581
    /// \brief Returns a random real number from the range [0, 1)
alpar@10
   582
    ///
alpar@10
   583
    /// It returns a random real number from the range [0, 1). The
alpar@10
   584
    /// default Number type is double.
alpar@10
   585
    template <typename Number>
alpar@10
   586
    Number real() {
alpar@10
   587
      return _random_bits::RealConversion<Number, Word>::convert(core);
alpar@10
   588
    }
alpar@10
   589
alpar@10
   590
    double real() {
alpar@10
   591
      return real<double>();
alpar@10
   592
    }
alpar@10
   593
alpar@10
   594
    /// \brief Returns a random real number the range [0, b)
alpar@10
   595
    ///
alpar@10
   596
    /// It returns a random real number from the range [0, b).
alpar@10
   597
    template <typename Number>
alpar@10
   598
    Number real(Number b) { 
alpar@10
   599
      return real<Number>() * b; 
alpar@10
   600
    }
alpar@10
   601
alpar@10
   602
    /// \brief Returns a random real number from the range [a, b)
alpar@10
   603
    ///
alpar@10
   604
    /// It returns a random real number from the range [a, b).
alpar@10
   605
    template <typename Number>
alpar@10
   606
    Number real(Number a, Number b) { 
alpar@10
   607
      return real<Number>() * (b - a) + a; 
alpar@10
   608
    }
alpar@10
   609
alpar@10
   610
    /// \brief Returns a random real number from the range [0, 1)
alpar@10
   611
    ///
alpar@10
   612
    /// It returns a random double from the range [0, 1).
alpar@10
   613
    double operator()() {
alpar@10
   614
      return real<double>();
alpar@10
   615
    }
alpar@10
   616
alpar@10
   617
    /// \brief Returns a random real number from the range [0, b)
alpar@10
   618
    ///
alpar@10
   619
    /// It returns a random real number from the range [0, b).
alpar@10
   620
    template <typename Number>
alpar@10
   621
    Number operator()(Number b) { 
alpar@10
   622
      return real<Number>() * b; 
alpar@10
   623
    }
alpar@10
   624
alpar@10
   625
    /// \brief Returns a random real number from the range [a, b)
alpar@10
   626
    ///
alpar@10
   627
    /// It returns a random real number from the range [a, b).
alpar@10
   628
    template <typename Number>
alpar@10
   629
    Number operator()(Number a, Number b) { 
alpar@10
   630
      return real<Number>() * (b - a) + a; 
alpar@10
   631
    }
alpar@10
   632
alpar@10
   633
    /// \brief Returns a random integer from a range
alpar@10
   634
    ///
alpar@10
   635
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
alpar@10
   636
    template <typename Number>
alpar@10
   637
    Number integer(Number b) {
alpar@10
   638
      return _random_bits::Mapping<Number, Word>::map(core, b);
alpar@10
   639
    }
alpar@10
   640
alpar@10
   641
    /// \brief Returns a random integer from a range
alpar@10
   642
    ///
alpar@10
   643
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
alpar@10
   644
    template <typename Number>
alpar@10
   645
    Number integer(Number a, Number b) {
alpar@10
   646
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
alpar@10
   647
    }
alpar@10
   648
alpar@10
   649
    /// \brief Returns a random integer from a range
alpar@10
   650
    ///
alpar@10
   651
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
alpar@10
   652
    template <typename Number>
alpar@10
   653
    Number operator[](Number b) {
alpar@10
   654
      return _random_bits::Mapping<Number, Word>::map(core, b);
alpar@10
   655
    }
alpar@10
   656
alpar@10
   657
    /// \brief Returns a random non-negative integer
alpar@10
   658
    ///
alpar@10
   659
    /// It returns a random non-negative integer uniformly from the
alpar@10
   660
    /// whole range of the current \c Number type.  The default result
alpar@10
   661
    /// type of this function is unsigned int.
alpar@10
   662
    template <typename Number>
alpar@10
   663
    Number uinteger() {
alpar@10
   664
      return _random_bits::IntConversion<Number, Word>::convert(core);
alpar@10
   665
    }
alpar@10
   666
alpar@10
   667
    unsigned int uinteger() {
alpar@10
   668
      return uinteger<unsigned int>();
alpar@10
   669
    }
alpar@10
   670
alpar@10
   671
    /// \brief Returns a random integer
alpar@10
   672
    ///
alpar@10
   673
    /// It returns a random integer uniformly from the whole range of
alpar@10
   674
    /// the current \c Number type. The default result type of this
alpar@10
   675
    /// function is int.
alpar@10
   676
    template <typename Number>
alpar@10
   677
    Number integer() {
alpar@10
   678
      static const int nb = std::numeric_limits<Number>::digits + 
alpar@10
   679
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
alpar@10
   680
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
alpar@10
   681
    }
alpar@10
   682
alpar@10
   683
    int integer() {
alpar@10
   684
      return integer<int>();
alpar@10
   685
    }
alpar@10
   686
    
alpar@10
   687
    /// \brief Returns a random bool
alpar@10
   688
    ///
alpar@10
   689
    /// It returns a random bool. The generator holds a buffer for
alpar@10
   690
    /// random bits. Every time when it become empty the generator makes
alpar@10
   691
    /// a new random word and fill the buffer up.
alpar@10
   692
    bool boolean() {
alpar@10
   693
      return bool_producer.convert(core);
alpar@10
   694
    }
alpar@10
   695
alpar@10
   696
    ///\name Nonuniform distributions
alpar@10
   697
    ///
alpar@10
   698
    
alpar@10
   699
    ///@{
alpar@10
   700
    
alpar@10
   701
    /// \brief Returns a random bool
alpar@10
   702
    ///
alpar@10
   703
    /// It returns a random bool with given probability of true result
alpar@10
   704
    bool boolean(double p) {
alpar@10
   705
      return operator()() < p;
alpar@10
   706
    }
alpar@10
   707
alpar@10
   708
    /// Standard Gauss distribution
alpar@10
   709
alpar@10
   710
    /// Standard Gauss distribution.
alpar@10
   711
    /// \note The Cartesian form of the Box-Muller
alpar@10
   712
    /// transformation is used to generate a random normal distribution.
alpar@10
   713
    /// \todo Consider using the "ziggurat" method instead.
alpar@10
   714
    double gauss() 
alpar@10
   715
    {
alpar@10
   716
      double V1,V2,S;
alpar@10
   717
      do {
alpar@10
   718
	V1=2*real<double>()-1;
alpar@10
   719
	V2=2*real<double>()-1;
alpar@10
   720
	S=V1*V1+V2*V2;
alpar@10
   721
      } while(S>=1);
alpar@10
   722
      return std::sqrt(-2*std::log(S)/S)*V1;
alpar@10
   723
    }
alpar@10
   724
    /// Gauss distribution with given mean and standard deviation
alpar@10
   725
alpar@10
   726
    /// \sa gauss()
alpar@10
   727
    ///
alpar@10
   728
    double gauss(double mean,double std_dev)
alpar@10
   729
    {
alpar@10
   730
      return gauss()*std_dev+mean;
alpar@10
   731
    }
alpar@10
   732
alpar@10
   733
    /// Exponential distribution with given mean
alpar@10
   734
alpar@10
   735
    /// This function generates an exponential distribution random number
alpar@10
   736
    /// with mean <tt>1/lambda</tt>.
alpar@10
   737
    ///
alpar@10
   738
    double exponential(double lambda=1.0)
alpar@10
   739
    {
alpar@11
   740
      return -std::log(1.0-real<double>())/lambda;
alpar@10
   741
    }
alpar@10
   742
alpar@10
   743
    /// Gamma distribution with given integer shape
alpar@10
   744
alpar@10
   745
    /// This function generates a gamma distribution random number.
alpar@10
   746
    /// 
alpar@10
   747
    ///\param k shape parameter (<tt>k>0</tt> integer)
alpar@10
   748
    double gamma(int k) 
alpar@10
   749
    {
alpar@10
   750
      double s = 0;
alpar@10
   751
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
alpar@10
   752
      return s;
alpar@10
   753
    }
alpar@10
   754
    
alpar@10
   755
    /// Gamma distribution with given shape and scale parameter
alpar@10
   756
alpar@10
   757
    /// This function generates a gamma distribution random number.
alpar@10
   758
    /// 
alpar@10
   759
    ///\param k shape parameter (<tt>k>0</tt>)
alpar@10
   760
    ///\param theta scale parameter
alpar@10
   761
    ///
alpar@10
   762
    double gamma(double k,double theta=1.0)
alpar@10
   763
    {
alpar@10
   764
      double xi,nu;
alpar@10
   765
      const double delta = k-std::floor(k);
alpar@10
   766
      const double v0=M_E/(M_E-delta);
alpar@10
   767
      do {
alpar@10
   768
	double V0=1.0-real<double>();
alpar@10
   769
	double V1=1.0-real<double>();
alpar@10
   770
	double V2=1.0-real<double>();
alpar@10
   771
	if(V2<=v0) 
alpar@10
   772
	  {
alpar@10
   773
	    xi=std::pow(V1,1.0/delta);
alpar@10
   774
	    nu=V0*std::pow(xi,delta-1.0);
alpar@10
   775
	  }
alpar@10
   776
	else 
alpar@10
   777
	  {
alpar@10
   778
	    xi=1.0-std::log(V1);
alpar@10
   779
	    nu=V0*std::exp(-xi);
alpar@10
   780
	  }
alpar@10
   781
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
alpar@10
   782
      return theta*(xi-gamma(int(std::floor(k))));
alpar@10
   783
    }
alpar@10
   784
    
alpar@11
   785
    /// Weibull distribution
alpar@11
   786
alpar@11
   787
    /// This function generates a Weibull distribution random number.
alpar@11
   788
    /// 
alpar@11
   789
    ///\param k shape parameter (<tt>k>0</tt>)
alpar@11
   790
    ///\param lambda scale parameter (<tt>lambda>0</tt>)
alpar@11
   791
    ///
alpar@11
   792
    double weibull(double k,double lambda)
alpar@11
   793
    {
alpar@11
   794
      return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
alpar@11
   795
    }  
alpar@11
   796
      
alpar@11
   797
    /// Pareto distribution
alpar@11
   798
alpar@11
   799
    /// This function generates a Pareto distribution random number.
alpar@11
   800
    /// 
alpar@12
   801
    ///\param k shape parameter (<tt>k>0</tt>)
alpar@11
   802
    ///\param x_min location parameter (<tt>x_min>0</tt>)
alpar@11
   803
    ///
alpar@12
   804
    double pareto(double k,double x_min)
alpar@11
   805
    {
alpar@12
   806
      return exponential(gamma(k,1.0/x_min));
alpar@11
   807
    }  
alpar@10
   808
      
alpar@10
   809
    ///@}
alpar@10
   810
    
alpar@10
   811
    ///\name Two dimensional distributions
alpar@10
   812
    ///
alpar@10
   813
alpar@10
   814
    ///@{
alpar@10
   815
    
alpar@10
   816
    /// Uniform distribution on the full unit circle.
alpar@10
   817
    dim2::Point<double> disc() 
alpar@10
   818
    {
alpar@10
   819
      double V1,V2;
alpar@10
   820
      do {
alpar@10
   821
	V1=2*real<double>()-1;
alpar@10
   822
	V2=2*real<double>()-1;
alpar@10
   823
	
alpar@10
   824
      } while(V1*V1+V2*V2>=1);
alpar@10
   825
      return dim2::Point<double>(V1,V2);
alpar@10
   826
    }
alpar@10
   827
    /// A kind of two dimensional Gauss distribution
alpar@10
   828
alpar@10
   829
    /// This function provides a turning symmetric two-dimensional distribution.
alpar@10
   830
    /// Both coordinates are of standard normal distribution, but they are not
alpar@10
   831
    /// independent.
alpar@10
   832
    ///
alpar@10
   833
    /// \note The coordinates are the two random variables provided by
alpar@10
   834
    /// the Box-Muller method.
alpar@10
   835
    dim2::Point<double> gauss2()
alpar@10
   836
    {
alpar@10
   837
      double V1,V2,S;
alpar@10
   838
      do {
alpar@10
   839
	V1=2*real<double>()-1;
alpar@10
   840
	V2=2*real<double>()-1;
alpar@10
   841
	S=V1*V1+V2*V2;
alpar@10
   842
      } while(S>=1);
alpar@10
   843
      double W=std::sqrt(-2*std::log(S)/S);
alpar@10
   844
      return dim2::Point<double>(W*V1,W*V2);
alpar@10
   845
    }
alpar@10
   846
    /// A kind of two dimensional exponential distribution
alpar@10
   847
alpar@10
   848
    /// This function provides a turning symmetric two-dimensional distribution.
alpar@10
   849
    /// The x-coordinate is of conditionally exponential distribution
alpar@10
   850
    /// with the condition that x is positive and y=0. If x is negative and 
alpar@10
   851
    /// y=0 then, -x is of exponential distribution. The same is true for the
alpar@10
   852
    /// y-coordinate.
alpar@10
   853
    dim2::Point<double> exponential2() 
alpar@10
   854
    {
alpar@10
   855
      double V1,V2,S;
alpar@10
   856
      do {
alpar@10
   857
	V1=2*real<double>()-1;
alpar@10
   858
	V2=2*real<double>()-1;
alpar@10
   859
	S=V1*V1+V2*V2;
alpar@10
   860
      } while(S>=1);
alpar@10
   861
      double W=-std::log(S)/S;
alpar@10
   862
      return dim2::Point<double>(W*V1,W*V2);
alpar@10
   863
    }
alpar@10
   864
alpar@10
   865
    ///@}    
alpar@10
   866
  };
alpar@10
   867
alpar@10
   868
alpar@10
   869
  extern Random rnd;
alpar@10
   870
alpar@10
   871
}
alpar@10
   872
alpar@10
   873
#endif