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

Revision 857, 2.5 KB checked in by igarcia, 18 years ago (diff)
Line 
1/* boost random/poisson_distribution.hpp header file
2 *
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)
7 *
8 * See http://www.boost.org for most recent version including documentation.
9 *
10 * $Id: poisson_distribution.hpp,v 1.15 2005/05/21 15:57:00 dgregor Exp $
11 *
12 */
13
14#ifndef BOOST_RANDOM_POISSON_DISTRIBUTION_HPP
15#define BOOST_RANDOM_POISSON_DISTRIBUTION_HPP
16
17#include <cmath>
18#include <cassert>
19#include <iostream>
20#include <boost/limits.hpp>
21#include <boost/static_assert.hpp>
22
23namespace boost {
24
25// Knuth
26template<class IntType = int, class RealType = double>
27class poisson_distribution
28{
29public:
30  typedef RealType input_type;
31  typedef IntType result_type;
32
33  explicit poisson_distribution(const RealType& mean = RealType(1))
34    : _mean(mean)
35  {
36#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
37    // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope
38    BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
39    BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
40#endif
41
42    assert(mean > RealType(0));
43    init();
44  }
45
46  // compiler-generated copy ctor and assignment operator are fine
47
48  RealType mean() const { return _mean; }
49  void reset() { }
50
51  template<class Engine>
52  result_type operator()(Engine& eng)
53  {
54    // TODO: This is O(_mean), but it should be O(log(_mean)) for large _mean
55    RealType product = RealType(1);
56    for(result_type m = 0; ; ++m) {
57      product *= eng();
58      if(product <= _exp_mean)
59        return m;
60    }
61  }
62
63#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
64  template<class CharT, class Traits>
65  friend std::basic_ostream<CharT,Traits>&
66  operator<<(std::basic_ostream<CharT,Traits>& os, const poisson_distribution& pd)
67  {
68    os << pd._mean;
69    return os;
70  }
71
72  template<class CharT, class Traits>
73  friend std::basic_istream<CharT,Traits>&
74  operator>>(std::basic_istream<CharT,Traits>& is, poisson_distribution& pd)
75  {
76    is >> std::ws >> pd._mean;
77    pd.init();
78    return is;
79  }
80#endif
81
82private:
83  void init()
84  {
85#ifndef BOOST_NO_STDC_NAMESPACE
86    // allow for Koenig lookup
87    using std::exp;
88#endif
89    _exp_mean = exp(-_mean);
90  }
91
92  RealType _mean;
93  // some precomputed data from the parameters
94  RealType _exp_mean;
95};
96
97} // namespace boost
98
99#endif // BOOST_RANDOM_POISSON_DISTRIBUTION_HPP
Note: See TracBrowser for help on using the repository browser.