Stan Math Library  2.14.0
reverse mode automatic differentiation
multinomial_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_RNG_HPP
2 #define STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_RNG_HPP
3 
12 #include <boost/math/special_functions/gamma.hpp>
13 #include <boost/random/uniform_01.hpp>
14 #include <boost/random/variate_generator.hpp>
15 #include <vector>
16 
17 namespace stan {
18  namespace math {
19 
20  template <class RNG>
21  inline std::vector<int>
22  multinomial_rng(const Eigen::Matrix<double, Eigen::Dynamic, 1>& theta,
23  int N,
24  RNG& rng) {
25  static const char* function("multinomial_rng");
26 
27  check_simplex(function, "Probabilites parameter", theta);
28  check_positive(function, "number of trials variables", N);
29 
30  std::vector<int> result(theta.size(), 0);
31  double mass_left = 1.0;
32  int n_left = N;
33  for (int k = 0; n_left > 0 && k < theta.size(); ++k) {
34  double p = theta[k] / mass_left;
35  if (p > 1.0) p = 1.0;
36  result[k] = binomial_rng(n_left, p, rng);
37  n_left -= result[k];
38  mass_left -= theta[k];
39  }
40  return result;
41  }
42 
43  }
44 }
45 #endif
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.
std::vector< int > multinomial_rng(const Eigen::Matrix< double, Eigen::Dynamic, 1 > &theta, int N, RNG &rng)
int binomial_rng(int N, double theta, RNG &rng)
void check_positive(const char *function, const char *name, const T_y &y)
Check if y is positive.

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