Stan Math Library  2.15.0
reverse mode automatic differentiation
categorical_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_RNG_HPP
2 #define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_RNG_HPP
3 
4 #include <boost/random/uniform_01.hpp>
5 #include <boost/random/variate_generator.hpp>
14 
15 namespace stan {
16  namespace math {
17 
18  template <class RNG>
19  inline int
20  categorical_rng(const Eigen::Matrix<double, Eigen::Dynamic, 1>& theta,
21  RNG& rng) {
22  using boost::variate_generator;
23  using boost::uniform_01;
24 
25  static const char* function("categorical_rng");
26 
27  check_simplex(function, "Probabilities parameter", theta);
28 
29  variate_generator<RNG&, uniform_01<> >
30  uniform01_rng(rng, uniform_01<>());
31 
32  Eigen::VectorXd index(theta.rows());
33  index.setZero();
34 
35  index = cumulative_sum(theta);
36 
37  double c = uniform01_rng();
38  int b = 0;
39  while (c > index(b, 0))
40  b++;
41  return b + 1;
42  }
43  }
44 }
45 #endif
std::vector< T > cumulative_sum(const std::vector< T > &x)
Return the cumulative sum of the specified vector.
void check_simplex(const char *function, const char *name, const Eigen::Matrix< T_prob, Eigen::Dynamic, 1 > &theta)
Check if the specified vector is simplex.
int categorical_rng(const Eigen::Matrix< double, Eigen::Dynamic, 1 > &theta, RNG &rng)

     [ Stan Home Page ] © 2011–2016, Stan Development Team.