gamma_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_SCAL_PROB_GAMMA_RNG_HPP
2 #define STAN_MATH_PRIM_SCAL_PROB_GAMMA_RNG_HPP
3 
10 #include <boost/random/gamma_distribution.hpp>
11 #include <boost/random/variate_generator.hpp>
12 
13 namespace stan {
14 namespace math {
15 
16 /**
17  * Return a gamma random variate for the given shape and inverse
18  * scale parameters using the specified random number generator.
19  *
20  * alpha and beta can each be a scalar or a one-dimensional container. Any
21  * non-scalar inputs must be the same size.
22  *
23  * @tparam T_shape Type of shape parameter
24  * @tparam T_inv Type of inverse scale parameter
25  * @tparam RNG type of random number generator
26  * @param alpha (Sequence of) positive shape parameter(s)
27  * @param beta (Sequence of) positive inverse scale parameter(s)
28  * @param rng random number generator
29  * @return (Sequence of) gamma random variate(s)
30  * @throw std::domain_error if alpha or beta are nonpositive
31  * @throw std::invalid_argument if non-scalar arguments are of different
32  * sizes
33  */
34 template <typename T_shape, typename T_inv, class RNG>
36  const T_shape& alpha, const T_inv& beta, RNG& rng) {
37  using boost::gamma_distribution;
38  using boost::variate_generator;
39 
40  static const char* function = "gamma_rng";
41 
42  check_positive_finite(function, "Shape parameter", alpha);
43  check_positive_finite(function, "Inverse scale parameter", beta);
44  check_consistent_sizes(function, "Shape parameter", alpha,
45  "Inverse scale Parameter", beta);
46 
47  scalar_seq_view<T_shape> alpha_vec(alpha);
48  scalar_seq_view<T_inv> beta_vec(beta);
49  size_t N = max_size(alpha, beta);
51 
52  for (size_t n = 0; n < N; ++n) {
53  // Convert rate (inverse scale) argument to scale for boost
54  variate_generator<RNG&, gamma_distribution<> > gamma_rng(
55  rng, gamma_distribution<>(alpha_vec[n],
56  1 / static_cast<double>(beta_vec[n])));
57  output[n] = gamma_rng();
58  }
59 
60  return output.data();
61 }
62 
63 } // namespace math
64 } // namespace stan
65 #endif
ofstream output
Double_t beta
void check_positive_finite(const char *function, const char *name, const T_y &y)
size_t max_size(const T1 &x1, const T2 &x2)
Definition: max_size.hpp:9
VectorBuilder< true, double, T_shape, T_inv >::type gamma_rng(const T_shape &alpha, const T_inv &beta, RNG &rng)
Definition: gamma_rng.hpp:35
void check_consistent_sizes(const char *function, const char *name1, const T1 &x1, const char *name2, const T2 &x2)