lemon/random.h
author Alpar Juttner <alpar@cs.elte.hu>
Thu, 25 Feb 2021 09:46:12 +0100
changeset 1209 4a170261cc54
parent 1164 04f57dad1b07
parent 1178 61fdd06833a6
permissions -rw-r--r--
Merge #638
alpar@209
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
alpar@10
     2
 *
alpar@209
     3
 * This file is a part of LEMON, a generic C++ optimization library.
alpar@10
     4
 *
alpar@440
     5
 * Copyright (C) 2003-2009
alpar@10
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@10
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@10
     8
 *
alpar@10
     9
 * Permission to use, modify and distribute this software is granted
alpar@10
    10
 * provided that this copyright notice appears in all copies. For
alpar@10
    11
 * precise terms see the accompanying LICENSE file.
alpar@10
    12
 *
alpar@10
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@10
    14
 * express or implied, and with no claim as to its suitability for any
alpar@10
    15
 * purpose.
alpar@10
    16
 *
alpar@10
    17
 */
alpar@10
    18
alpar@10
    19
/*
alpar@10
    20
 * This file contains the reimplemented version of the Mersenne Twister
alpar@10
    21
 * Generator of Matsumoto and Nishimura.
alpar@10
    22
 *
alpar@10
    23
 * See the appropriate copyright notice below.
alpar@209
    24
 *
alpar@10
    25
 * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
alpar@209
    26
 * All rights reserved.
alpar@10
    27
 *
alpar@10
    28
 * Redistribution and use in source and binary forms, with or without
alpar@10
    29
 * modification, are permitted provided that the following conditions
alpar@10
    30
 * are met:
alpar@10
    31
 *
alpar@10
    32
 * 1. Redistributions of source code must retain the above copyright
alpar@10
    33
 *    notice, this list of conditions and the following disclaimer.
alpar@10
    34
 *
alpar@10
    35
 * 2. Redistributions in binary form must reproduce the above copyright
alpar@10
    36
 *    notice, this list of conditions and the following disclaimer in the
alpar@10
    37
 *    documentation and/or other materials provided with the distribution.
alpar@10
    38
 *
alpar@209
    39
 * 3. The names of its contributors may not be used to endorse or promote
alpar@209
    40
 *    products derived from this software without specific prior written
alpar@10
    41
 *    permission.
alpar@10
    42
 *
alpar@10
    43
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
alpar@10
    44
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
alpar@10
    45
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
alpar@10
    46
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
alpar@10
    47
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
alpar@10
    48
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
alpar@10
    49
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
alpar@10
    50
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
alpar@10
    51
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
alpar@10
    52
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
alpar@10
    53
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
alpar@10
    54
 * OF THE POSSIBILITY OF SUCH DAMAGE.
alpar@10
    55
 *
alpar@10
    56
 *
alpar@10
    57
 * Any feedback is very welcome.
alpar@10
    58
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
alpar@10
    59
 * email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
alpar@10
    60
 */
alpar@10
    61
alpar@10
    62
#ifndef LEMON_RANDOM_H
alpar@10
    63
#define LEMON_RANDOM_H
alpar@10
    64
alpar@1134
    65
#include <lemon/config.h>
alpar@1134
    66
alpar@10
    67
#include <algorithm>
alpar@10
    68
#include <iterator>
alpar@10
    69
#include <vector>
deba@110
    70
#include <limits>
deba@177
    71
#include <fstream>
alpar@10
    72
alpar@68
    73
#include <lemon/math.h>
alpar@10
    74
#include <lemon/dim2.h>
alpar@68
    75
alpar@1134
    76
#ifndef LEMON_WIN32
deba@177
    77
#include <sys/time.h>
deba@177
    78
#include <ctime>
deba@177
    79
#include <sys/types.h>
deba@177
    80
#include <unistd.h>
deba@177
    81
#else
alpar@491
    82
#include <lemon/bits/windows.h>
deba@177
    83
#endif
deba@177
    84
alpar@10
    85
///\ingroup misc
alpar@10
    86
///\file
alpar@10
    87
///\brief Mersenne Twister random number generator
alpar@10
    88
alpar@10
    89
namespace lemon {
alpar@10
    90
alpar@10
    91
  namespace _random_bits {
alpar@209
    92
alpar@10
    93
    template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
alpar@10
    94
    struct RandomTraits {};
alpar@10
    95
alpar@10
    96
    template <typename _Word>
alpar@10
    97
    struct RandomTraits<_Word, 32> {
alpar@10
    98
alpar@10
    99
      typedef _Word Word;
alpar@10
   100
      static const int bits = 32;
alpar@10
   101
alpar@10
   102
      static const int length = 624;
alpar@10
   103
      static const int shift = 397;
alpar@209
   104
alpar@10
   105
      static const Word mul = 0x6c078965u;
alpar@10
   106
      static const Word arrayInit = 0x012BD6AAu;
alpar@10
   107
      static const Word arrayMul1 = 0x0019660Du;
alpar@10
   108
      static const Word arrayMul2 = 0x5D588B65u;
alpar@10
   109
alpar@10
   110
      static const Word mask = 0x9908B0DFu;
alpar@10
   111
      static const Word loMask = (1u << 31) - 1;
alpar@10
   112
      static const Word hiMask = ~loMask;
alpar@10
   113
alpar@10
   114
      static Word tempering(Word rnd) {
alpar@10
   115
        rnd ^= (rnd >> 11);
alpar@10
   116
        rnd ^= (rnd << 7) & 0x9D2C5680u;
alpar@10
   117
        rnd ^= (rnd << 15) & 0xEFC60000u;
alpar@10
   118
        rnd ^= (rnd >> 18);
alpar@10
   119
        return rnd;
alpar@10
   120
      }
alpar@10
   121
alpar@10
   122
    };
alpar@10
   123
alpar@10
   124
    template <typename _Word>
alpar@10
   125
    struct RandomTraits<_Word, 64> {
alpar@10
   126
alpar@10
   127
      typedef _Word Word;
alpar@10
   128
      static const int bits = 64;
alpar@10
   129
alpar@10
   130
      static const int length = 312;
alpar@10
   131
      static const int shift = 156;
alpar@10
   132
alpar@10
   133
      static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
alpar@10
   134
      static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
alpar@10
   135
      static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
alpar@10
   136
      static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
alpar@10
   137
alpar@10
   138
      static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
alpar@10
   139
      static const Word loMask = (Word(1u) << 31) - 1;
alpar@10
   140
      static const Word hiMask = ~loMask;
alpar@10
   141
alpar@10
   142
      static Word tempering(Word rnd) {
alpar@10
   143
        rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
alpar@10
   144
        rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
alpar@10
   145
        rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u));
alpar@10
   146
        rnd ^= (rnd >> 43);
alpar@10
   147
        return rnd;
alpar@10
   148
      }
alpar@10
   149
alpar@10
   150
    };
