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