Automatic Differentiation
 
Loading...
Searching...
No Matches
inc_beta_ddb.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_INC_BETA_DDB_HPP
2#define STAN_MATH_PRIM_FUN_INC_BETA_DDB_HPP
3
11#include <cmath>
12
13namespace stan {
14namespace math {
15
16template <typename T>
17T inc_beta_dda(T a, T b, T z, T digamma_a, T digamma_ab);
18
41template <typename T>
42T inc_beta_ddb(T a, T b, T z, T digamma_b, T digamma_ab) {
43 using std::fabs;
44 using std::log;
45 using std::pow;
46
47 if (b > a) {
48 if ((0.1 < z && z <= 0.75 && b > 500) || (0.01 < z && z <= 0.1 && b > 2500)
49 || (0.001 < z && z <= 0.01 && b > 1e5)) {
50 return -inc_beta_dda(b, a, 1 - z, digamma_b, digamma_ab);
51 }
52 }
53
54 if ((z > 0.75 && a < 500) || (z > 0.9 && a < 2500) || (z > 0.99 && a < 1e5)
55 || (z > 0.999)) {
56 return -inc_beta_dda(b, a, 1 - z, digamma_b, digamma_ab);
57 }
58
59 double threshold = 1e-10;
60
61 const T a_plus_b = a + b;
62 const T a_plus_1 = a + 1;
63
64 // Common prefactor to regularize numerator and denominator
65 T prefactor = pow(a_plus_1 / a_plus_b, 3);
66
67 T sum_numer = digamma_ab * prefactor;
68 T sum_denom = prefactor;
69
70 T summand = prefactor * z * a_plus_b / a_plus_1;
71
72 T k = 1;
73 digamma_ab += inv(a_plus_b);
74
75 while (fabs(summand) > threshold) {
76 sum_numer += digamma_ab * summand;
77 sum_denom += summand;
78
79 summand *= (1 + (a_plus_b) / k) * (1 + k) / (1 + a_plus_1 / k);
80 digamma_ab += inv(a_plus_b + k);
81 ++k;
82 summand *= z / k;
83
84 if (k > 1e5) {
85 throw_domain_error("inc_beta_ddb",
86 "did not converge within 100000 iterations", "", "");
87 }
88 }
89
90 return inc_beta(a, b, z) * (log1m(z) - digamma_b + sum_numer / sum_denom);
91}
92
93} // namespace math
94} // namespace stan
95#endif
static constexpr double e()
Return the base of the natural logarithm.
Definition constants.hpp:20
auto pow(const T1 &x1, const T2 &x2)
Definition pow.hpp:32
void throw_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.
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,...
fvar< T > inc_beta(const fvar< T > &a, const fvar< T > &b, const fvar< T > &x)
Definition inc_beta.hpp:19
fvar< T > log1m(const fvar< T > &x)
Definition log1m.hpp:12
fvar< T > inv(const fvar< T > &x)
Definition inv.hpp:13
fvar< T > fabs(const fvar< T > &x)
Definition fabs.hpp:16
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,...
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...