Stan Math Library  2.14.0
reverse mode automatic differentiation
von_mises_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_SCAL_PROB_VON_MISES_RNG_HPP
2 #define STAN_MATH_PRIM_SCAL_PROB_VON_MISES_RNG_HPP
3 
13 #include <cmath>
14 
15 namespace stan {
16  namespace math {
17 
18  // The algorithm used in von_mises_rng is a modified version of the
19  // algorithm in:
20  //
21  // Efficient Simulation of the von Mises Distribution
22  // D. J. Best and N. I. Fisher
23  // Journal of the Royal Statistical Society. Series C (Applied Statistics),
24  // Vol. 28, No. 2 (1979), pp. 152-157
25  //
26  // See licenses/stan-license.txt for Stan license.
27 
28  template <class RNG>
29  inline double
30  von_mises_rng(double mu,
31  double kappa,
32  RNG& rng) {
33  using boost::variate_generator;
34  using std::fmod;
35  using std::log;
36  using std::pow;
37 
38  static const char* function("von_mises_rng");
39 
40  check_finite(function, "mean", mu);
41  check_positive_finite(function, "inverse of variance", kappa);
42 
43  double r = 1 + pow((1 + 4 * kappa * kappa), 0.5);
44  double rho = 0.5 * (r - pow(2 * r, 0.5)) / kappa;
45  double s = 0.5 * (1 + rho * rho) / rho;
46 
47  bool done = 0;
48  double W;
49  while (!done) {
50  double Z = std::cos(pi() * uniform_rng(0.0, 1.0, rng));
51  W = (1 + s * Z) / (s + Z);
52  double Y = kappa * (s - W);
53  double U2 = uniform_rng(0.0, 1.0, rng);
54  done = Y * (2 - Y) - U2 > 0;
55 
56  if (!done)
57  done = log(Y / U2) + 1 - Y >= 0;
58  }
59 
60  double U3 = uniform_rng(0.0, 1.0, rng) - 0.5;
61  double sign = ((U3 >= 0) - (U3 <= 0));
62 
63  // it's really an fmod() with a positivity constraint
64  return sign * std::acos(W)
65  + fmod(fmod(mu, 2*pi())+2*stan::math::pi(),
66  2*pi());
67  }
68 
69  }
70 }
71 #endif
fvar< T > cos(const fvar< T > &x)
Definition: cos.hpp:13
void check_finite(const char *function, const char *name, const T_y &y)
Check if y is finite.
int sign(const T &z)
Definition: sign.hpp:9
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:14
fvar< T > fmod(const fvar< T > &x1, const fvar< T > &x2)
Definition: fmod.hpp:15
void check_positive_finite(const char *function, const char *name, const T_y &y)
Check if y is positive and finite.
double von_mises_rng(double mu, double kappa, RNG &rng)
fvar< T > acos(const fvar< T > &x)
Definition: acos.hpp:14
double pi()
Return the value of pi.
Definition: constants.hpp:85
fvar< T > pow(const fvar< T > &x1, const fvar< T > &x2)
Definition: pow.hpp:17
double uniform_rng(double alpha, double beta, RNG &rng)
Definition: uniform_rng.hpp:20

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