Automatic Differentiation
 
Loading...
Searching...
No Matches
gamma_q.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUN_GAMMA_Q_HPP
2#define STAN_MATH_FWD_FUN_GAMMA_Q_HPP
3
13#include <cmath>
14
15namespace stan {
16namespace math {
17
18template <typename T>
19inline fvar<T> gamma_q(const fvar<T>& x1, const fvar<T>& x2) {
20 T u = gamma_q(x1.val_, x2.val_);
21
22 T S = 0;
23 T s = 1;
24 T l = log(x2.val_);
25 T g = tgamma(x1.val_);
26 T dig = digamma(x1.val_);
27
28 int k = 0;
29 T delta = s / (x1.val_ * x1.val_);
30
31 while (fabs(delta) > 1e-6) {
32 S += delta;
33 ++k;
34 s *= -x2.val_ / k;
35 delta = s / ((k + x1.val_) * (k + x1.val_));
36 }
37
38 T der1 = (1.0 - u) * (dig - l) + exp(x1.val_ * l) * S / g;
39 T der2 = -exp(-x2.val_) * pow(x2.val_, x1.val_ - 1.0) / g;
40
41 return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
42}
43
44template <typename T>
45inline fvar<T> gamma_q(const fvar<T>& x1, double x2) {
46 T u = gamma_q(x1.val_, x2);
47 T S = 0;
48 double s = 1;
49 double l = log(x2);
50 T g = tgamma(x1.val_);
51 T dig = digamma(x1.val_);
52
53 int k = 0;
54 T delta = s / (x1.val_ * x1.val_);
55
56 while (fabs(delta) > 1e-6) {
57 S += delta;
58 ++k;
59 s *= -x2 / k;
60 delta = s / ((k + x1.val_) * (k + x1.val_));
61 }
62
63 T der1 = (1.0 - u) * (dig - l) + exp(x1.val_ * l) * S / g;
64
65 return fvar<T>(u, x1.d_ * der1);
66}
67
68template <typename T>
69inline fvar<T> gamma_q(double x1, const fvar<T>& x2) {
70 T u = gamma_q(x1, x2.val_);
71 double g = tgamma(x1);
72 T der2 = -exp(-x2.val_) * pow(x2.val_, x1 - 1.0) / g;
73 return fvar<T>(u, x2.d_ * der2);
74}
75} // namespace math
76} // namespace stan
77#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
fvar< T > log(const fvar< T > &x)
Definition log.hpp:18
fvar< T > tgamma(const fvar< T > &x)
Return the result of applying the gamma function to the specified argument.
Definition tgamma.hpp:21
fvar< T > gamma_q(const fvar< T > &x1, const fvar< T > &x2)
Definition gamma_q.hpp:19
fvar< T > digamma(const fvar< T > &x)
Return the derivative of the log gamma function at the specified argument.
Definition digamma.hpp:23
fvar< T > fabs(const fvar< T > &x)
Definition fabs.hpp:16
fvar< T > exp(const fvar< T > &x)
Definition exp.hpp:15
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Scalar val_
The value of this variable.
Definition fvar.hpp:49
Scalar d_
The tangent (derivative) of this variable.
Definition fvar.hpp:61
This template class represents scalars used in forward-mode automatic differentiation,...
Definition fvar.hpp:40