Automatic Differentiation
 
Loading...
Searching...
No Matches
lgamma_stirling_diff.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_LGAMMA_STIRLING_DIFF_HPP
2#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_LGAMMA_STIRLING_DIFF_HPP
3#ifdef STAN_OPENCL
4
6#include <string>
7
8namespace stan {
9namespace math {
10namespace opencl_kernels {
11
12// \cond
13static constexpr const char* lgamma_stirling_diff_device_function
14 = "\n"
15 "#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_LGAMMA_STIRLING_DIFF\n"
16 "#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_LGAMMA_STIRLING_DIFF\n"
17 "#define LGAMMA_STIRLING_DIFF_USEFUL 10\n" STRINGIFY(
18 // \endcond
45 double lgamma_stirling_diff(double x) {
46 if (isnan(x)) {
47 return x;
48 }
49 if (x == 0) {
50 return INFINITY;
51 }
52 if (x < LGAMMA_STIRLING_DIFF_USEFUL) {
53 return lgamma(x) - lgamma_stirling(x);
54 }
55 // Using the Stirling series as expressed in formula 5.11.1. at
56 // https://dlmf.nist.gov/5.11
57 const double stirling_series[] = {
58 0.0833333333333333333333333, -0.00277777777777777777777778,
59 0.000793650793650793650793651, -0.000595238095238095238095238,
60 0.000841750841750841750841751, -0.00191752691752691752691753,
61 0.00641025641025641025641026, -0.0295506535947712418300654};
62 double multiplier = 1 / x;
63 double inv_x_squared = multiplier * multiplier;
64 double result = stirling_series[0] * multiplier;
65 for (int n = 1; n < 6; n++) {
66 multiplier *= inv_x_squared;
67 result += stirling_series[n] * multiplier;
68 }
69 return result;
70 }
71 // \cond
72 ) "\n#endif\n"; // NOLINT
73// \endcond
74
75} // namespace opencl_kernels
76} // namespace math
77} // namespace stan
78
79#endif
80#endif
double lgamma_stirling_diff(double x)
Return the difference between log of the gamma function and its Stirling approximation.
double lgamma_stirling(double x)
Return the Stirling approximation to the lgamma function.
fvar< T > lgamma(const fvar< T > &x)
Return the natural logarithm of the gamma function applied to the specified argument.
Definition lgamma.hpp:21
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
#define STRINGIFY(...)
Definition stringify.hpp:9