Automatic Differentiation
 
Loading...
Searching...
No Matches
lgamma_stirling_diff.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_LGAMMA_STIRLING_DIFF_HPP
2#define STAN_MATH_PRIM_FUN_LGAMMA_STIRLING_DIFF_HPP
3
13#include <cmath>
14
15namespace stan {
16namespace math {
17
18constexpr double lgamma_stirling_diff_useful = 10;
19
42template <typename T>
44 using T_ret = return_type_t<T>;
45
46 if (is_nan(value_of_rec(x))) {
47 return NOT_A_NUMBER;
48 }
49 check_nonnegative("lgamma_stirling_diff", "argument", x);
50
51 if (x == 0) {
52 return INFTY;
53 }
55 return lgamma(x) - lgamma_stirling(x);
56 }
57
58 // Using the Stirling series as expressed in formula 5.11.1. at
59 // https://dlmf.nist.gov/5.11
60 constexpr double stirling_series[]{
61 0.0833333333333333333333333, -0.00277777777777777777777778,
62 0.000793650793650793650793651, -0.000595238095238095238095238,
63 0.000841750841750841750841751, -0.00191752691752691752691753,
64 0.00641025641025641025641026, -0.0295506535947712418300654};
65
66 constexpr int n_stirling_terms = 6;
67 T_ret result(0.0);
68 T_ret multiplier = inv(x);
69 T_ret inv_x_squared = square(multiplier);
70 for (int n = 0; n < n_stirling_terms; n++) {
71 if (n > 0) {
72 multiplier *= inv_x_squared;
73 }
74 result += stirling_series[n] * multiplier;
75 }
76 return result;
77}
78
79} // namespace math
80} // namespace stan
81
82#endif
typename return_type< Ts... >::type return_type_t
Convenience type for the return type of the specified template parameters.
double value_of_rec(const fvar< T > &v)
Return the value of the specified variable.
static constexpr double NOT_A_NUMBER
(Quiet) not-a-number value.
Definition constants.hpp:56
bool is_nan(T &&x)
Returns 1 if the input's value is NaN and 0 otherwise.
Definition is_nan.hpp:22
void check_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
T value_of(const fvar< T > &v)
Return the value of the specified variable.
Definition value_of.hpp:18
return_type_t< T > lgamma_stirling(const T 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
return_type_t< T > lgamma_stirling_diff(const T x)
Return the difference between log of the gamma function and its Stirling approximation.
constexpr double lgamma_stirling_diff_useful
fvar< T > inv(const fvar< T > &x)
Definition inv.hpp:12
static constexpr double INFTY
Positive infinity.
Definition constants.hpp:46
fvar< T > square(const fvar< T > &x)
Definition square.hpp:12
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...