Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-30 09:31:49

0001 // Copyright 2017 The Abseil Authors.
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //      https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 
0015 #ifndef ABSL_RANDOM_POISSON_DISTRIBUTION_H_
0016 #define ABSL_RANDOM_POISSON_DISTRIBUTION_H_
0017 
0018 #include <cassert>
0019 #include <cmath>
0020 #include <istream>
0021 #include <limits>
0022 #include <ostream>
0023 #include <type_traits>
0024 
0025 #include "absl/random/internal/fast_uniform_bits.h"
0026 #include "absl/random/internal/fastmath.h"
0027 #include "absl/random/internal/generate_real.h"
0028 #include "absl/random/internal/iostream_state_saver.h"
0029 #include "absl/random/internal/traits.h"
0030 
0031 namespace absl {
0032 ABSL_NAMESPACE_BEGIN
0033 
0034 // absl::poisson_distribution:
0035 // Generates discrete variates conforming to a Poisson distribution.
0036 //   p(n) = (mean^n / n!) exp(-mean)
0037 //
0038 // Depending on the parameter, the distribution selects one of the following
0039 // algorithms:
0040 // * The standard algorithm, attributed to Knuth, extended using a split method
0041 // for larger values
0042 // * The "Ratio of Uniforms as a convenient method for sampling from classical
0043 // discrete distributions", Stadlober, 1989.
0044 // http://www.sciencedirect.com/science/article/pii/0377042790903495
0045 //
0046 // NOTE: param_type.mean() is a double, which permits values larger than
0047 // poisson_distribution<IntType>::max(), however this should be avoided and
0048 // the distribution results are limited to the max() value.
0049 //
0050 // The goals of this implementation are to provide good performance while still
0051 // beig thread-safe: This limits the implementation to not using lgamma provided
0052 // by <math.h>.
0053 //
0054 template <typename IntType = int>
0055 class poisson_distribution {
0056  public:
0057   using result_type = IntType;
0058 
0059   class param_type {
0060    public:
0061     using distribution_type = poisson_distribution;
0062     explicit param_type(double mean = 1.0);
0063 
0064     double mean() const { return mean_; }
0065 
0066     friend bool operator==(const param_type& a, const param_type& b) {
0067       return a.mean_ == b.mean_;
0068     }
0069 
0070     friend bool operator!=(const param_type& a, const param_type& b) {
0071       return !(a == b);
0072     }
0073 
0074    private:
0075     friend class poisson_distribution;
0076 
0077     double mean_;
0078     double emu_;  // e ^ -mean_
0079     double lmu_;  // ln(mean_)
0080     double s_;
0081     double log_k_;
0082     int split_;
0083 
0084     static_assert(random_internal::IsIntegral<IntType>::value,
0085                   "Class-template absl::poisson_distribution<> must be "
0086                   "parameterized using an integral type.");
0087   };
0088 
0089   poisson_distribution() : poisson_distribution(1.0) {}
0090 
0091   explicit poisson_distribution(double mean) : param_(mean) {}
0092 
0093   explicit poisson_distribution(const param_type& p) : param_(p) {}
0094 
0095   void reset() {}
0096 
0097   // generating functions
0098   template <typename URBG>
0099   result_type operator()(URBG& g) {  // NOLINT(runtime/references)
0100     return (*this)(g, param_);
0101   }
0102 
0103   template <typename URBG>
0104   result_type operator()(URBG& g,  // NOLINT(runtime/references)
0105                          const param_type& p);
0106 
0107   param_type param() const { return param_; }
0108   void param(const param_type& p) { param_ = p; }
0109 
0110   result_type(min)() const { return 0; }
0111   result_type(max)() const { return (std::numeric_limits<result_type>::max)(); }
0112 
0113   double mean() const { return param_.mean(); }
0114 
0115   friend bool operator==(const poisson_distribution& a,
0116                          const poisson_distribution& b) {
0117     return a.param_ == b.param_;
0118   }
0119   friend bool operator!=(const poisson_distribution& a,
0120                          const poisson_distribution& b) {
0121     return a.param_ != b.param_;
0122   }
0123 
0124  private:
0125   param_type param_;
0126   random_internal::FastUniformBits<uint64_t> fast_u64_;
0127 };
0128 
0129 // -----------------------------------------------------------------------------
0130 // Implementation details follow
0131 // -----------------------------------------------------------------------------
0132 
0133 template <typename IntType>
0134 poisson_distribution<IntType>::param_type::param_type(double mean)
0135     : mean_(mean), split_(0) {
0136   assert(mean >= 0);
0137   assert(mean <=
0138          static_cast<double>((std::numeric_limits<result_type>::max)()));
0139   // As a defensive measure, avoid large values of the mean.  The rejection
0140   // algorithm used does not support very large values well.  It my be worth
0141   // changing algorithms to better deal with these cases.
0142   assert(mean <= 1e10);
0143   if (mean_ < 10) {
0144     // For small lambda, use the knuth method.
0145     split_ = 1;
0146     emu_ = std::exp(-mean_);
0147   } else if (mean_ <= 50) {
0148     // Use split-knuth method.
0149     split_ = 1 + static_cast<int>(mean_ / 10.0);
0150     emu_ = std::exp(-mean_ / static_cast<double>(split_));
0151   } else {
0152     // Use ratio of uniforms method.
0153     constexpr double k2E = 0.7357588823428846;
0154     constexpr double kSA = 0.4494580810294493;
0155 
0156     lmu_ = std::log(mean_);
0157     double a = mean_ + 0.5;
0158     s_ = kSA + std::sqrt(k2E * a);
0159     const double mode = std::ceil(mean_) - 1;
0160     log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode);
0161   }
0162 }
0163 
0164 template <typename IntType>
0165 template <typename URBG>
0166 typename poisson_distribution<IntType>::result_type
0167 poisson_distribution<IntType>::operator()(
0168     URBG& g,  // NOLINT(runtime/references)
0169     const param_type& p) {
0170   using random_internal::GeneratePositiveTag;
0171   using random_internal::GenerateRealFromBits;
0172   using random_internal::GenerateSignedTag;
0173 
0174   if (p.split_ != 0) {
0175     // Use Knuth's algorithm with range splitting to avoid floating-point
0176     // errors. Knuth's algorithm is: Ui is a sequence of uniform variates on
0177     // (0,1); return the number of variates required for product(Ui) <
0178     // exp(-lambda).
0179     //
0180     // The expected number of variates required for Knuth's method can be
0181     // computed as follows:
0182     // The expected value of U is 0.5, so solving for 0.5^n < exp(-lambda) gives
0183     // the expected number of uniform variates
0184     // required for a given lambda, which is:
0185     //  lambda = [2, 5,  9, 10, 11, 12, 13, 14, 15, 16, 17]
0186     //  n      = [3, 8, 13, 15, 16, 18, 19, 21, 22, 24, 25]
0187     //
0188     result_type n = 0;
0189     for (int split = p.split_; split > 0; --split) {
0190       double r = 1.0;
0191       do {
0192         r *= GenerateRealFromBits<double, GeneratePositiveTag, true>(
0193             fast_u64_(g));  // U(-1, 0)
0194         ++n;
0195       } while (r > p.emu_);
0196       --n;
0197     }
0198     return n;
0199   }
0200 
0201   // Use ratio of uniforms method.
0202   //
0203   // Let u ~ Uniform(0, 1), v ~ Uniform(-1, 1),
0204   //     a = lambda + 1/2,
0205   //     s = 1.5 - sqrt(3/e) + sqrt(2(lambda + 1/2)/e),
0206   //     x = s * v/u + a.
0207   // P(floor(x) = k | u^2 < f(floor(x))/k), where
0208   // f(m) = lambda^m exp(-lambda)/ m!, for 0 <= m, and f(m) = 0 otherwise,
0209   // and k = max(f).
0210   const double a = p.mean_ + 0.5;
0211   for (;;) {
0212     const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>(
0213         fast_u64_(g));  // U(0, 1)
0214     const double v = GenerateRealFromBits<double, GenerateSignedTag, false>(
0215         fast_u64_(g));  // U(-1, 1)
0216 
0217     const double x = std::floor(p.s_ * v / u + a);
0218     if (x < 0) continue;  // f(negative) = 0
0219     const double rhs = x * p.lmu_;
0220     // clang-format off
0221     double s = (x <= 1.0) ? 0.0
0222              : (x == 2.0) ? 0.693147180559945
0223              : absl::random_internal::StirlingLogFactorial(x);
0224     // clang-format on
0225     const double lhs = 2.0 * std::log(u) + p.log_k_ + s;
0226     if (lhs < rhs) {
0227       return x > static_cast<double>((max)())
0228                  ? (max)()
0229                  : static_cast<result_type>(x);  // f(x)/k >= u^2
0230     }
0231   }
0232 }
0233 
0234 template <typename CharT, typename Traits, typename IntType>
0235 std::basic_ostream<CharT, Traits>& operator<<(
0236     std::basic_ostream<CharT, Traits>& os,  // NOLINT(runtime/references)
0237     const poisson_distribution<IntType>& x) {
0238   auto saver = random_internal::make_ostream_state_saver(os);
0239   os.precision(random_internal::stream_precision_helper<double>::kPrecision);
0240   os << x.mean();
0241   return os;
0242 }
0243 
0244 template <typename CharT, typename Traits, typename IntType>
0245 std::basic_istream<CharT, Traits>& operator>>(
0246     std::basic_istream<CharT, Traits>& is,  // NOLINT(runtime/references)
0247     poisson_distribution<IntType>& x) {     // NOLINT(runtime/references)
0248   using param_type = typename poisson_distribution<IntType>::param_type;
0249 
0250   auto saver = random_internal::make_istream_state_saver(is);
0251   double mean = random_internal::read_floating_point<double>(is);
0252   if (!is.fail()) {
0253     x.param(param_type(mean));
0254   }
0255   return is;
0256 }
0257 
0258 ABSL_NAMESPACE_END
0259 }  // namespace absl
0260 
0261 #endif  // ABSL_RANDOM_POISSON_DISTRIBUTION_H_