Automatic Differentiation
 
Loading...
Searching...
No Matches
trigamma.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_TRIGAMMA_HPP
2#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_TRIGAMMA_HPP
3#ifdef STAN_OPENCL
4
6#include <string>
7
8namespace stan {
9namespace math {
10namespace opencl_kernels {
11// \cond
12static constexpr const char* trigamma_device_function
13 = "\n"
14 "#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_TRIGAMMA\n"
15 "#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_TRIGAMMA\n" STRINGIFY(
16 // \endcond
26 double trigamma(double x) {
27 // negative integers and zero return positive infinity
28 // see http://mathworld.wolfram.com/PolygammaFunction.html
29 if (x <= 0.0 && floor(x) == x) {
30 return INFINITY;
31 }
32
33 // negative non-integers: use the reflection formula
34 // see http://mathworld.wolfram.com/PolygammaFunction.html
35 double value = 0;
36 bool neg = false;
37 if (x <= 0 && floor(x) != x) {
38 neg = true;
39 double v_sqrt = M_PI / sinpi(-x);
40 value = -v_sqrt * v_sqrt;
41 x = -x + 1.0;
42 }
43
44 double small = 0.0001;
45 double large = 5.0;
46 // small value approximation if x <= small.
47 if (x <= small) {
48 value = 1.0 / (x * x);
49 } else {
50 // use recurrence relation until x >= large
51 // see http://mathworld.wolfram.com/PolygammaFunction.html
52 double z = x;
53 while (z < large) {
54 value += 1.0 / (z * z);
55 z += 1.0;
56 }
57
58 // bernoulli numbers
59 double b2 = 1.0 / 6.0;
60 double b4 = -1.0 / 30.0;
61 double b6 = 1.0 / 42.0;
62 double b8 = -1.0 / 30.0;
63
64 // asymptotic expansion as a Laurent series if x >= large
65 // see http://en.wikipedia.org/wiki/Trigamma_function
66 double y = 1.0 / (z * z);
67 value += 0.5 * y
68 + (1.0 + y * (b2 + y * (b4 + y * (b6 + y * b8)))) / z;
69 }
70 if (neg) {
71 return -value;
72 } else {
73 return value;
74 }
75 }
76 // \cond
77 ) "\n#endif\n"; // NOLINT
78// \endcond
79
80} // namespace opencl_kernels
81} // namespace math
82} // namespace stan
83
84#endif
85#endif
double trigamma(double x)
Return the trigamma function applied to the argument.
Definition trigamma.hpp:26
fvar< T > floor(const fvar< T > &x)
Definition floor.hpp:13
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
#define STRINGIFY(...)
Definition stringify.hpp:9