Stan Math Library  2.20.0
reverse mode automatic differentiation
categorical_logit_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_RNG_HPP
2 #define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_RNG_HPP
3 
5 #include <boost/random/uniform_01.hpp>
6 #include <boost/random/variate_generator.hpp>
12 
13 namespace stan {
14 namespace math {
28 template <class RNG>
29 inline int categorical_logit_rng(const Eigen::VectorXd& beta, RNG& rng) {
30  using boost::uniform_01;
31  using boost::variate_generator;
32 
33  static const char* function = "categorical_logit_rng";
34 
35  check_finite(function, "Log odds parameter", beta);
36 
37  variate_generator<RNG&, uniform_01<> > uniform01_rng(rng, uniform_01<>());
38  Eigen::VectorXd theta = softmax(beta);
39  Eigen::VectorXd index = cumulative_sum(theta);
40 
41  double c = uniform01_rng();
42  int b = 0;
43  while (c > index(b))
44  b++;
45  return b + 1;
46 }
47 } // namespace math
48 } // namespace stan
49 #endif
std::vector< T > cumulative_sum(const std::vector< T > &x)
Return the cumulative sum of the specified vector.
void check_finite(const char *function, const char *name, const T_y &y)
Check if y is finite.
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: softmax.hpp:12
int categorical_logit_rng(const Eigen::VectorXd &beta, RNG &rng)
Return a draw from a Categorical distribution given a a vector of unnormalized log probabilities and ...
fvar< T > beta(const fvar< T > &x1, const fvar< T > &x2)
Return fvar with the beta function applied to the specified arguments and its gradient.
Definition: beta.hpp:51

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