Stan Math Library  2.14.0
reverse mode automatic differentiation
beta_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_SCAL_PROB_BETA_RNG_HPP
2 #define STAN_MATH_PRIM_SCAL_PROB_BETA_RNG_HPP
3 
4 #include <boost/math/special_functions/gamma.hpp>
5 #include <boost/random/gamma_distribution.hpp>
6 #include <boost/random/uniform_real_distribution.hpp>
7 #include <boost/random/variate_generator.hpp>
24 
25 namespace stan {
26  namespace math {
27 
28  template <class RNG>
29  inline double
30  beta_rng(double alpha,
31  double beta,
32  RNG& rng) {
33  using boost::variate_generator;
34  using boost::random::gamma_distribution;
35  using boost::random::uniform_real_distribution;
36  using std::log;
37  using std::exp;
38  static const char* function("beta_rng");
39  check_positive_finite(function, "First shape parameter", alpha);
40  check_positive_finite(function, "Second shape parameter", beta);
41 
42  // If alpha and beta are large, trust the usual ratio of gammas
43  // method for generating beta random variables. If any parameter
44  // is small, work in log space and use Marsaglia and Tsang's trick
45  if (alpha > 1.0 && beta > 1.0) {
46  variate_generator<RNG&, gamma_distribution<> >
47  rng_gamma_alpha(rng, gamma_distribution<>(alpha, 1.0));
48  variate_generator<RNG&, gamma_distribution<> >
49  rng_gamma_beta(rng, gamma_distribution<>(beta, 1.0));
50  double a = rng_gamma_alpha();
51  double b = rng_gamma_beta();
52  return a / (a + b);
53  } else {
54  variate_generator<RNG&, uniform_real_distribution<> >
55  uniform_rng(rng, uniform_real_distribution<>(0.0, 1.0));
56  variate_generator<RNG&, gamma_distribution<> >
57  rng_gamma_alpha(rng, gamma_distribution<>(alpha + 1, 1.0));
58  variate_generator<RNG&, gamma_distribution<> >
59  rng_gamma_beta(rng, gamma_distribution<>(beta + 1, 1.0));
60  double log_a = log(uniform_rng()) / alpha + log(rng_gamma_alpha());
61  double log_b = log(uniform_rng()) / beta + log(rng_gamma_beta());
62  double log_sum = log_sum_exp(log_a, log_b);
63  return exp(log_a - log_sum);
64  }
65  }
66 
67  }
68 }
69 #endif
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:14
double beta_rng(double alpha, double beta, RNG &rng)
Definition: beta_rng.hpp:30
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:13
void check_positive_finite(const char *function, const char *name, const T_y &y)
Check if y is positive and finite.
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
double uniform_rng(double alpha, double beta, RNG &rng)
Definition: uniform_rng.hpp:20

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