alpar@10
   151
alpar@10
   152
    template <typename _Word>
alpar@10
   153
    class RandomCore {
alpar@10
   154
    public:
alpar@10
   155
alpar@10
   156
      typedef _Word Word;
alpar@10
   157
alpar@10
   158
    private:
alpar@10
   159
alpar@10
   160
      static const int bits = RandomTraits<Word>::bits;
alpar@10
   161
alpar@10
   162
      static const int length = RandomTraits<Word>::length;
alpar@10
   163
      static const int shift = RandomTraits<Word>::shift;
alpar@10
   164
alpar@10
   165
    public:
alpar@10
   166
alpar@10
   167
      void initState() {
alpar@10
   168
        static const Word seedArray[4] = {
alpar@10
   169
          0x12345u, 0x23456u, 0x34567u, 0x45678u
alpar@10
   170
        };
alpar@209
   171
alpar@10
   172
        initState(seedArray, seedArray + 4);
alpar@10
   173
      }
alpar@10
   174
alpar@10
   175
      void initState(Word seed) {
alpar@10
   176
alpar@10
   177
        static const Word mul = RandomTraits<Word>::mul;
alpar@10
   178
alpar@209
   179
        current = state;
alpar@10
   180
alpar@10
   181
        Word *curr = state + length - 1;
alpar@10
   182
        curr[0] = seed; --curr;
alpar@10
   183
        for (int i = 1; i < length; ++i) {
alpar@10
   184
          curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
alpar@10
   185
          --curr;
alpar@10
   186
        }
alpar@10
   187
      }
alpar@10
   188
alpar@10
   189
      template <typename Iterator>
alpar@10
   190
      void initState(Iterator begin, Iterator end) {
alpar@10
   191
alpar@10
   192
        static const Word init = RandomTraits<Word>::arrayInit;
alpar@10
   193
        static const Word mul1 = RandomTraits<Word>::arrayMul1;
alpar@10
   194
        static const Word mul2 = RandomTraits<Word>::arrayMul2;
alpar@10
   195
alpar@10
   196
alpar@10
   197
        Word *curr = state + length - 1; --curr;
alpar@10
   198
        Iterator it = begin; int cnt = 0;
alpar@10
   199
        int num;
alpar@10
   200
alpar@10
   201
        initState(init);
alpar@10
   202
alpar@1124
   203
        num = static_cast<int>(length > end - begin ? length : end - begin);
alpar@10
   204
        while (num--) {
alpar@209
   205
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1))
alpar@10
   206
            + *it + cnt;
alpar@10
   207
          ++it; ++cnt;
alpar@10
   208
          if (it == end) {
alpar@10
   209
            it = begin; cnt = 0;
alpar@10
   210
          }
alpar@10
   211
          if (curr == state) {
alpar@10
   212
            curr = state + length - 1; curr[0] = state[0];
alpar@10
   213
          }
alpar@10
   214
          --curr;
alpar@10
   215
        }
alpar@10
   216
alpar@1124
   217
        num = length - 1; cnt = static_cast<int>(length - (curr - state) - 1);
alpar@10
   218
        while (num--) {
alpar@10
   219
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
alpar@10
   220
            - cnt;
alpar@10
   221
          --curr; ++cnt;
alpar@10
   222
          if (curr == state) {
alpar@10
   223
            curr = state + length - 1; curr[0] = state[0]; --curr;
alpar@10
   224
            cnt = 1;
alpar@10
   225
          }
alpar@10
   226
        }
alpar@209
   227
alpar@10
   228
        state[length - 1] = Word(1) << (bits - 1);
alpar@10
   229
      }
alpar@209
   230
alpar@10
   231
      void copyState(const RandomCore& other) {
alpar@10
   232
        std::copy(other.state, other.state + length, state);
alpar@10
   233
        current = state + (other.current - other.state);
alpar@10
   234
      }
alpar@10
   235
alpar@10
   236
      Word operator()() {
alpar@10
   237
        if (current == state) fillState();
alpar@10
   238
        --current;
alpar@10
   239
        Word rnd = *current;
alpar@10
   240
        return RandomTraits<Word>::tempering(rnd);
alpar@10
   241
      }
alpar@10
   242
alpar@10
   243
    private:
alpar@10
   244
