Automatic Differentiation
 
Loading...
Searching...
No Matches
categorical_rng.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_PROB_CATEGORICAL_RNG_HPP
2#define STAN_MATH_PRIM_PROB_CATEGORICAL_RNG_HPP
3
7#include <boost/random/uniform_01.hpp>
8#include <boost/random/variate_generator.hpp>
9
10namespace stan {
11namespace math {
12
13template <class RNG>
14inline 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 static constexpr const char* function = "categorical_rng";
19 check_simplex(function, "Probabilities parameter", theta);
20
21 variate_generator<RNG&, uniform_01<> > uniform01_rng(rng, uniform_01<>());
22
23 Eigen::VectorXd index(theta.rows());
24 index.setZero();
25
26 index = cumulative_sum(theta);
27
28 // index may sum to just below 1, so stop at the last nonzero entry
29 int last = theta.size() - 1;
30 while (theta(last) == 0) {
31 last--;
32 }
33 double c = uniform01_rng();
34 int b = 0;
35 while (b < last && c >= index(b)) {
36 b++;
37 }
38 return b + 1;
39}
40} // namespace math
41} // namespace stan
42#endif
int categorical_rng(const Eigen::Matrix< double, Eigen::Dynamic, 1 > &theta, RNG &rng)
auto cumulative_sum(T_vec &&v)
Return the cumulative sum of the specified vector.
void check_simplex(const char *function, const char *name, const T &theta)
Throw an exception if the specified vector is not a simplex.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...