1 /* boost random/binomial_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: binomial_distribution.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $
14 #ifndef BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP
15 #define BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP
17 #include <boost/config/no_tr1/cmath.hpp>
19 #include <boost/random/detail/config.hpp>
20 #include <boost/random/bernoulli_distribution.hpp>
25 * The binomial distribution is an integer valued distribution with
26 * two parameters, @c t and @c p. The values of the distribution
27 * are within the range [0,t].
29 * The probability that the distribution produces a value k is
30 * \f${t \choose k}p^k(1-p)^{t-k}\f$.
32 template<class IntType = int, class RealType = double>
33 class binomial_distribution
36 typedef typename bernoulli_distribution<RealType>::input_type input_type;
37 typedef IntType result_type;
40 * Construct an @c binomial_distribution object. @c t and @c p
41 * are the parameters of the distribution.
43 * Requires: t >=0 && 0 <= p <= 1
45 explicit binomial_distribution(IntType t = 1,
46 const RealType& p = RealType(0.5))
47 : _bernoulli(p), _t(t)
50 assert(RealType(0) <= p && p <= RealType(1));
53 // compiler-generated copy ctor and assignment operator are fine
55 /** Returns: the @c t parameter of the distribution */
56 IntType t() const { return _t; }
57 /** Returns: the @c p parameter of the distribution */
58 RealType p() const { return _bernoulli.p(); }
60 * Effects: Subsequent uses of the distribution do not depend
61 * on values produced by any engine prior to invoking reset.
66 * Returns: a random variate distributed according to the
67 * binomial distribution.
69 template<class Engine>
70 result_type operator()(Engine& eng)
72 // TODO: This is O(_t), but it should be O(log(_t)) for large _t
74 for(IntType i = 0; i < _t; ++i)
80 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
82 * Writes the parameters of the distribution to a @c std::ostream.
84 template<class CharT, class Traits>
85 friend std::basic_ostream<CharT,Traits>&
86 operator<<(std::basic_ostream<CharT,Traits>& os, const binomial_distribution& bd)
88 os << bd._bernoulli << " " << bd._t;
93 * Reads the parameters of the distribution from a @c std::istream.
95 template<class CharT, class Traits>
96 friend std::basic_istream<CharT,Traits>&
97 operator>>(std::basic_istream<CharT,Traits>& is, binomial_distribution& bd)
99 is >> std::ws >> bd._bernoulli >> std::ws >> bd._t;
105 bernoulli_distribution<RealType> _bernoulli;
111 #endif // BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP