Stan Math Library  2.20.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 
5 #include <boost/random/uniform_01.hpp>
6 #include <boost/random/variate_generator.hpp>
9 
10 namespace stan {
11 namespace math {
12 
13 template <class RNG>
14 inline int categorical_rng(
15  const Eigen::Matrix<double, Eigen::Dynamic, 1>& theta, RNG& rng) {
16  using boost::uniform_01;
17  using boost::variate_generator;
18 
19  static const char* function = "categorical_rng";
20 
21  check_simplex(function, "Probabilities parameter", theta);
22 
23  variate_generator<RNG&, uniform_01<> > uniform01_rng(rng, uniform_01<>());
24 
25  Eigen::VectorXd index(theta.rows());
26  index.setZero();
27 
28  index = cumulative_sum(theta);
29 
30  double c = uniform01_rng();
31  int b = 0;
32  while (c > index(b, 0))
33  b++;
34  return b + 1;
35 }
36 } // namespace math
37 } // namespace stan
38 #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–2018, Stan Development Team.