alpar@10
   245
      void fillState() {
alpar@10
   246
        static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
alpar@10
   247
        static const Word loMask = RandomTraits<Word>::loMask;
alpar@10
   248
        static const Word hiMask = RandomTraits<Word>::hiMask;
alpar@10
   249
alpar@209
   250
        current = state + length;
alpar@10
   251
alpar@1132
   252
        Word *curr = state + length - 1;
alpar@1132
   253
        long num;
alpar@209
   254
alpar@10
   255
        num = length - shift;
alpar@10
   256
        while (num--) {
alpar@10
   257
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
alpar@10
   258
            curr[- shift] ^ mask[curr[-1] & 1ul];
alpar@10
   259
          --curr;
alpar@10
   260
        }
alpar@10
   261
        num = shift - 1;
alpar@10
   262
        while (num--) {
alpar@10
   263
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
alpar@10
   264
            curr[length - shift] ^ mask[curr[-1] & 1ul];
alpar@10
   265
          --curr;
alpar@10
   266
        }
deba@62
   267
        state[0] = (((state[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
alpar@10
   268
          curr[length - shift] ^ mask[curr[length - 1] & 1ul];
alpar@10
   269
alpar@10
   270
      }
alpar@10
   271
alpar@10
   272
      Word *current;
alpar@10
   273
      Word state[length];
alpar@209
   274
alpar@10
   275
    };
alpar@10
   276
alpar@10
   277
alpar@209
   278
    template <typename Result,
alpar@10
   279
              int shift = (std::numeric_limits<Result>::digits + 1) / 2>
alpar@10
   280
    struct Masker {
alpar@10
   281
      static Result mask(const Result& result) {
alpar@10
   282
        return Masker<Result, (shift + 1) / 2>::
alpar@10
   283
          mask(static_cast<Result>(result | (result >> shift)));
alpar@10
   284
      }
alpar@10
   285
    };
alpar@209
   286
alpar@10
   287
    template <typename Result>
alpar@10
   288
    struct Masker<Result, 1> {
alpar@10
   289
      static Result mask(const Result& result) {
alpar@10
   290
        return static_cast<Result>(result | (result >> 1));
alpar@10
   291
      }
alpar@10
   292
    };
alpar@10
   293
alpar@209
   294
    template <typename Result, typename Word,
alpar@209
   295
              int rest = std::numeric_limits<Result>::digits, int shift = 0,
alpar@1163
   296
              bool last = (rest <= std::numeric_limits<Word>::digits)>
alpar@10
   297
    struct IntConversion {
alpar@10
   298
      static const int bits = std::numeric_limits<Word>::digits;
alpar@209
   299
alpar@10
   300
      static Result convert(RandomCore<Word>& rnd) {
alpar@10
   301
        return static_cast<Result>(rnd() >> (bits - rest)) << shift;
alpar@10
   302
      }
alpar@10
   303
alpar@209
   304
    };
alpar@209
   305
alpar@209
   306
    template <typename Result, typename Word, int rest, int shift>
alpar@10
   307
    struct IntConversion<Result, Word, rest, shift, false> {
alpar@10
   308
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   309
alpar@10
   310
      static Result convert(RandomCore<Word>& rnd) {
alpar@209
   311
        return (static_cast<Result>(rnd()) << shift) |
alpar@10
   312
          IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
alpar@10
   313
      }
alpar@10
   314
    };
alpar@10
   315
alpar@10
   316
alpar@10
   317
    template <typename Result, typename Word,
alpar@209
   318
              bool one_word = (std::numeric_limits<Word>::digits <
alpar@209
   319
                               std::numeric_limits<Result>::digits) >
alpar@10
   320
    struct Mapping {
alpar@10
   321
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
alpar@10
   322
        Word max = Word(bound - 1);
alpar@10
   323
        Result mask = Masker<Result>::mask(bound - 1);
alpar@10
   324
        Result num;
alpar@10
   325
        do {
alpar@209
   326
          num = IntConversion<Result, Word>::convert(rnd) & mask;
alpar@10
   327
        } while (num > max);
alpar@10
   328
        return num;
alpar@10
   329
      }
alpar@10
   330
    };
alpar@10
   331
alpar@10
   332
    template <typename Result, typename Word>
alpar@10
   333
    struct Mapping<Result, Word, false> {
alpar@10
   334
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
alpar@10
   335
        Word max = Word(bound - 1);
alpar@10
   336
        Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
alpar@10
   337
          ::mask(max);
alpar@10
   338
        Word num;
alpar@10
   339
        do {
alpar@10
   340
          num = rnd() & mask;
alpar@10
   341
        } while (num > max);
alpar@1178
   342
        return static_cast<Result>(num);
alpar@10
   343
      }
alpar@10
   344
    };
alpar@10
   345
kpeter@498
   346
    template <typename Result, int exp>
alpar@10
   347
    struct ShiftMultiplier {
alpar@10
   348
      static const Result multiplier() {
alpar@10
   349
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
alpar@10
   350
        res *= res;
alpar@10
   351
        if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
alpar@209
   352
        return res;
alpar@10
   353
      }
alpar@10
   354
    };
alpar@10
   355
alpar@10
   356
    template <typename Result>
kpeter@498
   357
    struct ShiftMultiplier<Result, 0> {
alpar@10
   358
      static const Result multiplier() {
alpar@209
   359
        return static_cast<Result>(1.0);
alpar@10
   360
      }
alpar@10
   361
    };
alpar@10
   362
alpar@10
   363
    template <typename Result>
kpeter@498
   364
    struct ShiftMultiplier<Result, 20> {
alpar@10
   365
      static const Result multiplier() {
alpar@209
   366
        return static_cast<Result>(1.0/1048576.0);
alpar@10
   367
      }
alpar@10
   368
    };
alpar@209
   369
alpar@10
   370
    template <typename Result>
kpeter@498
   371
    struct ShiftMultiplier<Result, 32> {
alpar@10
   372
      static const Result multiplier() {
kpeter@498
   373
        return static_cast<Result>(1.0/4294967296.0);
alpar@10
   374
      }
alpar@10
   375
    };
alpar@10
   376
alpar@10
   377
    template <typename Result>
kpeter@498
   378
    struct ShiftMultiplier<Result, 53> {
alpar@10
   379
      static const Result multiplier() {
alpar@209
   380
        return static_cast<Result>(1.0/9007199254740992.0);
alpar@10
   381
      }
alpar@10
   382
    };
alpar@10
   383
alpar@10
   384
    template <typename Result>
kpeter@498
   385
    struct ShiftMultiplier<Result, 64> {
alpar@10
   386
      static const Result multiplier() {
alpar@209
   387
        return static_cast<Result>(1.0/18446744073709551616.0);
alpar@10
   388
      }
alpar@10
   389
    };
alpar@10
   390
alpar@10
   391
    template <typename Result, int exp>
alpar@10
   392
    struct Shifting {
alpar@10
   393
      static Result shift(const Result& result) {
alpar@10
   394
        return result * ShiftMultiplier<Result, exp>::multiplier();
alpar@10
   395
      }
alpar@10
   396
    };
alpar@10
   397
alpar@10
   398
    template <typename Result, typename Word,
alpar@209
   399
              int rest = std::numeric_limits<Result>::digits, int shift = 0,
alpar@10
   400
              bool last = rest <= std::numeric_limits<Word>::digits>
alpar@209
   401
    struct RealConversion{
alpar@10
   402
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   403
alpar@10
   404
      static Result convert(RandomCore<Word>& rnd) {
kpeter@498
   405
        return Shifting<Result, shift + rest>::
alpar@10
   406
          shift(static_cast<Result>(rnd() >> (bits - rest)));
alpar@10
   407
      }
alpar@10
   408
    };
alpar@10
   409
alpar@10
   410
    template <typename Result, typename Word, int rest, int shift>
alpar@209
   411
    struct RealConversion<Result, Word, rest, shift, false> {
alpar@10
   412
      static const int bits = std::numeric_limits<Word>::digits;
alpar@10
   413
alpar@10
   414
      static Result convert(RandomCore<Word>& rnd) {
kpeter@498
   415
        return Shifting<Result, shift + bits>::
alpar@10
   416
          shift(static_cast<Result>(rnd())) +
alpar@10
   417
          RealConversion<Result, Word, rest-bits, shift + bits>::
alpar@10
   418
          convert(rnd);
alpar@10
   419
      }
alpar@10
   420
    };
alpar@10
   421
alpar@10
   422
    template <typename Result, typename Word>
alpar@10
   423
    struct Initializer {
alpar@10
   424
alpar@10
   425
      template <typename Iterator>
alpar@10
   426
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
alpar@10
   427
        std::vector<Word> ws;
alpar@10
   428
        for (Iterator it = begin; it != end; ++it) {
alpar@10
   429
          ws.push_back(Word(*it));
alpar@10
   430
        }
alpar@10
   431
        rnd.initState(ws.begin(), ws.end());
alpar@10
   432
      }
alpar@10
   433
alpar@10
   434
      static void init(RandomCore<Word>& rnd, Result seed) {
alpar@10
   435
        rnd.initState(seed);
alpar@10
   436
      }
alpar@10
   437
    };
