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