Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.


/* boost random/poisson_distribution.hpp header file
 * Copyright Jens Maurer 2002
 * Permission to use, copy, modify, sell, and distribute this software
 * is hereby granted without fee provided that the above copyright notice
 * appears in all copies and that both that copyright notice and this
 * permission notice appear in supporting documentation,
 * Jens Maurer makes no representations about the suitability of this
 * software for any purpose. It is provided "as is" without express or
 * implied warranty.
 * See for most recent version including documentation.
 * $Id: poisson_distribution.hpp,v 2004/01/25 21:26:45 jmaurer Exp $


#include <cmath>
#include <cassert>
#include <iostream>
#include <boost/limits.hpp>
#include <boost/static_assert.hpp>

namespace boost {

// Knuth
template<class IntType = int, class RealType = double>
class poisson_distribution
  typedef RealType input_type;
  typedef IntType result_type;

  explicit poisson_distribution(const RealType& mean = RealType(1))
    : _mean(mean)
    // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope

    assert(mean > RealType(0));

  // compiler-generated copy ctor and assignment operator are fine

  RealType mean() const { return _mean; }
  void reset() { }

  template<class Engine>
  result_type operator()(Engine& eng)
    // TODO: This is O(_mean), but it should be O(log(_mean)) for large _mean
    RealType product = RealType(1);
    for(result_type m = 0; ; ++m) {
      product *= eng();
      if(product <= _exp_mean)
        return m;

  template<class CharT, class Traits>
  friend std::basic_ostream<CharT,Traits>&
  operator<<(std::basic_ostream<CharT,Traits>& os, const poisson_distribution& pd)
    os << pd._mean;
    return os;

  template<class CharT, class Traits>
  friend std::basic_istream<CharT,Traits>&
  operator>>(std::basic_istream<CharT,Traits>& is, poisson_distribution& pd)
    is >> std::ws >> pd._mean;
    return is;

  void init()
    // allow for Koenig lookup
    using std::exp;
    _exp_mean = exp(-_mean);

  RealType _mean;
  // some precomputed data from the parameters
  RealType _exp_mean;

} // namespace boost