alpar@10
   438
alpar@10
   439
    template <typename Word>
alpar@10
   440
    struct BoolConversion {
alpar@10
   441
      static bool convert(RandomCore<Word>& rnd) {
alpar@10
   442
        return (rnd() & 1) == 1;
alpar@10
   443
      }
alpar@10
   444
    };
alpar@10
   445
alpar@10
   446
    template <typename Word>
alpar@10
   447
    struct BoolProducer {
alpar@10
   448
      Word buffer;
alpar@10
   449
      int num;
alpar@209
   450
alpar@10
   451
      BoolProducer() : num(0) {}
alpar@10
   452
alpar@10
   453
      bool convert(RandomCore<Word>& rnd) {
alpar@10
   454
        if (num == 0) {
alpar@10
   455
          buffer = rnd();
alpar@10
   456
          num = RandomTraits<Word>::bits;
alpar@10
   457
        }
alpar@10
   458
        bool r = (buffer & 1);
alpar@10
   459
        buffer >>= 1;
alpar@10
   460
        --num;
alpar@10
   461
        return r;
alpar@10
   462
      }
alpar@10
   463
    };
alpar@10
   464
alpar@1163
   465
    /// \ingroup misc
alpar@1163
   466
    ///
alpar@1163
   467
    /// \brief Mersenne Twister random number generator
alpar@1163
   468
    ///
alpar@1163
   469
    /// The Mersenne Twister is a twisted generalized feedback
alpar@1163
   470
    /// shift-register generator of Matsumoto and Nishimura. The period
kpeter@1164
   471
    /// of this generator is \f$ 2^{19937} - 1\f$ and it is
alpar@1163
   472
    /// equi-distributed in 623 dimensions for 32-bit numbers. The time
alpar@1163
   473
    /// performance of this generator is comparable to the commonly used
alpar@1163
   474
    /// generators.
alpar@1163
   475
    ///
kpeter@1164
   476
    /// This is a template implementation of both 32-bit and
alpar@1163
   477
    /// 64-bit architecture optimized versions. The generators differ
alpar@1163
   478
    /// sligthly in the initialization and generation phase so they
alpar@1163
   479
    /// produce two completly different sequences.
alpar@1163
   480
    ///
alpar@1163
   481
    /// \alert Do not use this class directly, but instead one of \ref
alpar@1163
   482
    /// Random, \ref Random32 or \ref Random64.
alpar@1163
   483
    ///
alpar@1163
   484
    /// The generator gives back random numbers of serveral types. To
kpeter@1164
   485
    /// get a random number from a range of a floating point type, you
alpar@1163
   486
    /// can use one form of the \c operator() or the \c real() member
alpar@1163
   487
    /// function. If you want to get random number from the {0, 1, ...,
kpeter@1164
   488
    /// n-1} integer range, use the \c operator[] or the \c integer()
alpar@1163
   489
    /// method. And to get random number from the whole range of an
kpeter@1164
   490
    /// integer type, you can use the argumentless \c integer() or
kpeter@1164
   491
    /// \c uinteger() functions. Finally, you can get random bool with
kpeter@1164
   492
    /// equal chance of true and false or with given probability of true
kpeter@1164
   493
    /// result using the \c boolean() member functions.
kpeter@1164
   494
    ///
kpeter@1164
   495
    /// Various non-uniform distributions are also supported: normal (Gauss),
kpeter@1164
   496
    /// exponential, gamma, Poisson, etc.; and a few two-dimensional
kpeter@1164
   497
    /// distributions, too.
alpar@1163
   498
    ///
alpar@1163
   499
    ///\code
alpar@1163
   500
    /// // The commented code is identical to the other
alpar@1163
   501
    /// double a = rnd();                     // [0.0, 1.0)
alpar@1163
   502
    /// // double a = rnd.real();             // [0.0, 1.0)
alpar@1163
   503
    /// double b = rnd(100.0);                // [0.0, 100.0)
alpar@1163
   504
    /// // double b = rnd.real(100.0);        // [0.0, 100.0)
alpar@1163
   505
    /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
alpar@1163
   506
    /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
alpar@1163
   507
    /// int d = rnd[100000];                  // 0..99999
alpar@1163
   508
    /// // int d = rnd.integer(100000);       // 0..99999
alpar@1163
   509
    /// int e = rnd[6] + 1;                   // 1..6
alpar@1163
   510
    /// // int e = rnd.integer(1, 1 + 6);     // 1..6
alpar@1163
   511
    /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
alpar@1163
   512
    /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
alpar@1163
   513
    /// bool g = rnd.boolean();               // P(g = true) = 0.5
alpar@1163
   514
    /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
alpar@1163
   515
    ///\endcode
alpar@1163
   516
    ///
kpeter@1164
   517
    /// LEMON provides a global instance of the random number generator:
kpeter@1164
   518
    /// \ref lemon::rnd "rnd". In most cases, it is a good practice
kpeter@1164
   519
    /// to use this global generator to get random numbers.
alpar@1163
   520
    ///
alpar@1163
   521
    /// \sa \ref Random, \ref Random32 or \ref Random64.
alpar@1163
   522
    template<class Word>
