Stan Math Library  2.20.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 
8 #include <vector>
9 
10 namespace stan {
11 namespace math {
12 
13 template <class RNG>
14 inline std::vector<int> multinomial_rng(
15  const Eigen::Matrix<double, Eigen::Dynamic, 1>& theta, int N, RNG& rng) {
16  static const char* function = "multinomial_rng";
17 
18  check_simplex(function, "Probabilities parameter", theta);
19  check_positive(function, "number of trials variables", N);
20 
21  std::vector<int> result(theta.size(), 0);
22  double mass_left = 1.0;
23  int n_left = N;
24  for (int k = 0; n_left > 0 && k < theta.size(); ++k) {
25  double p = theta[k] / mass_left;
26  if (p > 1.0)
27  p = 1.0;
28  result[k] = binomial_rng(n_left, p, rng);
29  n_left -= result[k];
30  mass_left -= theta[k];
31  }
32  return result;
33 }
34 
35 } // namespace math
36 } // namespace stan
37 #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)
VectorBuilder< true, int, T_N, T_theta >::type binomial_rng(const T_N &N, const T_theta &theta, RNG &rng)
Return a pseudorandom binomial random variable for the given population size and chance of success pa...
void check_positive(const char *function, const char *name, const T_y &y)
Check if y is positive.

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