lemon/random.h
author alpar
Thu, 01 Mar 2007 16:04:12 +0000
changeset 2380 7b0558c52de3
parent 2374 b59a17034ffa
child 2386 81b47fc5c444
permissions -rw-r--r--
ball2() -> disc() renaming
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
 *
deba@2229
     5
 * Copyright (C) 2003-2006
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@2229
    70
#include <cmath>
deba@2229
    71
alpar@2374
    72
#include <lemon/dim2.h>
deba@2229
    73
///\ingroup misc
deba@2229
    74
///\file
deba@2229
    75
///\brief Mersenne Twister random number generator
deba@2229
    76
///
deba@2229
    77
///\author Balazs Dezso
deba@2229
    78
deba@2229
    79
namespace lemon {
deba@2229
    80
deba@2242
    81
  namespace _random_bits {
deba@2242
    82
    
deba@2242
    83
    template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
deba@2242
    84
    struct RandomTraits {};
deba@2242
    85
deba@2242
    86
    template <typename _Word>
deba@2242
    87
    struct RandomTraits<_Word, 32> {
deba@2242
    88
deba@2242
    89
      typedef _Word Word;
deba@2242
    90
      static const int bits = 32;
deba@2242
    91
deba@2242
    92
      static const int length = 624;
deba@2242
    93
      static const int shift = 397;
deba@2242
    94
      
deba@2242
    95
      static const Word mul = 0x6c078965u;
deba@2242
    96
      static const Word arrayInit = 0x012BD6AAu;
deba@2242
    97
      static const Word arrayMul1 = 0x0019660Du;
deba@2242
    98
      static const Word arrayMul2 = 0x5D588B65u;
deba@2242
    99
deba@2242
   100
      static const Word mask = 0x9908B0DFu;
deba@2242
   101
      static const Word loMask = (1u << 31) - 1;
deba@2242
   102
      static const Word hiMask = ~loMask;
deba@2242
   103
deba@2242
   104
deba@2242
   105
      static Word tempering(Word rnd) {
deba@2242
   106
        rnd ^= (rnd >> 11);
deba@2242
   107
        rnd ^= (rnd << 7) & 0x9D2C5680u;
deba@2242
   108
        rnd ^= (rnd << 15) & 0xEFC60000u;
deba@2242
   109
        rnd ^= (rnd >> 18);
deba@2242
   110
        return rnd;
deba@2242
   111
      }
deba@2242
   112
deba@2242
   113
    };
deba@2242
   114
deba@2242
   115
    template <typename _Word>
deba@2242
   116
    struct RandomTraits<_Word, 64> {
deba@2242
   117
deba@2242
   118
      typedef _Word Word;
deba@2242
   119
      static const int bits = 64;
deba@2242
   120
deba@2242
   121
      static const int length = 312;
deba@2242
   122
      static const int shift = 156;
deba@2242
   123
deba@2242
   124
      static const Word mul = (Word)0x5851F42Du << 32 | (Word)0x4C957F2Du;
deba@2242
   125
      static const Word arrayInit = (Word)0x00000000u << 32 |(Word)0x012BD6AAu;
deba@2242
   126
      static const Word arrayMul1 = (Word)0x369DEA0Fu << 32 |(Word)0x31A53F85u;
deba@2242
   127
      static const Word arrayMul2 = (Word)0x27BB2EE6u << 32 |(Word)0x87B0B0FDu;
deba@2242
   128
deba@2242
   129
      static const Word mask = (Word)0xB5026F5Au << 32 | (Word)0xA96619E9u;
deba@2242
   130
      static const Word loMask = ((Word)1u << 31) - 1;
deba@2242
   131
      static const Word hiMask = ~loMask;
deba@2242
   132
deba@2242
   133
      static Word tempering(Word rnd) {
deba@2242
   134
        rnd ^= (rnd >> 29) & ((Word)0x55555555u << 32 | (Word)0x55555555u);
deba@2242
   135
        rnd ^= (rnd << 17) & ((Word)0x71D67FFFu << 32 | (Word)0xEDA60000u);
deba@2242
   136
        rnd ^= (rnd << 37) & ((Word)0xFFF7EEE0u << 32 | (Word)0x00000000u);
deba@2242
   137
        rnd ^= (rnd >> 43);
deba@2242
   138
        return rnd;
deba@2242
   139
      }
deba@2242
   140
deba@2242
   141
    };
deba@2242
   142
deba@2242
   143
    template <typename _Word>
deba@2242
   144
    class RandomCore {
deba@2242
   145
    public:
deba@2242
   146
deba@2242
   147
      typedef _Word Word;
deba@2242
   148
deba@2242
   149
    private:
deba@2242
   150
deba@2242
   151
      static const int bits = RandomTraits<Word>::bits;
deba@2242
   152
deba@2242
   153
      static const int length = RandomTraits<Word>::length;
deba@2242
   154
      static const int shift = RandomTraits<Word>::shift;
deba@2242
   155
deba@2242
   156
    public:
deba@2242
   157
deba@2242
   158
      void initState() {
deba@2242
   159
        static const Word seedArray[4] = {
deba@2242
   160
          0x12345u, 0x23456u, 0x34567u, 0x45678u
deba@2242
   161
        };
deba@2242
   162
    
deba@2242
   163
        initState(seedArray, seedArray + 4);
deba@2242
   164
      }
deba@2242
   165
deba@2242
   166
      void initState(Word seed) {
deba@2242
   167
deba@2242
   168
        static const Word mul = RandomTraits<Word>::mul;
deba@2242
   169
deba@2242
   170
        current = state; 
deba@2242
   171
deba@2242
   172
        Word *curr = state + length - 1;
deba@2242
   173
        curr[0] = seed; --curr;
deba@2242
   174
        for (int i = 1; i < length; ++i) {
deba@2242
   175
          curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
deba@2242
   176
          --curr;
deba@2242
   177
        }
deba@2242
   178
      }
deba@2242
   179
deba@2242
   180
      template <typename Iterator>
deba@2242
   181
      void initState(Iterator begin, Iterator end) {
deba@2242
   182
deba@2242
   183
        static const Word init = RandomTraits<Word>::arrayInit;
deba@2242
   184
        static const Word mul1 = RandomTraits<Word>::arrayMul1;
deba@2242
   185
        static const Word mul2 = RandomTraits<Word>::arrayMul2;
deba@2242
   186
deba@2242
   187
deba@2242
   188
        Word *curr = state + length - 1; --curr;
deba@2242
   189
        Iterator it = begin; int cnt = 0;
deba@2242
   190
        int num;
deba@2242
   191
deba@2242
   192
        initState(init);
deba@2242
   193
deba@2242
   194
        num = length > end - begin ? length : end - begin;
deba@2242
   195
        while (num--) {
deba@2242
   196
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 
deba@2242
   197
            + *it + cnt;
deba@2242
   198
          ++it; ++cnt;
deba@2242
   199
          if (it == end) {
deba@2242
   200
            it = begin; cnt = 0;
deba@2242
   201
          }
deba@2242
   202
          if (curr == state) {
deba@2242
   203
            curr = state + length - 1; curr[0] = state[0];
deba@2242
   204
          }
deba@2242
   205
          --curr;
deba@2242
   206
        }
deba@2242
   207
deba@2242
   208
        num = length - 1; cnt = length - (curr - state) - 1;
deba@2242
   209
        while (num--) {
deba@2242
   210
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
deba@2242
   211
            - cnt;
deba@2242
   212
          --curr; ++cnt;
deba@2242
   213
          if (curr == state) {
deba@2242
   214
            curr = state + length - 1; curr[0] = state[0]; --curr;
deba@2242
   215
            cnt = 1;
deba@2242
   216
          }
deba@2242
   217
        }
deba@2242
   218
        
deba@2242
   219
        state[length - 1] = (Word)1 << (bits - 1);
deba@2242
   220
      }
deba@2242
   221
      
deba@2242
   222
      void copyState(const RandomCore& other) {
deba@2242
   223
        std::copy(other.state, other.state + length, state);
deba@2242
   224
        current = state + (other.current - other.state);
deba@2242
   225
      }
deba@2242
   226
deba@2242
   227
      Word operator()() {
deba@2242
   228
        if (current == state) fillState();
deba@2242
   229
        --current;
deba@2242
   230
        Word rnd = *current;
deba@2242
   231
        return RandomTraits<Word>::tempering(rnd);
deba@2242
   232
      }
deba@2242
   233
deba@2242
   234
    private:
deba@2242
   235
deba@2242
   236
  
deba@2242
   237
      void fillState() {
deba@2242
   238
        static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
deba@2242
   239
        static const Word loMask = RandomTraits<Word>::loMask;
deba@2242
   240
        static const Word hiMask = RandomTraits<Word>::hiMask;
deba@2242
   241
deba@2242
   242
        current = state + length; 
deba@2242
   243
deba@2242
   244
        register Word *curr = state + length - 1;
deba@2242
   245
        register long num;
deba@2242
   246
      
deba@2242
   247
        num = length - shift;
deba@2242
   248
        while (num--) {
deba@2242
   249
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
deba@2242
   250
            curr[- shift] ^ mask[curr[-1] & 1ul];
deba@2242
   251
          --curr;
deba@2242
   252
        }
deba@2242
   253
        num = shift - 1;
deba@2242
   254
        while (num--) {
deba@2242
   255
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
deba@2242
   256
            curr[length - shift] ^ mask[curr[-1] & 1ul];
deba@2242
   257
          --curr;
deba@2242
   258
        }
deba@2242
   259
        curr[0] = (((curr[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
deba@2242
   260
          curr[length - shift] ^ mask[curr[length - 1] & 1ul];
deba@2242
   261
deba@2242
   262
      }
deba@2242
   263
deba@2242
   264
  
deba@2242
   265
      Word *current;
deba@2242
   266
      Word state[length];
deba@2242
   267
      
deba@2242
   268
    };
deba@2242
   269
deba@2242
   270
deba@2242
   271
    template <typename Result, 
deba@2242
   272
              int shift = (std::numeric_limits<Result>::digits + 1) / 2>
deba@2242
   273
    struct Masker {
deba@2242
   274
      static Result mask(const Result& result) {
deba@2242
   275
        return Masker<Result, (shift + 1) / 2>::
deba@2242
   276
          mask((Result)(result | (result >> shift)));
deba@2242
   277
      }
deba@2242
   278
    };
deba@2242
   279
    
deba@2242
   280
    template <typename Result>
deba@2242
   281
    struct Masker<Result, 1> {
deba@2242
   282
      static Result mask(const Result& result) {
deba@2242
   283
        return (Result)(result | (result >> 1));
deba@2242
   284
      }
deba@2242
   285
    };
deba@2242
   286
deba@2242
   287
    template <typename Result, typename Word, 
deba@2242
   288
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
deba@2242
   289
              bool last = rest <= std::numeric_limits<Word>::digits>
deba@2242
   290
    struct IntConversion {
deba@2242
   291
      static const int bits = std::numeric_limits<Word>::digits;
deba@2242
   292
    
deba@2242
   293
      static Result convert(RandomCore<Word>& rnd) {
deba@2242
   294
        return (Result)(rnd() >> (bits - rest)) << shift;
deba@2242
   295
      }
deba@2242
   296
      
deba@2242
   297
    }; 
deba@2242
   298
deba@2242
   299
    template <typename Result, typename Word, int rest, int shift> 
deba@2242
   300
    struct IntConversion<Result, Word, rest, shift, false> {
deba@2242
   301
      static const int bits = std::numeric_limits<Word>::digits;
deba@2242
   302
deba@2242
   303
      static Result convert(RandomCore<Word>& rnd) {
deba@2242
   304
        return ((Result)rnd() << shift) | 
deba@2242
   305
          IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
deba@2242
   306
      }
deba@2242
   307
    };
deba@2242
   308
deba@2242
   309
deba@2242
   310
    template <typename Result, typename Word,
deba@2242
   311
              bool one_word = std::numeric_limits<Word>::digits < 
deba@2242
   312
                              std::numeric_limits<Result>::digits>
deba@2242
   313
    struct Mapping {
deba@2242
   314
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
deba@2242
   315
        Word max = (Word)(bound - 1);
deba@2242
   316
        Result mask = Masker<Result>::mask(bound - 1);
deba@2242
   317
        Result num;
deba@2242
   318
        do {
deba@2242
   319
          num = IntConversion<Result, Word>::convert(rnd) & mask; 
deba@2242
   320
        } while (num > max);
deba@2242
   321
        return num;
deba@2242
   322
      }
deba@2242
   323
    };
deba@2242
   324
deba@2242
   325
    template <typename Result, typename Word>
deba@2242
   326
    struct Mapping<Result, Word, false> {
deba@2242
   327
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
deba@2242
   328
        Word max = (Word)(bound - 1);
deba@2242
   329
        Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
deba@2242
   330
          ::mask(max);
deba@2242
   331
        Word num;
deba@2242
   332
        do {
deba@2242
   333
          num = rnd() & mask;
deba@2242
   334
        } while (num > max);
deba@2242
   335
        return num;
deba@2242
   336
      }
deba@2242
   337
    };
deba@2242
   338
deba@2242
   339
    template <typename Result, int exp, bool pos = (exp >= 0)>
deba@2242
   340
    struct ShiftMultiplier {
deba@2242
   341
      static const Result multiplier() {
deba@2242
   342
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
deba@2242
   343
        res *= res;
deba@2242
   344
        if ((exp & 1) == 1) res *= (Result)2.0;
deba@2242
   345
        return res; 
deba@2242
   346
      }
deba@2242
   347
    };
deba@2242
   348
deba@2242
   349
    template <typename Result, int exp>
deba@2242
   350
    struct ShiftMultiplier<Result, exp, false> {
deba@2242
   351
      static const Result multiplier() {
deba@2242
   352
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
deba@2242
   353
        res *= res;
deba@2242
   354
        if ((exp & 1) == 1) res *= (Result)0.5;
deba@2242
   355
        return res; 
deba@2242
   356
      }
deba@2242
   357
    };
deba@2242
   358
deba@2242
   359
    template <typename Result>
deba@2242
   360
    struct ShiftMultiplier<Result, 0, true> {
deba@2242
   361
      static const Result multiplier() {
deba@2242
   362
        return (Result)1.0; 
deba@2242
   363
      }
deba@2242
   364
    };
deba@2242
   365
deba@2242
   366
    template <typename Result>
deba@2242
   367
    struct ShiftMultiplier<Result, -20, true> {
deba@2242
   368
      static const Result multiplier() {
deba@2242
   369
        return (Result)(1.0/1048576.0); 
deba@2242
   370
      }
deba@2242
   371
    };
deba@2242
   372
    
deba@2242
   373
    template <typename Result>
deba@2242
   374
    struct ShiftMultiplier<Result, -32, true> {
deba@2242
   375
      static const Result multiplier() {
deba@2242
   376
        return (Result)(1.0/424967296.0); 
deba@2242
   377
      }
deba@2242
   378
    };
deba@2242
   379
deba@2242
   380
    template <typename Result>
deba@2242
   381
    struct ShiftMultiplier<Result, -53, true> {
deba@2242
   382
      static const Result multiplier() {
deba@2242
   383
        return (Result)(1.0/9007199254740992.0); 
deba@2242
   384
      }
deba@2242
   385
    };
deba@2242
   386
deba@2242
   387
    template <typename Result>
deba@2242
   388
    struct ShiftMultiplier<Result, -64, true> {
deba@2242
   389
      static const Result multiplier() {
deba@2242
   390
        return (Result)(1.0/18446744073709551616.0); 
deba@2242
   391
      }
deba@2242
   392
    };
deba@2242
   393
deba@2242
   394
    template <typename Result, int exp>
deba@2242
   395
    struct Shifting {
deba@2242
   396
      static Result shift(const Result& result) {
deba@2242
   397
        return result * ShiftMultiplier<Result, exp>::multiplier();
deba@2242
   398
      }
deba@2242
   399
    };
deba@2242
   400
deba@2242
   401
    template <typename Result, typename Word,
deba@2242
   402
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
deba@2242
   403
              bool last = rest <= std::numeric_limits<Word>::digits>
deba@2242
   404
    struct RealConversion{ 
deba@2242
   405
      static const int bits = std::numeric_limits<Word>::digits;
deba@2242
   406
deba@2242
   407
      static Result convert(RandomCore<Word>& rnd) {
deba@2242
   408
        return Shifting<Result, - shift - rest>::
deba@2242
   409
          shift((Result)(rnd() >> (bits - rest)));
deba@2242
   410
      }
deba@2242
   411
    };
deba@2242
   412
deba@2242
   413
    template <typename Result, typename Word, int rest, int shift>
deba@2242
   414
    struct RealConversion<Result, Word, rest, shift, false> { 
deba@2242
   415
      static const int bits = std::numeric_limits<Word>::digits;
deba@2242
   416
deba@2242
   417
      static Result convert(RandomCore<Word>& rnd) {
deba@2242
   418
        return Shifting<Result, - shift - bits>::shift((Result)rnd()) +
deba@2242
   419
          RealConversion<Result, Word, rest-bits, shift + bits>::convert(rnd);
deba@2242
   420
      }
deba@2242
   421
    };
deba@2242
   422
deba@2242
   423
    template <typename Result, typename Word>
deba@2242
   424
    struct Initializer {
deba@2242
   425
deba@2242
   426
      template <typename Iterator>
deba@2242
   427
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
deba@2242
   428
        std::vector<Word> ws;
deba@2242
   429
        for (Iterator it = begin; it != end; ++it) {
deba@2242
   430
          ws.push_back((Word)*it);
deba@2242
   431
        }
deba@2242
   432
        rnd.initState(ws.begin(), ws.end());
deba@2242
   433
      }
deba@2242
   434
deba@2242
   435
      static void init(RandomCore<Word>& rnd, Result seed) {
deba@2242
   436
        rnd.initState(seed);
deba@2242
   437
      }
deba@2242
   438
    };
deba@2242
   439
deba@2242
   440
    template <typename Word>
deba@2242
   441
    struct BoolConversion {
deba@2242
   442
      static bool convert(RandomCore<Word>& rnd) {
deba@2242
   443
        return (rnd() & 1) == 1;
deba@2242
   444
      }
deba@2242
   445
    };
deba@2242
   446
deba@2372
   447
    template <typename Word>
deba@2372
   448
    struct BoolProducer {
deba@2372
   449
      Word buffer;
deba@2372
   450
      int num;
deba@2372
   451
      
deba@2372
   452
      BoolProducer() : num(0) {}
deba@2372
   453
deba@2372
   454
      bool convert(RandomCore<Word>& rnd) {
deba@2372
   455
        if (num == 0) {
deba@2372
   456
          buffer = rnd();
deba@2372
   457
          num = RandomTraits<Word>::bits;
deba@2372
   458
        }
deba@2372
   459
        bool r = (buffer & 1);
deba@2372
   460
        buffer >>= 1;
deba@2372
   461
        --num;
deba@2372
   462
        return r;
deba@2372
   463
      }
deba@2372
   464
    };
deba@2372
   465
deba@2242
   466
  }
deba@2229
   467
deba@2229
   468
  /// \ingroup misc
deba@2229
   469
  ///
deba@2229
   470
  /// \brief Mersenne Twister random number generator
deba@2229
   471
  ///
deba@2229
   472
  /// The Mersenne Twister is a twisted generalized feedback
deba@2242
   473
  /// shift-register generator of Matsumoto and Nishimura. The period
deba@2242
   474
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
deba@2242
   475
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
deba@2242
   476
  /// performance of this generator is comparable to the commonly used
deba@2242
   477
  /// generators.
deba@2242
   478
  ///
deba@2242
   479
  /// This implementation is specialized for both 32-bit and 64-bit
deba@2242
   480
  /// architectures. The generators differ sligthly in the
deba@2242
   481
  /// initialization and generation phase so they produce two
deba@2242
   482
  /// completly different sequences.
deba@2242
   483
  ///
deba@2242
   484
  /// The generator gives back random numbers of serveral types. To
deba@2242
   485
  /// get a random number from a range of a floating point type you
deba@2245
   486
  /// can use one form of the \c operator() or the \c real() member
deba@2245
   487
  /// function. If you want to get random number from the {0, 1, ...,
deba@2245
   488
  /// n-1} integer range use the \c operator[] or the \c integer()
deba@2245
   489
  /// method. And to get random number from the whole range of an
deba@2245
   490
  /// integer type you can use the argumentless \c integer() or \c
deba@2245
   491
  /// uinteger() functions. After all you can get random bool with
deba@2245
   492
  /// equal chance of true and false or given probability of true
deba@2245
   493
  /// result with the \c boolean() member functions.
deba@2242
   494
  ///
deba@2242
   495
  ///\code
deba@2245
   496
  /// // The commented code is identical to the other
deba@2245
   497
  /// double a = rnd();                     // [0.0, 1.0)
deba@2245
   498
  /// // double a = rnd.real();             // [0.0, 1.0)
deba@2245
   499
  /// double b = rnd(100.0);                // [0.0, 100.0)
deba@2245
   500
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
deba@2245
   501
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
deba@2245
   502
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
deba@2245
   503
  /// int d = rnd[100000];                  // 0..99999
deba@2245
   504
  /// // int d = rnd.integer(100000);       // 0..99999
deba@2245
   505
  /// int e = rnd[6] + 1;                   // 1..6
deba@2245
   506
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
deba@2242
   507
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
deba@2242
   508
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
deba@2242
   509
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
deba@2242
   510
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
deba@2242
   511
  ///\endcode
deba@2242
   512
  ///
deba@2245
   513
  /// The lemon provides a global instance of the random number
deba@2245
   514
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
deba@2245
   515
  /// good programming convenience to use this global generator to get
deba@2245
   516
  /// random numbers.
deba@2229
   517
  ///
deba@2229
   518
  /// \author Balazs Dezso
deba@2229
   519
  class Random {
deba@2242
   520
  private:
deba@2229
   521
deba@2245
   522
    // architecture word
deba@2242
   523
    typedef unsigned long Word;
deba@2242
   524
    
deba@2242
   525
    _random_bits::RandomCore<Word> core;
deba@2372
   526
    _random_bits::BoolProducer<Word> bool_producer;
deba@2372
   527
    
deba@2229
   528
deba@2229
   529
  public:
deba@2229
   530
deba@2229
   531
    /// \brief Constructor
deba@2229
   532
    ///
deba@2242
   533
    /// Constructor with constant seeding.
deba@2242
   534
    Random() { core.initState(); }
deba@2229
   535
deba@2229
   536
    /// \brief Constructor
deba@2229
   537
    ///
deba@2242
   538
    /// Constructor with seed. The current number type will be converted
deba@2242
   539
    /// to the architecture word type.
deba@2242
   540
    template <typename Number>
deba@2242
   541
    Random(Number seed) { 
deba@2242
   542
      _random_bits::Initializer<Number, Word>::init(core, seed);
deba@2242
   543
    }
deba@2242
   544
deba@2242
   545
    /// \brief Constructor
deba@2242
   546
    ///
deba@2242
   547
    /// Constructor with array seeding. The given range should contain
deba@2242
   548
    /// any number type and the numbers will be converted to the
deba@2242
   549
    /// architecture word type.
deba@2242
   550
    template <typename Iterator>
deba@2242
   551
    Random(Iterator begin, Iterator end) { 
deba@2242
   552
      typedef typename std::iterator_traits<Iterator>::value_type Number;
deba@2242
   553
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
deba@2242
   554
    }
deba@2229
   555
deba@2229
   556
    /// \brief Copy constructor
deba@2229
   557
    ///
deba@2229
   558
    /// Copy constructor. The generated sequence will be identical to
deba@2245
   559
    /// the other sequence. It can be used to save the current state
deba@2245
   560
    /// of the generator and later use it to generate the same
deba@2245
   561
    /// sequence.
deba@2242
   562
    Random(const Random& other) {
deba@2242
   563
      core.copyState(other.core);
deba@2229
   564
    }
deba@2229
   565
deba@2229
   566
    /// \brief Assign operator
deba@2229
   567
    ///
deba@2229
   568
    /// Assign operator. The generated sequence will be identical to
deba@2245
   569
    /// the other sequence. It can be used to save the current state
deba@2245
   570
    /// of the generator and later use it to generate the same
deba@2245
   571
    /// sequence.
deba@2229
   572
    Random& operator=(const Random& other) {
deba@2229
   573
      if (&other != this) {
deba@2242
   574
        core.copyState(other.core);
deba@2229
   575
      }
deba@2229
   576
      return *this;
deba@2229
   577
    }
deba@2229
   578
alpar@2257
   579
    /// \brief Returns a random real number from the range [0, 1)
deba@2229
   580
    ///
deba@2245
   581
    /// It returns a random real number from the range [0, 1). The
deba@2245
   582
    /// default Number type is double.
deba@2242
   583
    template <typename Number>
deba@2245
   584
    Number real() {
deba@2242
   585
      return _random_bits::RealConversion<Number, Word>::convert(core);
deba@2229
   586
    }
deba@2229
   587
deba@2245
   588
    double real() {
deba@2245
   589
      return real<double>();
deba@2245
   590
    }
deba@2245
   591
alpar@2257
   592
    /// \brief Returns a random real number the range [0, b)
deba@2245
   593
    ///
deba@2245
   594
    /// It returns a random real number from the range [0, b).
deba@2245
   595
    template <typename Number>
deba@2245
   596
    Number real(Number b) { 
deba@2245
   597
      return real<Number>() * b; 
deba@2245
   598
    }
deba@2245
   599
alpar@2257
   600
    /// \brief Returns a random real number from the range [a, b)
deba@2245
   601
    ///
deba@2245
   602
    /// It returns a random real number from the range [a, b).
deba@2245
   603
    template <typename Number>
deba@2245
   604
    Number real(Number a, Number b) { 
deba@2245
   605
      return real<Number>() * (b - a) + a; 
deba@2245
   606
    }
deba@2245
   607
alpar@2257
   608
    /// \brief Returns a random real number from the range [0, 1)
deba@2245
   609
    ///
deba@2245
   610
    /// It returns a random double from the range [0, 1).
deba@2242
   611
    double operator()() {
deba@2245
   612
      return real<double>();
deba@2242
   613
    }
deba@2242
   614
alpar@2257
   615
    /// \brief Returns a random real number from the range [0, b)
deba@2229
   616
    ///
deba@2242
   617
    /// It returns a random real number from the range [0, b).
deba@2242
   618
    template <typename Number>
deba@2242
   619
    Number operator()(Number b) { 
deba@2245
   620
      return real<Number>() * b; 
deba@2242
   621
    }
deba@2242
   622
alpar@2257
   623
    /// \brief Returns a random real number from the range [a, b)
deba@2242
   624
    ///
deba@2242
   625
    /// It returns a random real number from the range [a, b).
deba@2242
   626
    template <typename Number>
deba@2242
   627
    Number operator()(Number a, Number b) { 
deba@2245
   628
      return real<Number>() * (b - a) + a; 
deba@2242
   629
    }
deba@2242
   630
deba@2242
   631
    /// \brief Returns a random integer from a range
deba@2242
   632
    ///
deba@2245
   633
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
deba@2242
   634
    template <typename Number>
deba@2245
   635
    Number integer(Number b) {
deba@2245
   636
      return _random_bits::Mapping<Number, Word>::map(core, b);
deba@2245
   637
    }
deba@2245
   638
deba@2245
   639
    /// \brief Returns a random integer from a range
deba@2245
   640
    ///
deba@2245
   641
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
deba@2245
   642
    template <typename Number>
deba@2245
   643
    Number integer(Number a, Number b) {
deba@2245
   644
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
deba@2245
   645
    }
deba@2245
   646
deba@2245
   647
    /// \brief Returns a random integer from a range
deba@2245
   648
    ///
deba@2245
   649
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
deba@2245
   650
    template <typename Number>
deba@2245
   651
    Number operator[](Number b) {
deba@2245
   652
      return _random_bits::Mapping<Number, Word>::map(core, b);
deba@2242
   653
    }
deba@2242
   654
deba@2242
   655
    /// \brief Returns a random non-negative integer
deba@2242
   656
    ///
deba@2242
   657
    /// It returns a random non-negative integer uniformly from the
deba@2242
   658
    /// whole range of the current \c Number type.  The default result
deba@2242
   659
    /// type of this function is unsigned int.
deba@2242
   660
    template <typename Number>
deba@2242
   661
    Number uinteger() {
deba@2242
   662
      return _random_bits::IntConversion<Number, Word>::convert(core);
deba@2242
   663
    }
deba@2242
   664
deba@2242
   665
    unsigned int uinteger() {
deba@2242
   666
      return uinteger<unsigned int>();
deba@2242
   667
    }
deba@2242
   668
deba@2242
   669
    /// \brief Returns a random integer
deba@2242
   670
    ///
deba@2242
   671
    /// It returns a random integer uniformly from the whole range of
deba@2242
   672
    /// the current \c Number type. The default result type of this
deba@2242
   673
    /// function is int.
deba@2242
   674
    template <typename Number>
deba@2242
   675
    Number integer() {
deba@2242
   676
      static const int nb = std::numeric_limits<Number>::digits + 
deba@2242
   677
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
deba@2242
   678
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
deba@2242
   679
    }
deba@2242
   680
deba@2242
   681
    int integer() {
deba@2242
   682
      return integer<int>();
deba@2229
   683
    }
deba@2229
   684
    
deba@2242
   685
    /// \brief Returns a random bool
deba@2229
   686
    ///
deba@2372
   687
    /// It returns a random bool. The generator holds a buffer for
deba@2372
   688
    /// random bits. Every time when it become empty the generator makes
deba@2372
   689
    /// a new random word and fill the buffer up.
deba@2242
   690
    bool boolean() {
deba@2372
   691
      return bool_producer.convert(core);
deba@2229
   692
    }
deba@2229
   693
alpar@2356
   694
    ///\name Nonuniform distributions
alpar@2356
   695
    ///
alpar@2356
   696
    
alpar@2356
   697
    ///@{
alpar@2356
   698
    
deba@2229
   699
    /// \brief Returns a random bool
deba@2229
   700
    ///
deba@2242
   701
    /// It returns a random bool with given probability of true result
deba@2242
   702
    bool boolean(double p) {
deba@2242
   703
      return operator()() < p;
deba@2229
   704
    }
alpar@2355
   705
alpar@2355
   706
    /// Standard Gauss distribution
alpar@2355
   707
alpar@2355
   708
    /// Standard Gauss distribution.
alpar@2356
   709
    /// \note The Cartesian form of the Box-Muller
alpar@2356
   710
    /// transformation is used to generate a random normal distribution.
alpar@2356
   711
    /// \todo Consider using the "ziggurat" method instead.
alpar@2355
   712
    double gauss() 
alpar@2355
   713
    {
alpar@2355
   714
      double V1,V2,S;
alpar@2355
   715
      do {
alpar@2355
   716
	V1=2*real<double>()-1;
alpar@2355
   717
	V2=2*real<double>()-1;
alpar@2355
   718
	S=V1*V1+V2*V2;
alpar@2355
   719
      } while(S>=1);
alpar@2355
   720
      return std::sqrt(-2*std::log(S)/S)*V1;
alpar@2355
   721
    }
alpar@2356
   722
    /// Gauss distribution with given standard deviation and mean 0
alpar@2356
   723
alpar@2356
   724
    /// \sa gauss()
alpar@2356
   725
    ///
alpar@2356
   726
    double gauss(double std_dev) 
alpar@2355
   727
    {
alpar@2356
   728
      return gauss()*std_dev;
alpar@2355
   729
    }
alpar@2356
   730
    /// Gauss distribution with given mean and standard deviation
alpar@2356
   731
alpar@2356
   732
    /// \sa gauss()
alpar@2356
   733
    ///
alpar@2356
   734
    double gauss(double mean,double std_dev)
alpar@2355
   735
    {
alpar@2356
   736
      return gauss()*std_dev+mean;
alpar@2355
   737
    }
alpar@2355
   738
alpar@2356
   739
    /// Exponential distribution with given mean
alpar@2356
   740
alpar@2356
   741
    /// This function generates an exponential distribution random number
alpar@2356
   742
    /// with mean <tt>1/lambda</tt>.
alpar@2356
   743
    ///
alpar@2356
   744
    double exponential(double lambda=1.0)
alpar@2355
   745
    {
alpar@2374
   746
      return -std::log(real<double>())/lambda;
alpar@2355
   747
    }
alpar@2356
   748
alpar@2356
   749
    ///@}
deba@2229
   750
    
alpar@2374
   751
    ///\name Two dimensional distributions
alpar@2374
   752
    ///
alpar@2374
   753
alpar@2374
   754
    ///@{
alpar@2374
   755
    
alpar@2374
   756
    /// Uniform distribution on the full unit circle.
alpar@2380
   757
    dim2::Point<double> disc() 
alpar@2374
   758
    {
alpar@2374
   759
      double V1,V2;
alpar@2374
   760
      do {
alpar@2374
   761
	V1=2*real<double>()-1;
alpar@2374
   762
	V2=2*real<double>()-1;
alpar@2374
   763
	
alpar@2374
   764
      } while(V1*V1+V2*V2>=1);
alpar@2374
   765
      return dim2::Point<double>(V1,V2);
alpar@2374
   766
    }
alpar@2374
   767
    /// A kind of two dimensional Gauss distribution
alpar@2374
   768
alpar@2374
   769
    /// This function provides a turning symmetric two-dimensional distribution.
alpar@2374
   770
    /// Both coordinates are of standard normal distribution, but they are not
alpar@2374
   771
    /// independent.
alpar@2374
   772
    ///
alpar@2374
   773
    /// \note The coordinates are the two random variables provided by
alpar@2374
   774
    /// the Box-Muller method.
alpar@2374
   775
    dim2::Point<double> gauss2()
alpar@2374
   776
    {
alpar@2374
   777
      double V1,V2,S;
alpar@2374
   778
      do {
alpar@2374
   779
	V1=2*real<double>()-1;
alpar@2374
   780
	V2=2*real<double>()-1;
alpar@2374
   781
	S=V1*V1+V2*V2;
alpar@2374
   782
      } while(S>=1);
alpar@2374
   783
      double W=std::sqrt(-2*std::log(S)/S);
alpar@2374
   784
      return dim2::Point<double>(W*V1,W*V2);
alpar@2374
   785
    }
alpar@2374
   786
    /// A kind of two dimensional exponential distribution
alpar@2374
   787
alpar@2374
   788
    /// This function provides a turning symmetric two-dimensional distribution.
alpar@2374
   789
    /// The x-coordinate is of conditionally exponential distribution
alpar@2374
   790
    /// with the condition that x is positive and y=0. If x is negative and 
alpar@2374
   791
    /// y=0 then, -x is of exponential distribution. The same is true for the
alpar@2374
   792
    /// y-coordinate.
alpar@2374
   793
    dim2::Point<double> exponential2() 
alpar@2374
   794
    {
alpar@2374
   795
      double V1,V2,S;
alpar@2374
   796
      do {
alpar@2374
   797
	V1=2*real<double>()-1;
alpar@2374
   798
	V2=2*real<double>()-1;
alpar@2374
   799
	S=V1*V1+V2*V2;
alpar@2374
   800
      } while(S>=1);
alpar@2374
   801
      double W=-std::log(S)/S;
alpar@2374
   802
      return dim2::Point<double>(W*V1,W*V2);
alpar@2374
   803
    }
alpar@2374
   804
alpar@2374
   805
    ///@}    
deba@2229
   806
  };
deba@2229
   807
deba@2229
   808
deba@2229
   809
  extern Random rnd;
deba@2229
   810
deba@2229
   811
}
deba@2229
   812
deba@2229
   813
#endif