alpar@1163
   523
    class Random {
alpar@1163
   524
    private:
alpar@1163
   525
alpar@1163
   526
      _random_bits::RandomCore<Word> core;
alpar@1163
   527
      _random_bits::BoolProducer<Word> bool_producer;
alpar@1163
   528
alpar@1163
   529
alpar@1163
   530
    public:
alpar@1163
   531
alpar@1163
   532
      ///\name Initialization
alpar@1163
   533
      ///
alpar@1163
   534
      /// @{
alpar@1163
   535
alpar@1163
   536
      /// \brief Default constructor
alpar@1163
   537
      ///
alpar@1163
   538
      /// Constructor with constant seeding.
alpar@1163
   539
      Random() { core.initState(); }
alpar@1163
   540
alpar@1163
   541
      /// \brief Constructor with seed
alpar@1163
   542
      ///
alpar@1163
   543
      /// Constructor with seed. The current number type will be converted
alpar@1163
   544
      /// to the architecture word type.
alpar@1163
   545
      template <typename Number>
alpar@1163
   546
      Random(Number seed) {
alpar@1163
   547
        _random_bits::Initializer<Number, Word>::init(core, seed);
alpar@1163
   548
      }
alpar@1163
   549
alpar@1163
   550
      /// \brief Constructor with array seeding
alpar@1163
   551
      ///
alpar@1163
   552
      /// Constructor with array seeding. The given range should contain
alpar@1163
   553
      /// any number type and the numbers will be converted to the
alpar@1163
   554
      /// architecture word type.
alpar@1163
   555
      template <typename Iterator>
alpar@1163
   556
      Random(Iterator begin, Iterator end) {
alpar@1163
   557
        typedef typename std::iterator_traits<Iterator>::value_type Number;
alpar@1163
   558
        _random_bits::Initializer<Number, Word>::init(core, begin, end);
alpar@1163
   559
      }
alpar@1163
   560
alpar@1163
   561
      /// \brief Copy constructor
alpar@1163
   562
      ///
alpar@1163
   563
      /// Copy constructor. The generated sequence will be identical to
alpar@1163
   564
      /// the other sequence. It can be used to save the current state
alpar@1163
   565
      /// of the generator and later use it to generate the same
alpar@1163
   566
      /// sequence.
alpar@1163
   567
      Random(const Random& other) {
alpar@1163
   568
        core.copyState(other.core);
alpar@1163
   569
      }
alpar@1163
   570
alpar@1163
   571
      /// \brief Assign operator
alpar@1163
   572
      ///
alpar@1163
   573
      /// Assign operator. The generated sequence will be identical to
alpar@1163
   574
      /// the other sequence. It can be used to save the current state
alpar@1163
   575
      /// of the generator and later use it to generate the same
alpar@1163
   576
      /// sequence.
alpar@1163
   577
      Random& operator=(const Random& other) {
alpar@1163
   578
        if (&other != this) {
alpar@1163
   579
          core.copyState(other.core);
alpar@1163
   580
        }
alpar@1163
   581
        return *this;
alpar@1163
   582
      }
alpar@1163
   583
alpar@1163
   584
      /// \brief Seeding random sequence
alpar@1163
   585
      ///
alpar@1163
   586
      /// Seeding the random sequence. The current number type will be
alpar@1163
   587
      /// converted to the architecture word type.
alpar@1163
   588
      template <typename Number>
alpar@1163
   589
      void seed(Number seed) {
alpar@1163
   590
        _random_bits::Initializer<Number, Word>::init(core, seed);
alpar@1163
   591
      }
alpar@1163
   592
alpar@1163
   593
      /// \brief Seeding random sequence
alpar@1163
   594
      ///
alpar@1163
   595
      /// Seeding the random sequence. The given range should contain
alpar@1163
   596
      /// any number type and the numbers will be converted to the
alpar@1163
   597
      /// architecture word type.
alpar@1163
   598
      template <typename Iterator>
alpar@1163
   599
      void seed(Iterator begin, Iterator end) {
alpar@1163
   600
        typedef typename std::iterator_traits<Iterator>::value_type Number;
alpar@1163
   601
        _random_bits::Initializer<Number, Word>::init(core, begin, end);
alpar@1163
   602
      }
alpar@1163
   603
alpar@1163
   604
      /// \brief Seeding from file or from process id and time
alpar@1163
   605
      ///
alpar@1163
   606
      /// By default, this function calls the \c seedFromFile() member
alpar@1163
   607
      /// function with the <tt>/dev/urandom</tt> file. If it does not success,
alpar@1163
   608
      /// it uses the \c seedFromTime().
alpar@1163
   609
      /// \return Currently always \c true.
alpar@1163
   610
      bool seed() {
alpar@1163
   611
#ifndef LEMON_WIN32
alpar@1163
   612
        if (seedFromFile("/dev/urandom", 0)) return true;
alpar@1163
   613
#endif
alpar@1163
   614
        if (seedFromTime()) return true;
alpar@1163
   615
        return false;
alpar@1163
   616
      }
alpar@1163
   617
alpar@1163
   618
      /// \brief Seeding from file
alpar@1163
   619
      ///
alpar@1163
   620
      /// Seeding the random sequence from file. The linux kernel has two
alpar@1163
   621
      /// devices, <tt>/dev/random</tt> and <tt>/dev/urandom</tt> which
alpar@1163
   622
      /// could give good seed values for pseudo random generators (The
alpar@1163
   623
      /// difference between two devices is that the <tt>random</tt> may
alpar@1163
   624
      /// block the reading operation while the kernel can give good
alpar@1163
   625
      /// source of randomness, while the <tt>urandom</tt> does not
alpar@1163
   626
      /// block the input, but it could give back bytes with worse
alpar@1163
   627
      /// entropy).
alpar@1163
   628
      /// \param file The source file
alpar@1163
   629
      /// \param offset The offset, from the file read.
alpar@1163
   630
      /// \return \c true when the seeding successes.
alpar@1163
   631
#ifndef LEMON_WIN32
alpar@1163
   632
      bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0)
alpar@1163
   633
#else
alpar@1163
   634
        bool seedFromFile(const std::string& file = "", int offset = 0)
alpar@1163
   635
#endif
alpar@1163
   636
      {
alpar@1163
   637
        std::ifstream rs(file.c_str());
alpar@1163
   638
        const int size = 4;
alpar@1163
   639
        Word buf[size];
alpar@1163
   640
        if (offset != 0 && !rs.seekg(offset)) return false;
alpar@1163
   641
        if (!rs.read(reinterpret_cast<char*>(buf), sizeof(buf))) return false;
alpar@1163
   642
        seed(buf, buf + size);
alpar@1163
   643
        return true;
alpar@1163
   644
      }
alpar@1163
   645
kpeter@1164
   646
      /// \brief Seeding from process id and time
alpar@1163
   647
      ///
kpeter@1164
   648
      /// Seeding from process id and time. This function uses the
alpar@1163
   649
      /// current process id and the current time for initialize the
alpar@1163
   650
      /// random sequence.
alpar@1163
   651
      /// \return Currently always \c true.
alpar@1163
   652
      bool seedFromTime() {
alpar@1163
   653
#ifndef LEMON_WIN32
alpar@1163
   654
        timeval tv;
alpar@1163
   655
        gettimeofday(&tv, 0);
alpar@1163
   656
        seed(getpid() + tv.tv_sec + tv.tv_usec);
alpar@1163
   657
#else
alpar@1163
   658
        seed(bits::getWinRndSeed());
alpar@1163
   659
#endif
alpar@1163
   660
        return true;
alpar@1163
   661
      }
alpar@1163
   662
alpar@1163
   663
      /// @}
alpar@1163
   664
alpar@1163
   665
      ///\name Uniform Distributions
alpar@1163
   666
      ///
alpar@1163
   667
      /// @{
alpar@1163
   668
alpar@1163
   669
      /// \brief Returns a random real number from the range [0, 1)
alpar@1163
   670
      ///
alpar@1163
   671
      /// It returns a random real number from the range [0, 1). The
alpar@1163
   672
      /// default Number type is \c double.
alpar@1163
   673
      template <typename Number>
