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 double c = uniform01_rng();
29 int b = 0;
30 while (c > index(b, 0)) {
31 b++;
32 }
33 return b + 1;
34}
35} // namespace math
36} // namespace stan
37#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 ...