Stan Math Library  2.20.0
reverse mode automatic differentiation
inc_beta_ddb.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDB_HPP
2 #define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDB_HPP
3 
8 #include <cmath>
9 
10 namespace stan {
11 namespace math {
12 
13 template <typename T>
14 T inc_beta_dda(T a, T b, T z, T digamma_a, T digamma_ab);
15 
38 template <typename T>
39 T inc_beta_ddb(T a, T b, T z, T digamma_b, T digamma_ab) {
40  using std::log;
41  using std::pow;
42 
43  if (b > a)
44  if ((0.1 < z && z <= 0.75 && b > 500) || (0.01 < z && z <= 0.1 && b > 2500)
45  || (0.001 < z && z <= 0.01 && b > 1e5))
46  return -inc_beta_dda(b, a, 1 - z, digamma_b, digamma_ab);
47 
48  if ((z > 0.75 && a < 500) || (z > 0.9 && a < 2500) || (z > 0.99 && a < 1e5)
49  || (z > 0.999))
50  return -inc_beta_dda(b, a, 1 - z, digamma_b, digamma_ab);
51 
52  double threshold = 1e-10;
53 
54  const T a_plus_b = a + b;
55  const T a_plus_1 = a + 1;
56 
57  // Common prefactor to regularize numerator and denomentator
58  T prefactor = pow(a_plus_1 / a_plus_b, 3);
59 
60  T sum_numer = digamma_ab * prefactor;
61  T sum_denom = prefactor;
62 
63  T summand = prefactor * z * a_plus_b / a_plus_1;
64 
65  T k = 1;
66  digamma_ab += inv(a_plus_b);
67 
68  while (fabs(summand) > threshold) {
69  sum_numer += digamma_ab * summand;
70  sum_denom += summand;
71 
72  summand *= (1 + (a_plus_b) / k) * (1 + k) / (1 + a_plus_1 / k);
73  digamma_ab += inv(a_plus_b + k);
74  ++k;
75  summand *= z / k;
76 
77  if (k > 1e5)
78  domain_error("inc_beta_ddb", "did not converge within 100000 iterations",
79  "", "");
80  }
81 
82  return inc_beta(a, b, z) * (log(1 - z) - digamma_b + sum_numer / sum_denom);
83 }
84 
85 } // namespace math
86 } // namespace stan
87 #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:12
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:18
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:87
fvar< T > pow(const fvar< T > &x1, const fvar< T > &x2)
Definition: pow.hpp:16
fvar< T > inv(const fvar< T > &x)
Definition: inv.hpp:12

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