alpar@1163
   674
      Number real() {
alpar@1163
   675
        return _random_bits::RealConversion<Number, Word>::convert(core);
alpar@1163
   676
      }
alpar@1163
   677
alpar@1163
   678
      double real() {
alpar@1163
   679
        return real<double>();
alpar@1163
   680
      }
alpar@1163
   681
alpar@1163
   682
      /// \brief Returns a random real number from the range [0, 1)
alpar@1163
   683
      ///
alpar@1163
   684
      /// It returns a random double from the range [0, 1).
alpar@1163
   685
      double operator()() {
alpar@1163
   686
        return real<double>();
alpar@1163
   687
      }
alpar@1163
   688
alpar@1163
   689
      /// \brief Returns a random real number from the range [0, b)
alpar@1163
   690
      ///
alpar@1163
   691
      /// It returns a random real number from the range [0, b).
alpar@1163
   692
      double operator()(double b) {
alpar@1163
   693
        return real<double>() * b;
alpar@1163
   694
      }
alpar@1163
   695
alpar@1163
   696
      /// \brief Returns a random real number from the range [a, b)
alpar@1163
   697
      ///
alpar@1163
   698
      /// It returns a random real number from the range [a, b).
alpar@1163
   699
      double operator()(double a, double b) {
alpar@1163
   700
        return real<double>() * (b - a) + a;
alpar@1163
   701
      }
alpar@1163
   702
alpar@1163
   703
      /// \brief Returns a random integer from a range
alpar@1163
   704
      ///
alpar@1163
   705
      /// It returns a random integer from the range {0, 1, ..., b - 1}.
alpar@1163
   706
      template <typename Number>
alpar@1163
   707
      Number integer(Number b) {
alpar@1163
   708
        return _random_bits::Mapping<Number, Word>::map(core, b);
alpar@1163
   709
      }
alpar@1163
   710
alpar@1163
   711
      /// \brief Returns a random integer from a range
alpar@1163
   712
      ///
alpar@1163
   713
      /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
alpar@1163
   714
      template <typename Number>
alpar@1163
   715
      Number integer(Number a, Number b) {
alpar@1163
   716
        return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
alpar@1163
   717
      }
alpar@1163
   718
alpar@1163
   719
      /// \brief Returns a random integer from a range
alpar@1163
   720
      ///
alpar@1163
   721
      /// It returns a random integer from the range {0, 1, ..., b - 1}.
alpar@1163
   722
      template <typename Number>
alpar@1163
   723
      Number operator[](Number b) {
alpar@1163
   724
        return _random_bits::Mapping<Number, Word>::map(core, b);
alpar@1163
   725
      }
alpar@1163
   726
alpar@1163
   727
      /// \brief Returns a random non-negative integer
alpar@1163
   728
      ///
alpar@1163
   729
      /// It returns a random non-negative integer uniformly from the
alpar@1163
   730
      /// whole range of the current \c Number type. The default result
alpar@1163
   731
      /// type of this function is <tt>unsigned int</tt>.
alpar@1163
   732
      template <typename Number>
alpar@1163
   733
      Number uinteger() {
alpar@1163
   734
        return _random_bits::IntConversion<Number, Word>::convert(core);
alpar@1163
   735
      }
alpar@1163
   736
alpar@1163
   737
      unsigned int uinteger() {
alpar@1163
   738
        return uinteger<unsigned int>();
alpar@1163
   739
      }
alpar@1163
   740
alpar@1163
   741
      /// \brief Returns a random integer
alpar@1163
   742
      ///
alpar@1163
   743
      /// It returns a random integer uniformly from the whole range of
alpar@1163
   744
      /// the current \c Number type. The default result type of this
alpar@1163
   745
      /// function is \c int.
alpar@1163
   746
      template <typename Number>
alpar@1163
   747
      Number integer() {
alpar@1163
   748
        static const int nb = std::numeric_limits<Number>::digits +
alpar@1163
   749
          (std::numeric_limits<Number>::is_signed ? 1 : 0);
alpar@1163
   750
        return _random_bits::IntConversion<Number, Word, nb>::convert(core);
alpar@1163
   751
      }
alpar@1163
   752
alpar@1163
   753
      int integer() {
alpar@1163
   754
        return integer<int>();
alpar@1163
   755
      }
alpar@1163
   756
alpar@1163
   757
      /// \brief Returns a random bool
alpar@1163
   758
      ///
alpar@1163
   759
      /// It returns a random bool. The generator holds a buffer for
alpar@1163
   760
      /// random bits. Every time when it become empty the generator makes
alpar@1163
   761
      /// a new random word and fill the buffer up.
alpar@1163
   762
      bool boolean() {
alpar@1163
   763
        return bool_producer.convert(core);
alpar@1163
   764
      }
alpar@1163
   765
alpar@1163
   766
      /// @}
alpar@1163
   767
alpar@1163
   768
      ///\name Non-uniform Distributions
alpar@1163
   769
      ///
alpar@1163
   770
      ///@{
alpar@1163
   771
alpar@1163
   772
      /// \brief Returns a random bool with given probability of true result.
alpar@1163
   773
      ///
alpar@1163
   774
      /// It returns a random bool with given probability of true result.
alpar@1163
   775
      bool boolean(double p) {
alpar@1163
   776
        return operator()() < p;
alpar@1163
   777
      }
alpar@1163
   778
alpar@1163
   779
      /// Standard normal (Gauss) distribution
alpar@1163
   780
alpar@1163
   781
      /// Standard normal (Gauss) distribution.
alpar@1163
   782
      /// \note The Cartesian form of the Box-Muller
alpar@1163
   783
      /// transformation is used to generate a random normal distribution.
alpar@1163
   784
      double gauss()
alpar@1163
   785
      {
alpar@1163
   786
        double V1,V2,S;
alpar@1163
   787
        do {
alpar@1163
   788
          V1=2*real<double>()-1;
alpar@1163
   789
          V2=2*real<double>()-1;
alpar@1163
   790
          S=V1*V1+V2*V2;
alpar@1163
   791
        } while(S>=1);
alpar@1163
   792
        return std::sqrt(-2*std::log(S)/S)*V1;
alpar@1163
   793
      }
alpar@1163
   794
      /// Normal (Gauss) distribution with given mean and standard deviation
alpar@1163
   795
alpar@1163
   796
      /// Normal (Gauss) distribution with given mean and standard deviation.
alpar@1163
   797
      /// \sa gauss()
alpar@1163
   798
      double gauss(double mean,double std_dev)
alpar@1163
   799
      {
alpar@1163
   800
        return gauss()*std_dev+mean;
alpar@1163
   801
      }
alpar@1163
   802
alpar@1163
   803
      /// Lognormal distribution
alpar@1163
   804
alpar@1163
   805
      /// Lognormal distribution. The parameters are the mean and the standard
