lemon/random.h
author kpeter
Mon, 18 Feb 2008 03:32:06 +0000
changeset 2575 e866e288cba6
parent 2569 12c2c5c4330b
child 2596 9c00e972cdfd
permissions -rw-r--r--
Major improvements in NetworkSimplex.

Main changes:
- Use -potenital[] instead of potential[] to conform to the usual
terminology.
- Use function parameter instead of #define commands to select pivot rule.
- Use much faster implementation for the candidate list pivot rule.
It is about 5-20 times faster now.
- Add a new pivot rule called "Limited Search" that is a modified
version of "Block Search". It is about 25 percent faster on rather
sparse graphs.
- By default "Limited Search" is used for sparse graphs and
"Block Search" is used otherwise. This combined method is the most
efficient on every input class.
- Change the name of private members to start with "_".
- Change the name of function parameters not to start with "_".
- Remove unnecessary documentation for private members.
- Many doc improvements.
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@2229
    70
alpar@2570
    71
#include <lemon/math.h>
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@2386
   124
      static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
deba@2386
   125
      static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
deba@2386
   126
      static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
deba@2386
   127
      static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
deba@2242
   128
deba@2386
   129
      static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
deba@2386
   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@2386
   134
        rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
deba@2386
   135
        rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
deba@2386
   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@2386
   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@2545
   260
          curr[length - shift] ^ mask[int(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@2386
   276
          mask(static_cast<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@2386
   283
        return static_cast<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@2386
   294
        return static_cast<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@2386
   304
        return (static_cast<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,
alpar@2387
   311
              bool one_word = (std::numeric_limits<Word>::digits < 
alpar@2387
   312
			       std::numeric_limits<Result>::digits) >
deba@2242
   313
    struct Mapping {
deba@2242
   314
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
deba@2386
   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@2386
   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@2386
   344
        if ((exp & 1) == 1) res *= static_cast<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@2386
   354
        if ((exp & 1) == 1) res *= static_cast<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@2386
   362
        return static_cast<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@2386
   369
        return static_cast<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@2386
   376
        return static_cast<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@2386
   383
        return static_cast<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@2386
   390
        return static_cast<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@2386
   409
          shift(static_cast<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@2386
   418
        return Shifting<Result, - shift - bits>::
deba@2386
   419
          shift(static_cast<Result>(rnd())) +
deba@2386
   420
          RealConversion<Result, Word, rest-bits, shift + bits>::
deba@2386
   421
          convert(rnd);
deba@2242
   422
      }
deba@2242
   423
    };
deba@2242
   424
deba@2242
   425
    template <typename Result, typename Word>
deba@2242
   426
    struct Initializer {
deba@2242
   427
deba@2242
   428
      template <typename Iterator>
deba@2242
   429
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
deba@2242
   430
        std::vector<Word> ws;
deba@2242
   431
        for (Iterator it = begin; it != end; ++it) {
deba@2386
   432
          ws.push_back(Word(*it));
deba@2242
   433
        }
deba@2242
   434
        rnd.initState(ws.begin(), ws.end());
deba@2242
   435
      }
deba@2242
   436
deba@2242
   437
      static void init(RandomCore<Word>& rnd, Result seed) {
deba@2242
   438
        rnd.initState(seed);
deba@2242
   439
      }
deba@2242
   440
    };
deba@2242
   441
deba@2242
   442
    template <typename Word>
deba@2242
   443
    struct BoolConversion {
deba@2242
   444
      static bool convert(RandomCore<Word>& rnd) {
deba@2242
   445
        return (rnd() & 1) == 1;
deba@2242
   446
      }
deba@2242
   447
    };
deba@2242
   448
deba@2372
   449
    template <typename Word>
deba@2372
   450
    struct BoolProducer {
deba@2372
   451
      Word buffer;
deba@2372
   452
      int num;
deba@2372
   453
      
deba@2372
   454
      BoolProducer() : num(0) {}
deba@2372
   455
deba@2372
   456
      bool convert(RandomCore<Word>& rnd) {
deba@2372
   457
        if (num == 0) {
deba@2372
   458
          buffer = rnd();
deba@2372
   459
          num = RandomTraits<Word>::bits;
deba@2372
   460
        }
deba@2372
   461
        bool r = (buffer & 1);
deba@2372
   462
        buffer >>= 1;
deba@2372
   463
        --num;
deba@2372
   464
        return r;
deba@2372
   465
      }
deba@2372
   466
    };
deba@2372
   467
deba@2242
   468
  }
deba@2229
   469
deba@2229
   470
  /// \ingroup misc
deba@2229
   471
  ///
deba@2229
   472
  /// \brief Mersenne Twister random number generator
deba@2229
   473
  ///
deba@2229
   474
  /// The Mersenne Twister is a twisted generalized feedback
deba@2242
   475
  /// shift-register generator of Matsumoto and Nishimura. The period
deba@2242
   476
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
deba@2242
   477
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
deba@2242
   478
  /// performance of this generator is comparable to the commonly used
deba@2242
   479
  /// generators.
deba@2242
   480
  ///
deba@2242
   481
  /// This implementation is specialized for both 32-bit and 64-bit
deba@2242
   482
  /// architectures. The generators differ sligthly in the
deba@2242
   483
  /// initialization and generation phase so they produce two
deba@2242
   484
  /// completly different sequences.
deba@2242
   485
  ///
deba@2242
   486
  /// The generator gives back random numbers of serveral types. To
deba@2242
   487
  /// get a random number from a range of a floating point type you
deba@2245
   488
  /// can use one form of the \c operator() or the \c real() member
deba@2245
   489
  /// function. If you want to get random number from the {0, 1, ...,
deba@2245
   490
  /// n-1} integer range use the \c operator[] or the \c integer()
deba@2245
   491
  /// method. And to get random number from the whole range of an
deba@2245
   492
  /// integer type you can use the argumentless \c integer() or \c
deba@2245
   493
  /// uinteger() functions. After all you can get random bool with
deba@2245
   494
  /// equal chance of true and false or given probability of true
deba@2245
   495
  /// result with the \c boolean() member functions.
deba@2242
   496
  ///
deba@2242
   497
  ///\code
deba@2245
   498
  /// // The commented code is identical to the other
deba@2245
   499
  /// double a = rnd();                     // [0.0, 1.0)
deba@2245
   500
  /// // double a = rnd.real();             // [0.0, 1.0)
deba@2245
   501
  /// double b = rnd(100.0);                // [0.0, 100.0)
deba@2245
   502
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
deba@2245
   503
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
deba@2245
   504
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
deba@2245
   505
  /// int d = rnd[100000];                  // 0..99999
deba@2245
   506
  /// // int d = rnd.integer(100000);       // 0..99999
deba@2245
   507
  /// int e = rnd[6] + 1;                   // 1..6
deba@2245
   508
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
deba@2242
   509
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
deba@2242
   510
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
deba@2242
   511
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
deba@2242
   512
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
deba@2242
   513
  ///\endcode
deba@2242
   514
  ///
deba@2245
   515
  /// The lemon provides a global instance of the random number
deba@2245
   516
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
deba@2245
   517
  /// good programming convenience to use this global generator to get
deba@2245
   518
  /// random numbers.
deba@2229
   519
  ///
deba@2229
   520
  /// \author Balazs Dezso
deba@2229
   521
  class Random {
deba@2242
   522
  private:
deba@2229
   523
deba@2245
   524
    // architecture word
deba@2242
   525
    typedef unsigned long Word;
deba@2242
   526
    
deba@2242
   527
    _random_bits::RandomCore<Word> core;
deba@2372
   528
    _random_bits::BoolProducer<Word> bool_producer;
deba@2372
   529
    
deba@2229
   530
deba@2229
   531
  public:
deba@2229
   532
deba@2229
   533
    /// \brief Constructor
deba@2229
   534
    ///
deba@2242
   535
    /// Constructor with constant seeding.
deba@2242
   536
    Random() { core.initState(); }
deba@2229
   537
deba@2229
   538
    /// \brief Constructor
deba@2229
   539
    ///
deba@2242
   540
    /// Constructor with seed. The current number type will be converted
deba@2242
   541
    /// to the architecture word type.
deba@2242
   542
    template <typename Number>
deba@2242
   543
    Random(Number seed) { 
deba@2242
   544
      _random_bits::Initializer<Number, Word>::init(core, seed);
deba@2242
   545
    }
deba@2242
   546
deba@2242
   547
    /// \brief Constructor
deba@2242
   548
    ///
deba@2242
   549
    /// Constructor with array seeding. The given range should contain
deba@2242
   550
    /// any number type and the numbers will be converted to the
deba@2242
   551
    /// architecture word type.
deba@2242
   552
    template <typename Iterator>
deba@2242
   553
    Random(Iterator begin, Iterator end) { 
deba@2242
   554
      typedef typename std::iterator_traits<Iterator>::value_type Number;
deba@2242
   555
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
deba@2242
   556
    }
deba@2229
   557
deba@2229
   558
    /// \brief Copy constructor
deba@2229
   559
    ///
deba@2229
   560
    /// Copy constructor. The generated sequence will be identical to
deba@2245
   561
    /// the other sequence. It can be used to save the current state
deba@2245
   562
    /// of the generator and later use it to generate the same
deba@2245
   563
    /// sequence.
deba@2242
   564
    Random(const Random& other) {
deba@2242
   565
      core.copyState(other.core);
deba@2229
   566
    }
deba@2229
   567
deba@2229
   568
    /// \brief Assign operator
deba@2229
   569
    ///
deba@2229
   570
    /// Assign operator. The generated sequence will be identical to
deba@2245
   571
    /// the other sequence. It can be used to save the current state
deba@2245
   572
    /// of the generator and later use it to generate the same
deba@2245
   573
    /// sequence.
deba@2229
   574
    Random& operator=(const Random& other) {
deba@2229
   575
      if (&other != this) {
deba@2242
   576
        core.copyState(other.core);
deba@2229
   577
      }
deba@2229
   578
      return *this;
deba@2229
   579
    }
deba@2229
   580
alpar@2257
   581
    /// \brief Returns a random real number from the range [0, 1)
deba@2229
   582
    ///
deba@2245
   583
    /// It returns a random real number from the range [0, 1). The
deba@2245
   584
    /// default Number type is double.
deba@2242
   585
    template <typename Number>
deba@2245
   586
    Number real() {
deba@2242
   587
      return _random_bits::RealConversion<Number, Word>::convert(core);
deba@2229
   588
    }
deba@2229
   589
deba@2245
   590
    double real() {
deba@2245
   591
      return real<double>();
deba@2245
   592
    }
deba@2245
   593
alpar@2257
   594
    /// \brief Returns a random real number the range [0, b)
deba@2245
   595
    ///
deba@2245
   596
    /// It returns a random real number from the range [0, b).
deba@2245
   597
    template <typename Number>
deba@2245
   598
    Number real(Number b) { 
deba@2245
   599
      return real<Number>() * b; 
deba@2245
   600
    }
deba@2245
   601
alpar@2257
   602
    /// \brief Returns a random real number from the range [a, b)
deba@2245
   603
    ///
deba@2245
   604
    /// It returns a random real number from the range [a, b).
deba@2245
   605
    template <typename Number>
deba@2245
   606
    Number real(Number a, Number b) { 
deba@2245
   607
      return real<Number>() * (b - a) + a; 
deba@2245
   608
    }
deba@2245
   609
alpar@2257
   610
    /// \brief Returns a random real number from the range [0, 1)
deba@2245
   611
    ///
deba@2245
   612
    /// It returns a random double from the range [0, 1).
deba@2242
   613
    double operator()() {
deba@2245
   614
      return real<double>();
deba@2242
   615
    }
deba@2242
   616
alpar@2257
   617
    /// \brief Returns a random real number from the range [0, b)
deba@2229
   618
    ///
deba@2242
   619
    /// It returns a random real number from the range [0, b).
deba@2242
   620
    template <typename Number>
deba@2242
   621
    Number operator()(Number b) { 
deba@2245
   622
      return real<Number>() * b; 
deba@2242
   623
    }
deba@2242
   624
alpar@2257
   625
    /// \brief Returns a random real number from the range [a, b)
deba@2242
   626
    ///
deba@2242
   627
    /// It returns a random real number from the range [a, b).
deba@2242
   628
    template <typename Number>
deba@2242
   629
    Number operator()(Number a, Number b) { 
deba@2245
   630
      return real<Number>() * (b - a) + a; 
deba@2242
   631
    }
deba@2242
   632
deba@2242
   633
    /// \brief Returns a random integer from a range
deba@2242
   634
    ///
deba@2245
   635
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
deba@2242
   636
    template <typename Number>
deba@2245
   637
    Number integer(Number b) {
deba@2245
   638
      return _random_bits::Mapping<Number, Word>::map(core, b);
deba@2245
   639
    }
deba@2245
   640
deba@2245
   641
    /// \brief Returns a random integer from a range
deba@2245
   642
    ///
deba@2245
   643
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
deba@2245
   644
    template <typename Number>
deba@2245
   645
    Number integer(Number a, Number b) {
deba@2245
   646
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
deba@2245
   647
    }
deba@2245
   648
deba@2245
   649
    /// \brief Returns a random integer from a range
deba@2245
   650
    ///
deba@2245
   651
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
deba@2245
   652
    template <typename Number>
deba@2245
   653
    Number operator[](Number b) {
deba@2245
   654
      return _random_bits::Mapping<Number, Word>::map(core, b);
deba@2242
   655
    }
deba@2242
   656
deba@2242
   657
    /// \brief Returns a random non-negative integer
deba@2242
   658
    ///
deba@2242
   659
    /// It returns a random non-negative integer uniformly from the
deba@2242
   660
    /// whole range of the current \c Number type.  The default result
deba@2242
   661
    /// type of this function is unsigned int.
deba@2242
   662
    template <typename Number>
deba@2242
   663
    Number uinteger() {
deba@2242
   664
      return _random_bits::IntConversion<Number, Word>::convert(core);
deba@2242
   665
    }
deba@2242
   666
deba@2242
   667
    unsigned int uinteger() {
deba@2242
   668
      return uinteger<unsigned int>();
deba@2242
   669
    }
deba@2242
   670
deba@2242
   671
    /// \brief Returns a random integer
deba@2242
   672
    ///
deba@2242
   673
    /// It returns a random integer uniformly from the whole range of
deba@2242
   674
    /// the current \c Number type. The default result type of this
deba@2242
   675
    /// function is int.
deba@2242
   676
    template <typename Number>
deba@2242
   677
    Number integer() {
deba@2242
   678
      static const int nb = std::numeric_limits<Number>::digits + 
deba@2242
   679
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
deba@2242
   680
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
deba@2242
   681
    }
deba@2242
   682
deba@2242
   683
    int integer() {
deba@2242
   684
      return integer<int>();
deba@2229
   685
    }
deba@2229
   686
    
deba@2242
   687
    /// \brief Returns a random bool
deba@2229
   688
    ///
deba@2372
   689
    /// It returns a random bool. The generator holds a buffer for
deba@2372
   690
    /// random bits. Every time when it become empty the generator makes
deba@2372
   691
    /// a new random word and fill the buffer up.
deba@2242
   692
    bool boolean() {
deba@2372
   693
      return bool_producer.convert(core);
deba@2229
   694
    }
deba@2229
   695
alpar@2356
   696
    ///\name Nonuniform distributions
alpar@2356
   697
    ///
alpar@2356
   698
    
alpar@2356
   699
    ///@{
alpar@2356
   700
    
deba@2229
   701
    /// \brief Returns a random bool
deba@2229
   702
    ///
deba@2242
   703
    /// It returns a random bool with given probability of true result
deba@2242
   704
    bool boolean(double p) {
deba@2242
   705
      return operator()() < p;
deba@2229
   706
    }
alpar@2355
   707
alpar@2355
   708
    /// Standard Gauss distribution
alpar@2355
   709
alpar@2355
   710
    /// Standard Gauss distribution.
alpar@2356
   711
    /// \note The Cartesian form of the Box-Muller
alpar@2356
   712
    /// transformation is used to generate a random normal distribution.
alpar@2356
   713
    /// \todo Consider using the "ziggurat" method instead.
alpar@2355
   714
    double gauss() 
alpar@2355
   715
    {
alpar@2355
   716
      double V1,V2,S;
alpar@2355
   717
      do {
alpar@2355
   718
	V1=2*real<double>()-1;
alpar@2355
   719
	V2=2*real<double>()-1;
alpar@2355
   720
	S=V1*V1+V2*V2;
alpar@2355
   721
      } while(S>=1);
alpar@2355
   722
      return std::sqrt(-2*std::log(S)/S)*V1;
alpar@2355
   723
    }
alpar@2356
   724
    /// Gauss distribution with given standard deviation and mean 0
alpar@2356
   725
alpar@2356
   726
    /// \sa gauss()
alpar@2356
   727
    ///
alpar@2356
   728
    double gauss(double std_dev) 
alpar@2355
   729
    {
alpar@2356
   730
      return gauss()*std_dev;
alpar@2355
   731
    }
alpar@2356
   732
    /// Gauss distribution with given mean and standard deviation
alpar@2356
   733
alpar@2356
   734
    /// \sa gauss()
alpar@2356
   735
    ///
alpar@2356
   736
    double gauss(double mean,double std_dev)
alpar@2355
   737
    {
alpar@2356
   738
      return gauss()*std_dev+mean;
alpar@2355
   739
    }
alpar@2355
   740
alpar@2356
   741
    /// Exponential distribution with given mean
alpar@2356
   742
alpar@2356
   743
    /// This function generates an exponential distribution random number
alpar@2356
   744
    /// with mean <tt>1/lambda</tt>.
alpar@2356
   745
    ///
alpar@2356
   746
    double exponential(double lambda=1.0)
alpar@2355
   747
    {
alpar@2374
   748
      return -std::log(real<double>())/lambda;
alpar@2355
   749
    }
alpar@2356
   750
alpar@2483
   751
    double gamma(int k) 
alpar@2483
   752
    {
alpar@2483
   753
      double s = 0;
alpar@2483
   754
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
alpar@2483
   755
      return s;
alpar@2483
   756
    }
alpar@2483
   757
    
alpar@2483
   758
    /// Gamma distribution with given shape and scale parameter
alpar@2483
   759
alpar@2483
   760
    /// This function generates a gamma distribution random number.
alpar@2483
   761
    /// 
alpar@2483
   762
    ///\param k shape parameter (<tt>k>0</tt>)
alpar@2483
   763
    ///\param theta scale parameter
alpar@2483
   764
    ///
alpar@2483
   765
    double gamma(double k,double theta=1.0)
alpar@2483
   766
    {
alpar@2483
   767
      double xi,nu;
alpar@2483
   768
      const double delta = k-std::floor(k);
alpar@2568
   769
      const double v0=E/(E-delta);
alpar@2483
   770
      do {
alpar@2483
   771
	double V0=1.0-real<double>();
alpar@2483
   772
	double V1=1.0-real<double>();
alpar@2483
   773
	double V2=1.0-real<double>();
alpar@2483
   774
	if(V2<=v0) 
alpar@2483
   775
	  {
alpar@2483
   776
	    xi=std::pow(V1,1.0/delta);
alpar@2483
   777
	    nu=V0*std::pow(xi,delta-1.0);
alpar@2483
   778
	  }
alpar@2483
   779
	else 
alpar@2483
   780
	  {
alpar@2483
   781
	    xi=1.0-std::log(V1);
alpar@2483
   782
	    nu=V0*std::exp(-xi);
alpar@2483
   783
	  }
alpar@2483
   784
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
alpar@2483
   785
      return theta*(xi-gamma(int(std::floor(k))));
alpar@2483
   786
    }
alpar@2483
   787
    
alpar@2483
   788
      
alpar@2356
   789
    ///@}
deba@2229
   790
    
alpar@2374
   791
    ///\name Two dimensional distributions
alpar@2374
   792
    ///
alpar@2374
   793
alpar@2374
   794
    ///@{
alpar@2374
   795
    
alpar@2374
   796
    /// Uniform distribution on the full unit circle.
alpar@2380
   797
    dim2::Point<double> disc() 
alpar@2374
   798
    {
alpar@2374
   799
      double V1,V2;
alpar@2374
   800
      do {
alpar@2374
   801
	V1=2*real<double>()-1;
alpar@2374
   802
	V2=2*real<double>()-1;
alpar@2374
   803
	
alpar@2374
   804
      } while(V1*V1+V2*V2>=1);
alpar@2374
   805
      return dim2::Point<double>(V1,V2);
alpar@2374
   806
    }
alpar@2374
   807
    /// A kind of two dimensional Gauss distribution
alpar@2374
   808
alpar@2374
   809
    /// This function provides a turning symmetric two-dimensional distribution.
alpar@2374
   810
    /// Both coordinates are of standard normal distribution, but they are not
alpar@2374
   811
    /// independent.
alpar@2374
   812
    ///
alpar@2374
   813
    /// \note The coordinates are the two random variables provided by
alpar@2374
   814
    /// the Box-Muller method.
alpar@2374
   815
    dim2::Point<double> gauss2()
alpar@2374
   816
    {
alpar@2374
   817
      double V1,V2,S;
alpar@2374
   818
      do {
alpar@2374
   819
	V1=2*real<double>()-1;
alpar@2374
   820
	V2=2*real<double>()-1;
alpar@2374
   821
	S=V1*V1+V2*V2;
alpar@2374
   822
      } while(S>=1);
alpar@2374
   823
      double W=std::sqrt(-2*std::log(S)/S);
alpar@2374
   824
      return dim2::Point<double>(W*V1,W*V2);
alpar@2374
   825
    }
alpar@2374
   826
    /// A kind of two dimensional exponential distribution
alpar@2374
   827
alpar@2374
   828
    /// This function provides a turning symmetric two-dimensional distribution.
alpar@2374
   829
    /// The x-coordinate is of conditionally exponential distribution
alpar@2374
   830
    /// with the condition that x is positive and y=0. If x is negative and 
alpar@2374
   831
    /// y=0 then, -x is of exponential distribution. The same is true for the
alpar@2374
   832
    /// y-coordinate.
alpar@2374
   833
    dim2::Point<double> exponential2() 
alpar@2374
   834
    {
alpar@2374
   835
      double V1,V2,S;
alpar@2374
   836
      do {
alpar@2374
   837
	V1=2*real<double>()-1;
alpar@2374
   838
	V2=2*real<double>()-1;
alpar@2374
   839
	S=V1*V1+V2*V2;
alpar@2374
   840
      } while(S>=1);
alpar@2374
   841
      double W=-std::log(S)/S;
alpar@2374
   842
      return dim2::Point<double>(W*V1,W*V2);
alpar@2374
   843
    }
alpar@2374
   844
alpar@2374
   845
    ///@}    
deba@2229
   846
  };
deba@2229
   847
deba@2229
   848
deba@2229
   849
  extern Random rnd;
deba@2229
   850
deba@2229
   851
}
deba@2229
   852
deba@2229
   853
#endif