source: NonGTP/Boost/boost/random/bernoulli_distribution.hpp @ 857

Revision 857, 2.2 KB checked in by igarcia, 19 years ago (diff)
Line 
1/* boost random/bernoulli_distribution.hpp header file
2 *
3 * Copyright Jens Maurer 2000-2001
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)
7 *
8 * See http://www.boost.org for most recent version including documentation.
9 *
10 * $Id: bernoulli_distribution.hpp,v 1.19 2004/07/27 03:43:32 dgregor Exp $
11 *
12 * Revision history
13 *  2001-02-18  moved to individual header files
14 */
15
16#ifndef BOOST_RANDOM_BERNOULLI_DISTRIBUTION_HPP
17#define BOOST_RANDOM_BERNOULLI_DISTRIBUTION_HPP
18
19#include <cassert>
20#include <iostream>
21
22namespace boost {
23
24// Bernoulli distribution: p(true) = p, p(false) = 1-p   (boolean)
25template<class RealType = double>
26class bernoulli_distribution
27{
28public:
29  // In principle, this could work with both integer and floating-point
30  // types.  Generating floating-point random numbers in the first
31  // place is probably more expensive, so use integer as input.
32  typedef int input_type;
33  typedef bool result_type;
34
35  explicit bernoulli_distribution(const RealType& p = RealType(0.5))
36    : _p(p)
37  {
38    assert(p >= 0);
39    assert(p <= 1);
40  }
41
42  // compiler-generated copy ctor and assignment operator are fine
43
44  RealType p() const { return _p; }
45  void reset() { }
46
47  template<class Engine>
48  result_type operator()(Engine& eng)
49  {
50    if(_p == RealType(0))
51      return false;
52    else
53      return RealType(eng() - (eng.min)()) <= _p * RealType((eng.max)()-(eng.min)());
54  }
55
56#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
57  template<class CharT, class Traits>
58  friend std::basic_ostream<CharT,Traits>&
59  operator<<(std::basic_ostream<CharT,Traits>& os, const bernoulli_distribution& bd)
60  {
61    os << bd._p;
62    return os;
63  }
64
65  template<class CharT, class Traits>
66  friend std::basic_istream<CharT,Traits>&
67  operator>>(std::basic_istream<CharT,Traits>& is, bernoulli_distribution& bd)
68  {
69    is >> std::ws >> bd._p;
70    return is;
71  }
72#endif
73
74private:
75  RealType _p;
76};
77
78} // namespace boost
79
80#endif // BOOST_RANDOM_BERNOULLI_DISTRIBUTION_HPP
Note: See TracBrowser for help on using the repository browser.