alpar@1163
   806
      /// deviation of <tt>exp(X)</tt>.
alpar@1163
   807
      ///
alpar@1163
   808
      double lognormal(double n_mean,double n_std_dev)
alpar@1163
   809
      {
alpar@1163
   810
        return std::exp(gauss(n_mean,n_std_dev));
alpar@1163
   811
      }
alpar@1163
   812
      /// Lognormal distribution
alpar@1163
   813
alpar@1163
   814
      /// Lognormal distribution. The parameter is an <tt>std::pair</tt> of
alpar@1163
   815
      /// the mean and the standard deviation of <tt>exp(X)</tt>.
alpar@1163
   816
      ///
alpar@1163
   817
      double lognormal(const std::pair<double,double> &params)
alpar@1163
   818
      {
alpar@1163
   819
        return std::exp(gauss(params.first,params.second));
alpar@1163
   820
      }
alpar@1163
   821
      /// Compute the lognormal parameters from mean and standard deviation
alpar@1163
   822
alpar@1163
   823
      /// This function computes the lognormal parameters from mean and
alpar@1163
   824
      /// standard deviation. The return value can direcly be passed to
alpar@1163
   825
      /// lognormal().
alpar@1163
   826
      std::pair<double,double> lognormalParamsFromMD(double mean,
alpar@1163
   827
                                                     double std_dev)
alpar@1163
   828
      {
alpar@1163
   829
        double fr=std_dev/mean;
alpar@1163
   830
        fr*=fr;
alpar@1163
   831
        double lg=std::log(1+fr);
alpar@1163
   832
        return std::pair<double,double>(std::log(mean)-lg/2.0,std::sqrt(lg));
alpar@1163
   833
      }
alpar@1163
   834
      /// Lognormal distribution with given mean and standard deviation
alpar@1163
   835
alpar@1163
   836
      /// Lognormal distribution with given mean and standard deviation.
alpar@1163
   837
      ///
alpar@1163
   838
      double lognormalMD(double mean,double std_dev)
alpar@1163
   839
      {
alpar@1163
   840
        return lognormal(lognormalParamsFromMD(mean,std_dev));
alpar@1163
   841
      }
alpar@1163
   842
alpar@1163
   843
      /// Exponential distribution with given mean
alpar@1163
   844
alpar@1163
   845
      /// This function generates an exponential distribution random number
alpar@1163
   846
      /// with mean <tt>1/lambda</tt>.
alpar@1163
   847
      ///
alpar@1163
   848
      double exponential(double lambda=1.0)
alpar@1163
   849
      {
alpar@1163
   850
        return -std::log(1.0-real<double>())/lambda;
alpar@1163
   851
      }
alpar@1163
   852
alpar@1163
   853
      /// Gamma distribution with given integer shape
alpar@1163
   854
alpar@1163
   855
      /// This function generates a gamma distribution random number.
alpar@1163
   856
      ///
alpar@1163
   857
      ///\param k shape parameter (<tt>k>0</tt> integer)
alpar@1163
   858
      double gamma(int k)
alpar@1163
   859
      {
alpar@1163
   860
        double s = 0;
alpar@1163
   861
        for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
alpar@1163
   862
        return s;
alpar@1163
   863
      }
alpar@1163
   864
alpar@1163
   865
      /// Gamma distribution with given shape and scale parameter
alpar@1163
   866
alpar@1163
   867
      /// This function generates a gamma distribution random number.
alpar@1163
   868
      ///
alpar@1163
   869
      ///\param k shape parameter (<tt>k>0</tt>)
alpar@1163
   870
      ///\param theta scale parameter
alpar@1163
   871
      ///
alpar@1163
   872
      double gamma(double k,double theta=1.0)
alpar@1163
   873
      {
alpar@1163
   874
        double xi,nu;
alpar@1163
   875
        const double delta = k-std::floor(k);
alpar@1163
   876
        const double v0=E/(E-delta);
alpar@1163
   877
        do {
alpar@1163
   878
          double V0=1.0-real<double>();
alpar@1163
   879
          double V1=1.0-real<double>();
alpar@1163
   880
          double V2=1.0-real<double>();
alpar@1163
   881
          if(V2<=v0)
alpar@1163
   882
            {
alpar@1163
   883
              xi=std::pow(V1,1.0/delta);
alpar@1163
   884
              nu=V0*std::pow(xi,delta-1.0);
alpar@1163
   885
            }
alpar@1163
   886
          else
alpar@1163
   887
            {
alpar@1163
   888
              xi=1.0-std::log(V1);
alpar@1163
   889
              nu=V0*std::exp(-xi);
alpar@1163
   890
            }
alpar@1163
   891
        } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
alpar@1163
   892
        return theta*(xi+gamma(int(std::floor(k))));
alpar@1163
   893
      }
alpar@1163
   894
alpar@1163
   895
      /// Weibull distribution
alpar@1163
   896
alpar@1163
   897
      /// This function generates a Weibull distribution random number.
alpar@1163
   898
      ///
alpar@1163
   899
      ///\param k shape parameter (<tt>k>0</tt>)
alpar@1163
   900
      ///\param lambda scale parameter (<tt>lambda>0</tt>)
alpar@1163
   901
      ///
alpar@1163
   902
      double weibull(double k,double lambda)
alpar@1163
   903
      {
alpar@1163
   904
        return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
alpar@1163
   905
      }
alpar@1163
   906
alpar@1163
   907
      /// Pareto distribution
alpar@1163
   908
alpar@1163
   909
      /// This function generates a Pareto distribution random number.
alpar@1163
   910
      ///
alpar@1163
   911
      ///\param k shape parameter (<tt>k>0</tt>)
alpar@1163
   912
      ///\param x_min location parameter (<tt>x_min>0</tt>)
alpar@1163
   913
      ///
alpar@1163
   914
      double pareto(double k,double x_min)
alpar@1163
   915
      {
alpar@1163
   916
        return exponential(gamma(k,1.0/x_min))+x_min;
alpar@1163
   917
      }
alpar@1163
   918
alpar@1163
   919
      /// Poisson distribution
alpar@1163
   920
alpar@1163
   921
      /// This function generates a Poisson distribution random number with
alpar@1163
   922
      /// parameter \c lambda.
alpar@1163
   923
      ///
alpar@1163
   924
      /// The probability mass function of this distribusion is
alpar@1163
   925
      /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f]
alpar@1163
   926
      /// \note The algorithm is taken from the book of Donald E. Knuth titled
alpar@1163
   927
      /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the
alpar@1163
   928
      /// return value.
alpar@1163
   929
alpar@1163
   930
      int poisson(double lambda)
