1 /* boost random/gamma_distribution.hpp header file
3 * Copyright Jens Maurer 2002
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE_1_0.txt or copy at
6 * http://www.boost.org/LICENSE_1_0.txt)
8 * See http://www.boost.org for most recent version including documentation.
10 * $Id: gamma_distribution.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $
14 #ifndef BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP
15 #define BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP
17 #include <boost/config/no_tr1/cmath.hpp>
19 #include <boost/limits.hpp>
20 #include <boost/static_assert.hpp>
21 #include <boost/random/detail/config.hpp>
22 #include <boost/random/exponential_distribution.hpp>
26 // The algorithm is taken from Knuth
29 * The gamma distribution is a continuous distribution with a single
32 * It has \f$p(x) = x^{\alpha-1}\frac{e^{-x}}{\Gamma(\alpha)}\f$.
34 template<class RealType = double>
35 class gamma_distribution
38 typedef RealType input_type;
39 typedef RealType result_type;
41 #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
42 BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
45 explicit gamma_distribution(const result_type& alpha_arg = result_type(1))
46 : _exp(result_type(1)), _alpha(alpha_arg)
48 assert(_alpha > result_type(0));
52 // compiler-generated copy ctor and assignment operator are fine
54 RealType alpha() const { return _alpha; }
56 void reset() { _exp.reset(); }
58 template<class Engine>
59 result_type operator()(Engine& eng)
61 #ifndef BOOST_NO_STDC_NAMESPACE
62 // allow for Koenig lookup
63 using std::tan; using std::sqrt; using std::exp; using std::log;
66 if(_alpha == result_type(1)) {
68 } else if(_alpha > result_type(1)) {
69 // Can we have a boost::mathconst please?
70 const result_type pi = result_type(3.14159265358979323846);
72 result_type y = tan(pi * eng());
73 result_type x = sqrt(result_type(2)*_alpha-result_type(1))*y
74 + _alpha-result_type(1);
75 if(x <= result_type(0))
78 (result_type(1)+y*y) * exp((_alpha-result_type(1))
79 *log(x/(_alpha-result_type(1)))
80 - sqrt(result_type(2)*_alpha
85 } else /* alpha < 1.0 */ {
87 result_type u = eng();
88 result_type y = _exp(eng);
95 q = _p + (result_type(1)-_p) * pow(x, _alpha-result_type(1));
104 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
105 template<class CharT, class Traits>
106 friend std::basic_ostream<CharT,Traits>&
107 operator<<(std::basic_ostream<CharT,Traits>& os, const gamma_distribution& gd)
113 template<class CharT, class Traits>
114 friend std::basic_istream<CharT,Traits>&
115 operator>>(std::basic_istream<CharT,Traits>& is, gamma_distribution& gd)
117 is >> std::ws >> gd._alpha;
124 /// \cond hide_private_members
127 #ifndef BOOST_NO_STDC_NAMESPACE
128 // allow for Koenig lookup
131 _p = exp(result_type(1)) / (_alpha + exp(result_type(1)));
135 exponential_distribution<RealType> _exp;
137 // some data precomputed from the parameters
143 #endif // BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP