00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #if !defined(EXPONENTIALPROB_HPP)
00013 #define EXPONENTIALPROB_HPP "$Id: ExponentialProb.hpp 6415 2008-01-12 19:12:01Z ckarney $"
00014
00015 #include <vector>
00016 #include <limits>
00017
00018 namespace RandomLib {
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048 class ExponentialProb {
00049 private:
00050 typedef unsigned word;
00051 public:
00052
00053 ExponentialProb() : _v(std::vector<word>(alloc_incr)) {}
00054
00055
00056
00057
00058
00059 template<typename RealType, class Random>
00060 bool operator()(Random& r, RealType p) const throw(std::bad_alloc);
00061
00062 private:
00063
00064
00065
00066 template<typename RealType, class Random>
00067 bool ExpFraction(Random& r, RealType p) const throw(std::bad_alloc);
00068
00069
00070
00071 mutable std::vector<word> _v;
00072
00073
00074
00075 static const unsigned alloc_incr = 16;
00076 };
00077
00078 template<typename RealType, class Random>
00079 inline bool ExponentialProb::operator()(Random& r, RealType p) const
00080 throw(std::bad_alloc) {
00081 return p <= 0 ||
00082
00083 p < RealType(1)/std::numeric_limits<RealType>::epsilon() &&
00084
00085 ExpFraction(r, p < RealType(1) ? p : RealType(1)) &&
00086 ( p <= RealType(1) || operator()(r, p - RealType(1)) );
00087 }
00088
00089 template<typename RealType, class Random>
00090 inline bool ExponentialProb::ExpFraction(Random& r, RealType p) const
00091 throw(std::bad_alloc) {
00092
00093 const int c =
00094 std::numeric_limits<word>::digits <
00095 std::numeric_limits<RealType>::digits ?
00096 std::numeric_limits<word>::digits :
00097 std::numeric_limits<RealType>::digits;
00098
00099 unsigned m = 0, l = _v.size();
00100 if (p < RealType(1))
00101 while (true) {
00102 if (p <= RealType(0))
00103 return true;
00104
00105 if (l == m)
00106 _v.resize(l += alloc_incr);
00107 _v[m++] = r.template Integer<word, c>();
00108 p *= pow(RealType(2), c);
00109 word w = word(p);
00110 if (_v[m - 1] > w)
00111 return true;
00112 else if (_v[m - 1] < w)
00113 break;
00114 else
00115 p -= RealType(w);
00116 }
00117
00118
00119 for (unsigned s = 0; ; s ^= 1) {
00120 for (size_t j = 0; ; ++j) {
00121 if (j == m) {
00122
00123 if (l == m)
00124 _v.resize(l += alloc_incr);
00125 _v[m++] = r.template Integer<word, c>();
00126 }
00127 word w = r.template Integer<word, c>();
00128 if (w > _v[j])
00129 return s;
00130 else if (w < _v[j]) {
00131 _v[j] = w;
00132 m = j + 1;
00133 break;
00134 }
00135
00136 }
00137 }
00138 }
00139 }
00140 #endif // EXPONENTIALPROB_HPP