alpar@1163
   931
      {
alpar@1163
   932
        const double l = std::exp(-lambda);
alpar@1163
   933
        int k=0;
alpar@1163
   934
        double p = 1.0;
alpar@1163
   935
        do {
alpar@1163
   936
          k++;
alpar@1163
   937
          p*=real<double>();
alpar@1163
   938
        } while (p>=l);
alpar@1163
   939
        return k-1;
alpar@1163
   940
      }
alpar@1163
   941
alpar@1163
   942
      ///@}
alpar@1163
   943
kpeter@1164
   944
      ///\name Two-Dimensional Distributions
alpar@1163
   945
      ///
alpar@1163
   946
      ///@{
alpar@1163
   947
alpar@1163
   948
      /// Uniform distribution on the full unit circle
alpar@1163
   949
alpar@1163
   950
      /// Uniform distribution on the full unit circle.
alpar@1163
   951
      ///
alpar@1163
   952
      dim2::Point<double> disc()
alpar@1163
   953
      {
alpar@1163
   954
        double V1,V2;
alpar@1163
   955
        do {
alpar@1163
   956
          V1=2*real<double>()-1;
alpar@1163
   957
          V2=2*real<double>()-1;
alpar@1163
   958
alpar@1163
   959
        } while(V1*V1+V2*V2>=1);
alpar@1163
   960
        return dim2::Point<double>(V1,V2);
alpar@1163
   961
      }
kpeter@1164
   962
      /// A kind of two-dimensional normal (Gauss) distribution
alpar@1163
   963
alpar@1163
   964
      /// This function provides a turning symmetric two-dimensional distribution.
alpar@1163
   965
      /// Both coordinates are of standard normal distribution, but they are not
alpar@1163
   966
      /// independent.
alpar@1163
   967
      ///
alpar@1163
   968
      /// \note The coordinates are the two random variables provided by
alpar@1163
   969
      /// the Box-Muller method.
alpar@1163
   970
      dim2::Point<double> gauss2()
alpar@1163
   971
      {
alpar@1163
   972
        double V1,V2,S;
alpar@1163
   973
        do {
alpar@1163
   974
          V1=2*real<double>()-1;
alpar@1163
   975
          V2=2*real<double>()-1;
alpar@1163
   976
          S=V1*V1+V2*V2;
alpar@1163
   977
        } while(S>=1);
alpar@1163
   978
        double W=std::sqrt(-2*std::log(S)/S);
alpar@1163
   979
        return dim2::Point<double>(W*V1,W*V2);
alpar@1163
   980
      }
kpeter@1164
   981
      /// A kind of two-dimensional exponential distribution
alpar@1163
   982
alpar@1163
   983
      /// This function provides a turning symmetric two-dimensional distribution.
alpar@1163
   984
      /// The x-coordinate is of conditionally exponential distribution
alpar@1163
   985
      /// with the condition that x is positive and y=0. If x is negative and
alpar@1163
   986
      /// y=0 then, -x is of exponential distribution. The same is true for the
alpar@1163
   987
      /// y-coordinate.
alpar@1163
   988
      dim2::Point<double> exponential2()
alpar@1163
   989
      {
alpar@1163
   990
        double V1,V2,S;
alpar@1163
   991
        do {
alpar@1163
   992
          V1=2*real<double>()-1;
alpar@1163
   993
          V2=2*real<double>()-1;
alpar@1163
   994
          S=V1*V1+V2*V2;
alpar@1163
   995
        } while(S>=1);
alpar@1163
   996
        double W=-std::log(S)/S;
alpar@1163
   997
        return dim2::Point<double>(W*V1,W*V2);
alpar@1163
   998
      }
alpar@1163
   999
alpar@1163
  1000
      ///@}
alpar@1163
  1001
    };
alpar@1163
  1002
alpar@1163
  1003
alpar@1163
  1004
  };
alpar@10
  1005
alpar@10
  1006
  /// \ingroup misc
alpar@10
  1007
  ///
alpar@10
  1008
  /// \brief Mersenne Twister random number generator
alpar@10
  1009
  ///
kpeter@1164
  1010
  /// This class implements either the 32-bit or the 64-bit version of
alpar@1163
  1011
  /// the Mersenne Twister random number generator algorithm
kpeter@1164
  1012
  /// depending on the system architecture.
alpar@1163
  1013
  /// 
kpeter@1164
  1014
  /// For the API description, see its base class
kpeter@1164
  1015
  /// \ref _random_bits::Random.
alpar@10
  1016
  ///
alpar@1163
  1017
  /// \sa \ref _random_bits::Random
alpar@1163
  1018
  typedef _random_bits::Random<unsigned long> Random;
kpeter@1164
  1019
alpar@1163
  1020
  /// \ingroup misc
alpar@10
  1021
  ///
kpeter@1164
  1022
  /// \brief Mersenne Twister random number generator (32-bit version)
alpar@10
  1023
  ///
kpeter@1164
  1024
  /// This class implements the 32-bit version of the Mersenne Twister
alpar@1163
  1025
  /// random number generator algorithm. It is recommended to be used
alpar@1163
  1026
  /// when someone wants to make sure that the \e same pseudo random
alpar@1163
  1027
  /// sequence will be generated on every platfrom.
alpar@10
  1028
  ///
kpeter@1164
  1029
  /// For the API description, see its base class
kpeter@1164
  1030
  /// \ref _random_bits::Random.
alpar@1163
  1031
  ///
alpar@1163
  1032
  /// \sa \ref _random_bits::Random
kpeter@1164
  1033
  typedef _random_bits::Random<unsigned int> Random32;
alpar@10
  1034
alpar@1163
  1035
  /// \ingroup misc
alpar@1163
  1036
  ///
kpeter@1164
  1037
  /// \brief Mersenne Twister random number generator (64-bit version)
alpar@1163
  1038
  ///
kpeter@1164
  1039
  /// This class implements the 64-bit version of the Mersenne Twister
kpeter@1164
  1040
  /// random number generator algorithm. (Even though it runs
kpeter@1164
  1041
  /// on 32-bit architectures, too.) It is recommended to be used when
alpar@1163
  1042
  /// someone wants to make sure that the \e same pseudo random sequence
alpar@1163
  1043
  /// will be generated on every platfrom.
alpar@1163
  1044
  ///
kpeter@1164
  1045
  /// For the API description, see its base class
kpeter@1164
  1046
  /// \ref _random_bits::Random.
alpar@1163
  1047
  ///
alpar@1163
  1048
  /// \sa \ref _random_bits::Random
alpar@1163
  1049
  typedef _random_bits::Random<unsigned long long> Random64;
alpar@10
  1050
alpar@10
  1051
  extern Random rnd;
alpar@1163
  1052
  
alpar@10
  1053
}
alpar@10
  1054
alpar@10
  1055
#endif