Stan Math Library  2.15.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 
39  template <class RNG>
40  inline double
41  beta_rng(double alpha,
42  double beta,
43  RNG& rng) {
44  using boost::variate_generator;
45  using boost::random::gamma_distribution;
46  using boost::random::uniform_real_distribution;
47  using std::log;
48  using std::exp;
49  static const char* function("beta_rng");
50  check_positive_finite(function, "First shape parameter", alpha);
51  check_positive_finite(function, "Second shape parameter", beta);
52 
53  // If alpha and beta are large, trust the usual ratio of gammas
54  // method for generating beta random variables. If any parameter
55  // is small, work in log space and use Marsaglia and Tsang's trick
56  if (alpha > 1.0 && beta > 1.0) {
57  variate_generator<RNG&, gamma_distribution<> >
58  rng_gamma_alpha(rng, gamma_distribution<>(alpha, 1.0));
59  variate_generator<RNG&, gamma_distribution<> >
60  rng_gamma_beta(rng, gamma_distribution<>(beta, 1.0));
61  double a = rng_gamma_alpha();
62  double b = rng_gamma_beta();
63  return a / (a + b);
64  } else {
65  variate_generator<RNG&, uniform_real_distribution<> >
66  uniform_rng(rng, uniform_real_distribution<>(0.0, 1.0));
67  variate_generator<RNG&, gamma_distribution<> >
68  rng_gamma_alpha(rng, gamma_distribution<>(alpha + 1, 1.0));
69  variate_generator<RNG&, gamma_distribution<> >
70  rng_gamma_beta(rng, gamma_distribution<>(beta + 1, 1.0));
71  double log_a = log(uniform_rng()) / alpha + log(rng_gamma_alpha());
72  double log_b = log(uniform_rng()) / beta + log(rng_gamma_beta());
73  double log_sum = log_sum_exp(log_a, log_b);
74  return exp(log_a - log_sum);
75  }
76  }
77 
78  }
79 }
80 #endif
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:14
double beta_rng(double alpha, double beta, RNG &rng)
Return a pseudorandom Beta variate with the supplied success and failure parameters and specified ran...
Definition: beta_rng.hpp:41
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.