Geometric.h
Go to the documentation of this file.
1 /*!
2  *
3  *
4  * \brief Implements a geometric distribution.
5  *
6  *
7  *
8  * \author O. Krause
9  * \date 2010-01-01
10  *
11  *
12  * \par Copyright 1995-2017 Shark Development Team
13  *
14  * <BR><HR>
15  * This file is part of Shark.
16  * <http://shark-ml.org/>
17  *
18  * Shark is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU Lesser General Public License as published
20  * by the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * Shark is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU Lesser General Public License for more details.
27  *
28  * You should have received a copy of the GNU Lesser General Public License
29  * along with Shark. If not, see <http://www.gnu.org/licenses/>.
30  *
31  */
32 #ifndef SHARK_RNG_GEOMETRIC_H
33 #define SHARK_RNG_GEOMETRIC_H
34 
35 
36 
37 #include <cmath>
38 
39 namespace shark{
40 
41  /**
42  * \brief Implements the geometric distribution.
43  *
44  * Note that a support {1,2,3,...} is assumed here.
45  */
46  template<typename RngType = shark::DefaultRngType>
47  class Geometric:public boost::variate_generator<RngType*,boost::geometric_distribution<long> > {
48  private:
49  typedef boost::variate_generator<RngType*,boost::geometric_distribution<long> > Base;
50  public:
51 
52  /**
53  * \brief C'tor, initializes the parameter p modelling the probability of success. Associates
54  * the distribution with a custom RNG.
55  * \param [in,out] rng The RNG to associate the distribution with.
56  * \param [in] p Parameter p, the probability of success.
57  */
58  Geometric( RngType & rng, double p = 0.5 )
59  :Base(&rng,boost::geometric_distribution<long>(1.0-p))
60  {}
61 
62  /** \brief Injects the default sampling operator. */
63  using Base::operator();
64 
65  /**
66  * \brief Reinitializes the distribution with the supplied success probability and samples a random number.
67  * \param [in] p The new success probability.
68  */
69  long operator()(double p) {
70  boost::geometric_distribution<long> dist( p );
71  return dist(Base::engine());
72  }
73 
74  /**
75  * \brief Accesses the success probability.
76  */
77  double prob() const {
78  return 1-Base::distribution().p();
79  }
80 
81  /**
82  * \brief Adjusts the success probability.
83  */
84  void prob(double newMean) {
85  Base::distribution()=boost::geometric_distribution<long>(1-newMean);
86  }
87 
88  /**
89  * \brief Calculates the probability of x.
90  */
91  double p( long x ) {
92  return( x > 0 ? prob() * std::pow(1 - prob(), (double) x - 1) : 0 );
93  }
94 
95  };
96 }
97 #endif