Stan Math Library  2.12.0
reverse mode automatic differentiation
inc_beta_dda.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDA_HPP
2 #define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDA_HPP
3 
7 #include <cmath>
8 
9 namespace stan {
10  namespace math {
11 
12  template <typename T>
13  T inc_beta_ddb(T a, T b, T z,
14  T digamma_b, T digamma_ab);
15 
38  template <typename T>
39  T inc_beta_dda(T a, T b, T z,
40  T digamma_a, T digamma_ab) {
41  using std::log;
42 
43  if (b > a)
44  if ((0.1 < z && z <= 0.75 && b > 500)
45  || (0.01 < z && z <= 0.1 && b > 2500)
46  || (0.001 < z && z <= 0.01 && b > 1e5))
47  return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
48 
49  if (z > 0.75 && a < 500)
50  return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
51  if (z > 0.9 && a < 2500)
52  return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
53  if (z > 0.99 && a < 1e5)
54  return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
55  if (z > 0.999)
56  return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
57 
58  double threshold = 1e-10;
59 
60  digamma_a += 1.0 / a; // Need digamma(a + 1), not digamma(a);
61 
62  // Common prefactor to regularize numerator and denomentator
63  T prefactor = (a + 1) / (a + b);
64  prefactor = prefactor * prefactor * prefactor;
65 
66  T sum_numer = (digamma_ab - digamma_a) * prefactor;
67  T sum_denom = prefactor;
68 
69  T summand = prefactor * z * (a + b) / (a + 1);
70 
71  T k = 1;
72  digamma_ab += 1.0 / (a + b);
73  digamma_a += 1.0 / (a + 1);
74 
75  while (fabs(summand) > threshold) {
76  sum_numer += (digamma_ab - digamma_a) * summand;
77  sum_denom += summand;
78 
79  summand *= (1 + (a + b) / k) * (1 + k) / (1 + (a + 1) / k);
80  digamma_ab += 1.0 / (a + b + k);
81  digamma_a += 1.0 / (a + 1 + k);
82  ++k;
83  summand *= z / k;
84 
85  if (k > 1e5)
86  domain_error("inc_beta_dda",
87  "did not converge within 10000 iterations", "", "");
88  }
89  return inc_beta(a, b, z) * (log(z) + sum_numer / sum_denom);
90  }
91 
92  }
93 }
94 #endif
fvar< T > fabs(const fvar< T > &x)
Definition: fabs.hpp:15
T inc_beta_dda(T a, T b, T z, T digamma_a, T digamma_ab)
Returns the partial derivative of the regularized incomplete beta function, I_{z}(a, b) with respect to a.
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:14
T inc_beta_ddb(T a, T b, T z, T digamma_b, T digamma_ab)
Returns the partial derivative of the regularized incomplete beta function, I_{z}(a, b) with respect to b.
fvar< T > inc_beta(const fvar< T > &a, const fvar< T > &b, const fvar< T > &x)
Definition: inc_beta.hpp:19
void domain_error(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw a domain error with a consistently formatted message.
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:94

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