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

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