Automatic Differentiation
 
Loading...
Searching...
No Matches
multinomial_rng.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_PROB_MULTINOMIAL_RNG_HPP
2#define STAN_MATH_PRIM_PROB_MULTINOMIAL_RNG_HPP
3
8#include <vector>
9
10namespace stan {
11namespace math {
12
26template <class T_theta, class RNG,
27 require_eigen_col_vector_t<T_theta>* = nullptr>
28inline std::vector<int> multinomial_rng(const T_theta& theta, int N, RNG& rng) {
29 static constexpr const char* function = "multinomial_rng";
30 const auto& theta_ref = to_ref(theta);
31 check_simplex(function, "Probabilities parameter", theta_ref);
32 check_nonnegative(function, "number of trials variables", N);
33
34 std::vector<int> result(theta.size(), 0);
35 double mass_left = 1.0;
36 int n_left = N;
37 for (int k = 0; n_left > 0 && k < theta.size(); ++k) {
38 double p = theta_ref.coeff(k) / mass_left;
39 if (p > 1.0) {
40 p = 1.0;
41 }
42 result[k] = binomial_rng(n_left, p, rng);
43 n_left -= result[k];
44 mass_left -= theta_ref(k);
45 }
46 return result;
47}
48
49} // namespace math
50} // namespace stan
51#endif
std::vector< int > multinomial_rng(const T_theta &theta, int N, RNG &rng)
Return a draw from a Multinomial distribution given a probability simplex, a total count,...
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_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
void check_simplex(const char *function, const char *name, const T &theta)
Throw an exception if the specified vector is not a simplex.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...