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,v 1.9 2004/07/27 03:43:32 dgregor Exp $
14 #ifndef BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP
15 #define BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP
19 #include <boost/limits.hpp>
20 #include <boost/static_assert.hpp>
21 #include <boost/random/exponential_distribution.hpp>
26 template<class RealType = double>
27 class gamma_distribution
30 typedef RealType input_type;
31 typedef RealType result_type;
33 #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
34 BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
37 explicit gamma_distribution(const result_type& alpha = result_type(1))
38 : _exp(result_type(1)), _alpha(alpha)
40 assert(alpha > result_type(0));
44 // compiler-generated copy ctor and assignment operator are fine
46 RealType alpha() const { return _alpha; }
48 void reset() { _exp.reset(); }
50 template<class Engine>
51 result_type operator()(Engine& eng)
53 #ifndef BOOST_NO_STDC_NAMESPACE
54 // allow for Koenig lookup
55 using std::tan; using std::sqrt; using std::exp; using std::log;
58 if(_alpha == result_type(1)) {
60 } else if(_alpha > result_type(1)) {
61 // Can we have a boost::mathconst please?
62 const result_type pi = result_type(3.14159265358979323846);
64 result_type y = tan(pi * eng());
65 result_type x = sqrt(result_type(2)*_alpha-result_type(1))*y
66 + _alpha-result_type(1);
67 if(x <= result_type(0))
70 (result_type(1)+y*y) * exp((_alpha-result_type(1))
71 *log(x/(_alpha-result_type(1)))
72 - sqrt(result_type(2)*_alpha
77 } else /* alpha < 1.0 */ {
79 result_type u = eng();
80 result_type y = _exp(eng);
87 q = _p + (result_type(1)-_p) * pow(x, _alpha-result_type(1));
96 #if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
97 template<class CharT, class Traits>
98 friend std::basic_ostream<CharT,Traits>&
99 operator<<(std::basic_ostream<CharT,Traits>& os, const gamma_distribution& gd)
105 template<class CharT, class Traits>
106 friend std::basic_istream<CharT,Traits>&
107 operator>>(std::basic_istream<CharT,Traits>& is, gamma_distribution& gd)
109 is >> std::ws >> gd._alpha;
118 #ifndef BOOST_NO_STDC_NAMESPACE
119 // allow for Koenig lookup
122 _p = exp(result_type(1)) / (_alpha + exp(result_type(1)));
125 exponential_distribution<RealType> _exp;
127 // some data precomputed from the parameters
133 #endif // BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP