COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/random.h @ 2380:7b0558c52de3

Last change on this file since 2380:7b0558c52de3 was 2380:7b0558c52de3, checked in by Alpar Juttner, 17 years ago

ball2() -> disc() renaming

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