00001 /** 00002 * \file ExactPower.hpp 00003 * \brief Header for ExactPower 00004 * 00005 * Sample exactly from a power distribution. 00006 * 00007 * Written by <a href="http://charles.karney.info/">Charles Karney</a> 00008 * <charles@karney.com> and licensed under the LGPL. For more 00009 * information, see http://charles.karney.info/random/ 00010 **********************************************************************/ 00011 00012 #if !defined(EXACTPOWER_HPP) 00013 #define EXACTPOWER_HPP "$Id: ExactPower.hpp 6415 2008-01-12 19:12:01Z ckarney $" 00014 00015 #include "RandomLib/RandomNumber.hpp" 00016 00017 namespace RandomLib { 00018 /** 00019 * \brief Sample exactly from a power distribution. 00020 * 00021 * Sample exactly from power distribution (<i>n</i> + 1) 00022 * <i>x</i><sup><i>n</i></sup> for \e x in (0,1) and integer \e n >= 0 using 00023 * infinite precision. The template parameter \a bits specifies the number 00024 * of bits in the base used for RandomNumber (i.e., base = 00025 * 2<sup><i>bits</i></sup>). 00026 **********************************************************************/ 00027 template<int bits = 1> class ExactPower { 00028 public: 00029 /** 00030 * Return the random deviate with a power distribution, (<i>n</i> + 1) 00031 * <i>x</i><sup><i>n</i></sup> for \e x in (0,1) and integer \e n >= 0. 00032 * Returned result is a RandomNumber with base 2<sup><i>bits</i></sup>. 00033 * For \e bits = 1, the number of random bits in the result and consumed 00034 * are as follows:\n 00035 \verbatim 00036 n random bits 00037 result consumed 00038 0 0 0 00039 1 2 4 00040 2 2.33 6.67 00041 3 2.67 9.24 00042 4 2.96 11.71 00043 5 3.20 14.11 00044 6 3.41 16.45 00045 7 3.59 18.75 00046 8 3.75 21.01 00047 9 3.89 23.25 00048 10 4.02 25.47 00049 \endverbatim 00050 * The relative frequency of the results with \a bits = 1 can be shown via 00051 * a histogram\n <img src="powerhist.png" width=580 height=750 alt="exact 00052 * binary sampling of power distribution">\n The base of each rectangle 00053 * gives the range represented by the corresponding binary number and the 00054 * area is proportional to its frequency. A PDF version of this figure 00055 * <a href="powerhist.pdf">here</a>. This allows the figure to be 00056 * magnified to show the rectangles for all binary numbers up to 9 bits. 00057 **********************************************************************/ 00058 template<class Random> 00059 RandomNumber<bits> operator()(Random& r, unsigned n) const; 00060 }; 00061 00062 template<int bits> template<class Random> inline RandomNumber<bits> 00063 ExactPower<bits>::operator()(Random& r, unsigned n) const { 00064 // Return max(u_0, u_1, u_2, ..., u_n). Equivalent to taking the 00065 // (n+1)th root of u_0. 00066 RandomNumber<bits> x; 00067 for (RandomNumber<bits> y; n--;) { 00068 y.Init(); 00069 if (x.LessThan(r, y)) 00070 x = y; 00071 } 00072 return x; 00073 } 00074 } // namespace RandomLib 00075 #endif // EXACTPOWER_HPP