Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
SpecialFunctionsImpl.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2015 Eugene Brevdo <ebrevdo@gmail.com>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_SPECIAL_FUNCTIONS_H
12#define EIGEN_SPECIAL_FUNCTIONS_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18namespace internal {
19
20// Parts of this code are based on the Cephes Math Library.
21//
22// Cephes Math Library Release 2.8: June, 2000
23// Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
24//
25// Permission has been kindly provided by the original author
26// to incorporate the Cephes software into the Eigen codebase:
27//
28// From: Stephen Moshier
29// To: Eugene Brevdo
30// Subject: Re: Permission to wrap several cephes functions in Eigen
31//
32// Hello Eugene,
33//
34// Thank you for writing.
35//
36// If your licensing is similar to BSD, the formal way that has been
37// handled is simply to add a statement to the effect that you are incorporating
38// the Cephes software by permission of the author.
39//
40// Good luck with your project,
41// Steve
42
43/****************************************************************************
44 * Implementation of lgamma *
45 ****************************************************************************/
46
47template <typename Scalar>
48struct lgamma_default_impl {
49 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) {
50 EIGEN_STATIC_ASSERT((!std::is_same<Scalar, Scalar>::value), THIS_TYPE_IS_NOT_SUPPORTED)
51 return Scalar(0);
52 }
53};
54
55template <typename Scalar>
56struct lgamma_impl
57 : special_function_overload_or<special_function_overloads::lgamma_fn, lgamma_default_impl<Scalar>, Scalar> {};
58
59// Since glibc 2.19
60#if defined(__GLIBC__) && ((__GLIBC__ >= 2 && __GLIBC_MINOR__ >= 19) || __GLIBC__ > 2) && \
61 (defined(_DEFAULT_SOURCE) || defined(_BSD_SOURCE) || defined(_SVID_SOURCE))
62#define EIGEN_HAS_LGAMMA_R
63#endif
64
65// Glibc versions before 2.19
66#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ < 19) || __GLIBC__ < 2) && \
67 (defined(_BSD_SOURCE) || defined(_SVID_SOURCE))
68#define EIGEN_HAS_LGAMMA_R
69#endif
70
71template <>
72struct lgamma_impl<float> {
73 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float run(float x) {
74#if !defined(EIGEN_GPU_COMPILE_PHASE) && !defined(__SYCL_DEVICE_ONLY__) && defined(EIGEN_HAS_LGAMMA_R) && \
75 !defined(__APPLE__)
76 int dummy;
77 return ::lgammaf_r(x, &dummy);
78#elif defined(EIGEN_SYCL_DEVICE_ONLY)
79 return cl::sycl::lgamma(x);
80#else
81 return ::lgammaf(x);
82#endif
83 }
84};
85
86template <>
87struct lgamma_impl<double> {
88 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double run(double x) {
89#if !defined(EIGEN_GPU_COMPILE_PHASE) && !defined(__SYCL_DEVICE_ONLY__) && defined(EIGEN_HAS_LGAMMA_R) && \
90 !defined(__APPLE__)
91 int dummy;
92 return ::lgamma_r(x, &dummy);
93#elif defined(EIGEN_SYCL_DEVICE_ONLY)
94 return cl::sycl::lgamma(x);
95#else
96 return ::lgamma(x);
97#endif
98 }
99};
100
101template <>
102struct lgamma_impl<long double> {
103 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE long double run(long double x) {
104#if !defined(EIGEN_GPU_COMPILE_PHASE) && !defined(__SYCL_DEVICE_ONLY__) && defined(EIGEN_HAS_LGAMMA_R) && \
105 !defined(__APPLE__)
106 int dummy;
107 return ::lgammal_r(x, &dummy);
108#else
109 return std::lgamma(x);
110#endif
111 }
112};
113
114#undef EIGEN_HAS_LGAMMA_R
115
116/****************************************************************************
117 * Implementation of digamma (psi), based on Cephes *
118 ****************************************************************************/
119
120/*
121 *
122 * Polynomial evaluation helper for the Psi (digamma) function.
123 *
124 * digamma_impl_maybe_poly::run(s) evaluates the asymptotic Psi expansion for
125 * input Scalar s, assuming s is above 10.0.
126 *
127 * If s is above a certain threshold for the given Scalar type, zero
128 * is returned. Otherwise the polynomial is evaluated with enough
129 * coefficients for results matching Scalar machine precision.
130 *
131 *
132 */
133template <typename Scalar>
134struct digamma_impl_maybe_poly {
135 EIGEN_STATIC_ASSERT((std::is_same<Scalar, Scalar>::value == false), THIS_TYPE_IS_NOT_SUPPORTED)
136
137 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { return Scalar(0); }
138};
139
140template <>
141struct digamma_impl_maybe_poly<float> {
142 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float run(const float s) {
143 constexpr float A[] = {-4.16666666666666666667E-3f, 3.96825396825396825397E-3f, -8.33333333333333333333E-3f,
144 8.33333333333333333333E-2f};
145
146 float z;
147 if (s < 1.0e8f) {
148 z = 1.0f / (s * s);
149 return z * internal::ppolevl<float, 3>::run(z, A);
150 } else
151 return 0.0f;
152 }
153};
154
155template <>
156struct digamma_impl_maybe_poly<double> {
157 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double run(const double s) {
158 constexpr double A[] = {8.33333333333333333333E-2, -2.10927960927960927961E-2, 7.57575757575757575758E-3,
159 -4.16666666666666666667E-3, 3.96825396825396825397E-3, -8.33333333333333333333E-3,
160 8.33333333333333333333E-2};
161
162 double z;
163 if (s < 1.0e17) {
164 z = 1.0 / (s * s);
165 return z * internal::ppolevl<double, 6>::run(z, A);
166 } else
167 return 0.0;
168 }
169};
170
171template <typename Scalar>
172struct digamma_default_impl {
173 EIGEN_DEVICE_FUNC static Scalar run(Scalar x) {
174 /*
175 *
176 * Psi (digamma) function (modified for Eigen)
177 *
178 *
179 * SYNOPSIS:
180 *
181 * double x, y, psi();
182 *
183 * y = psi( x );
184 *
185 *
186 * DESCRIPTION:
187 *
188 * d -
189 * psi(x) = -- ln | (x)
190 * dx
191 *
192 * is the logarithmic derivative of the gamma function.
193 * For integer x,
194 * n-1
195 * -
196 * psi(n) = -EUL + > 1/k.
197 * -
198 * k=1
199 *
200 * If x is negative, it is transformed to a positive argument by the
201 * reflection formula psi(1-x) = psi(x) + pi cot(pi x).
202 * For general positive x, the argument is made greater than 10
203 * using the recurrence psi(x+1) = psi(x) + 1/x.
204 * Then the following asymptotic expansion is applied:
205 *
206 * inf. B
207 * - 2k
208 * psi(x) = log(x) - 1/2x - > -------
209 * - 2k
210 * k=1 2k x
211 *
212 * where the B2k are Bernoulli numbers.
213 *
214 * ACCURACY (float):
215 * Relative error (except absolute when |psi| < 1):
216 * arithmetic domain # trials peak rms
217 * IEEE 0,30 30000 1.3e-15 1.4e-16
218 * IEEE -30,0 40000 1.5e-15 2.2e-16
219 *
220 * ACCURACY (double):
221 * Absolute error, relative when |psi| > 1 :
222 * arithmetic domain # trials peak rms
223 * IEEE -33,0 30000 8.2e-7 1.2e-7
224 * IEEE 0,33 100000 7.3e-7 7.7e-8
225 *
226 * ERROR MESSAGES:
227 * message condition value returned
228 * psi singularity x integer <=0 INFINITY
229 */
230
231 Scalar p, q, nz, s, w, y;
232 bool negative = false;
233
234 const Scalar nan = NumTraits<Scalar>::quiet_NaN();
235 const Scalar m_pi = Scalar(EIGEN_PI);
236
237 const Scalar zero = Scalar(0);
238 const Scalar one = Scalar(1);
239 const Scalar half = Scalar(0.5);
240 nz = zero;
241
242 // Near 0, psi(x) ~ -1/x - gamma.
243 // For x = +0.0: psi(+0.0) -> -infinity.
244 // For x = -0.0: psi(-0.0) -> +infinity.
245 if (x == zero) {
246 return (std::signbit(x)) ? NumTraits<Scalar>::infinity() : -NumTraits<Scalar>::infinity();
247 }
248 if (x < zero) {
249 negative = true;
250 q = x;
251 p = numext::floor(q);
252 if (p == q) {
253 return nan;
254 }
255 /* Remove the zeros of tan(m_pi x)
256 * by subtracting the nearest integer from x
257 */
258 nz = q - p;
259 if (nz != half) {
260 if (nz > half) {
261 p += one;
262 nz = q - p;
263 }
264 nz = m_pi / numext::tan(m_pi * nz);
265 } else {
266 nz = zero;
267 }
268 x = one - x;
269 }
270
271 /* use the recurrence psi(x+1) = psi(x) + 1/x. */
272 s = x;
273 w = zero;
274 while (s < Scalar(10)) {
275 w += one / s;
276 s += one;
277 }
278
279 y = digamma_impl_maybe_poly<Scalar>::run(s);
280
281 y = numext::log(s) - (half / s) - y - w;
282
283 return (negative) ? y - nz : y;
284 }
285};
286
287template <typename Scalar>
288struct digamma_impl
289 : special_function_overload_or<special_function_overloads::digamma_fn, digamma_default_impl<Scalar>, Scalar> {};
290
291template <typename T>
292struct has_erf : has_special_function_overload<special_function_overloads::erf_fn, T> {};
293template <typename T>
294struct has_erfc : has_special_function_overload<special_function_overloads::erfc_fn, T> {};
295
296/***************************************************************************
297 * Implementation of erfc.
298 ****************************************************************************/
299template <typename Scalar>
300struct generic_fast_erfc {
301 template <typename T>
302 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T run(const T& x_in);
303};
304
305template <>
306template <typename T>
307EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_fast_erfc<float>::run(const T& x_in) {
308 constexpr float kClamp = 11.0f;
309 const T x = pmin<PropagateNaN>(pmax<PropagateNaN>(x_in, pset1<T>(-kClamp)), pset1<T>(kClamp));
310
311 // erfc(x) = 1 + x * S(x^2), |x| <= 1.
312 //
313 // Coefficients for S and T generated with Rminimax command:
314 // ./ratapprox --function="erfc(x)-1" --dom='[-1,1]' --type=[11,0] --num="odd"
315 // --numF="[SG]" --denF="[SG]" --log --dispCoeff="dec"
316 constexpr float alpha[] = {5.61802298761904239654541015625e-04, -4.91381669417023658752441406250e-03,
317 2.67075151205062866210937500000e-02, -1.12800106406211853027343750000e-01,
318 3.76122951507568359375000000000e-01, -1.12837910652160644531250000000e+00};
319 const T x2 = pmul(x, x);
320 const T one = pset1<T>(1.0f);
321 const T erfc_small = pmadd(x, ppolevl<T, 5>::run(x2, alpha), one);
322
323 // Return early if we don't need the more expensive approximation for any
324 // entry in a.
325 const T x_abs_gt_one_mask = pcmp_lt(one, x2);
326 if (!predux_any(x_abs_gt_one_mask)) return erfc_small;
327
328 // erfc(x) = exp(-x^2) * 1/x * P(1/x^2) / Q(1/x^2), 1 < x < 9.
329 //
330 // Coefficients for P and Q generated with Rminimax command:
331 // ./ratapprox --function="erfc(1/sqrt(x))*exp(1/x)/sqrt(x)"
332 // --dom='[0.01,1]' --type=[3,4] --numF="[SG]" --denF="[SG]" --log
333 // --dispCoeff="dec"
334 constexpr float gamma[] = {1.0208116471767425537109375e-01f, 4.2920666933059692382812500e-01f,
335 3.2379078865051269531250000e-01f, 5.3971976041793823242187500e-02f};
336 constexpr float delta[] = {1.7251677811145782470703125e-02f, 3.9137163758277893066406250e-01f,
337 1.0000000000000000000000000e+00f, 6.2173241376876831054687500e-01f,
338 9.5662862062454223632812500e-02f};
339 const T x2_lo = twoprod_low(x, x, x2);
340 // Here we use that
341 // exp(-x^2) = exp(-(x2+x2_lo)^2) ~= exp(-x2)*exp(-x2_lo) ~= exp(-x2)*(1-x2_lo)
342 // since x2_lo < kClamp * eps << 1 in the region we care about. This trick reduces the max error
343 // from 34 ulps to below 5 ulps.
344 const T exp2_hi = pexp(pnegate(x2));
345 const T z = pnmadd(exp2_hi, x2_lo, exp2_hi);
346 const T q2 = preciprocal(x2);
347 const T num = ppolevl<T, 3>::run(q2, gamma);
348 const T denom = pmul(x, ppolevl<T, 4>::run(q2, delta));
349 const T r = pdiv(num, denom);
350 const T maybe_two = pselect(pcmp_lt(x, pset1<T>(0.0f)), pset1<T>(2.0f), pset1<T>(0.0f));
351 const T erfc_large = pmadd(z, r, maybe_two);
352 return pselect(x_abs_gt_one_mask, erfc_large, erfc_small);
353}
354
355// Computes erf(x)/x for |x| <= 1. Used by both erf and erfc implementations.
356// Takes x2 = x^2 as input.
357//
358// PRECONDITION: x2 <= 1.
359template <typename T>
360EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T erf_over_x_double_small(const T& x2) {
361 // erf(x)/x = S(x^2) / T(x^2), x^2 <= 1.
362 //
363 // Coefficients for S and T generated with Rminimax command:
364 // ./ratapprox --function="erf(x)" --dom='[-1,1]' --type=[9,10]
365 // --num="odd" --numF="[D]" --den="even" --denF="[D]" --log --dispCoeff="dec"
366 constexpr double alpha[] = {1.9493725660006057018823477644531294572516344487667083740234375e-04,
367 1.8272566210022942682217328425053892715368419885635375976562500e-03,
368 4.5303363351690106863856044583371840417385101318359375000000000e-02,
369 1.4215015503619179981775744181504705920815467834472656250000000e-01,
370 1.1283791670955125585606992899556644260883331298828125000000000e+00};
371 constexpr double beta[] = {2.0294484101083099089526257108317963684385176748037338256835938e-05,
372 6.8117805899186819641732970609382391558028757572174072265625000e-04,
373 1.0582026056098614921752165685120417037978768348693847656250000e-02,
374 9.3252603143757495374188692949246615171432495117187500000000000e-02,
375 4.5931062818368939559832142549566924571990966796875000000000000e-01,
376 1.0};
377 const T num_small = ppolevl<T, 4>::run(x2, alpha);
378 const T denom_small = ppolevl<T, 5>::run(x2, beta);
379 return pdiv(num_small, denom_small);
380}
381
382// erfc(x) = exp(-x^2) * 1/x * P(1/x^2) / Q(1/x^2), 1 < x < 28.
383//
384// Coefficients for P and Q generated with Rminimax command:
385// ./ratapprox --function="erfc(1/sqrt(x))*exp(1/x)/sqrt(x)" --dom='[0.0013717,1]' --type=[9,9] --numF="[D]"
386// --denF="[D]" --log --dispCoeff="dec"
387//
388// PRECONDITION: 1 < x < 28.
389template <typename T>
390EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T erfc_double_large(const T& x, const T& x2) {
391 constexpr double gamma[] = {1.5252844933226974316088642158462107545346952974796295166015625e-04,
392 1.0909912393738931124520519233556115068495273590087890625000000e-02,
393 1.0628604636755033252537572252549580298364162445068359375000000e-01,
394 3.3492472973137982217295416376146022230386734008789062500000000e-01,
395 4.5065776215933289750026347064704168587923049926757812500000000e-01,
396 2.9433039130294824659017649537418037652969360351562500000000000e-01,
397 9.8792676360600226170838311645638896152377128601074218750000000e-02,
398 1.7095935395503719655962981960328761488199234008789062500000000e-02,
399 1.4249109729504577659398023570247460156679153442382812500000000e-03,
400 4.4567378313647954771875570045835956989321857690811157226562500e-05};
401 constexpr double delta[] = {2.041985103115789845773520028160419315099716186523437500000000e-03,
402 5.316030659946043707142493417450168635696172714233398437500000e-02,
403 3.426242193784684864077405563875799998641014099121093750000000e-01,
404 8.565637124308049799026321124983951449394226074218750000000000e-01,
405 1.000000000000000000000000000000000000000000000000000000000000e+00,
406 5.968805280570776972126623149961233139038085937500000000000000e-01,
407 1.890922854723317836356244470152887515723705291748046875000000e-01,
408 3.152505418656005586885981983868987299501895904541015625000000e-02,
409 2.565085751861882583380047861965067568235099315643310546875000e-03,
410 7.899362131678837697403017248376499992446042597293853759765625e-05};
411 // Compute exp(-x^2).
412 const T x2_lo = twoprod_low(x, x, x2);
413 // Here we use that
414 // exp(-x^2) = exp(-(x2+x2_lo)^2) ~= exp(-x2)*exp(-x2_lo) ~= exp(-x2)*(1-x2_lo)
415 // since x2_lo < kClamp * eps << 1 in the region we care about. This trick reduces the max error
416 // from 258 ulps to below 7 ulps.
417 const T exp2_hi = pexp(pnegate(x2));
418 const T z = pnmadd(exp2_hi, x2_lo, exp2_hi);
419 // Compute r = P / Q.
420 const T q2 = preciprocal(x2);
421 const T num_large = ppolevl<T, 9>::run(q2, gamma);
422 const T denom_large = pmul(x, ppolevl<T, 9>::run(q2, delta));
423 const T r = pdiv(num_large, denom_large);
424 const T maybe_two = pselect(pcmp_lt(x, pset1<T>(0.0)), pset1<T>(2.0), pset1<T>(0.0));
425 return pmadd(z, r, maybe_two);
426}
427
428template <>
429template <typename T>
430EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_fast_erfc<double>::run(const T& x_in) {
431 // Clamp x to [-28:28] beyond which erfc(x) is either two or zero (below the underflow threshold).
432 // This avoids having to deal with twoprod(x,x) producing NaN for sufficiently large x.
433 constexpr double kClamp = 28.0;
434 const T x = pmin<PropagateNaN>(pmax<PropagateNaN>(x_in, pset1<T>(-kClamp)), pset1<T>(kClamp));
435
436 // For |x| < 1, we use erfc(x) = 1 - erf(x).
437 const T x2 = pmul(x, x);
438 const T one = pset1<T>(1.0);
439 const T erfc_small = pnmadd(x, erf_over_x_double_small(x2), one);
440
441 // Return early if we don't need the more expensive approximation for any
442 // entry in a.
443 const T x_abs_gt_one_mask = pcmp_lt(one, x2);
444 if (!predux_any(x_abs_gt_one_mask)) return erfc_small;
445
446 const T erfc_large = erfc_double_large(x, x2);
447 return pselect(x_abs_gt_one_mask, erfc_large, erfc_small);
448}
449
450template <typename T>
451struct erfc_impl {
452 using Scalar = typename unpacket_traits<T>::type;
453 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T& x) { return run_impl(x, std::is_same<T, Scalar>()); }
454
455 private:
456 // Packets of float/double: vectorized rational approximation.
457 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_impl(const T& x, std::false_type) {
458 return generic_fast_erfc<Scalar>::run(x);
459 }
460 // Any other scalar type: defer to an erfc found by argument-dependent lookup
461 // (or std::erfc), keeping custom scalars on their own implementation instead
462 // of the float/double-tuned polynomials.
463 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_impl(const T& x, std::true_type) {
464 EIGEN_STATIC_ASSERT_NON_INTEGER(T)
465 return run_scalar(x, has_erfc<T>());
466 }
467 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_scalar(const T& x, std::true_type) {
468 return special_function_overloads::erfc_fn::call<T>(x);
469 }
470 // Reject the type here instead of letting overload resolution fail inside the
471 // call above: the approximations in this file are tuned for float and double
472 // and are not valid for an arbitrary scalar, so a scalar type that wants erfc
473 // has to supply it.
474 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_scalar(const T& x, std::false_type) {
475 EIGEN_STATIC_ASSERT(has_erfc<T>::value, SCALAR_TYPE_MUST_PROVIDE_AN_ERFC_OVERLOAD_FOUND_BY_ADL_OR_IN_NAMESPACE_STD)
476 return x;
477 }
478};
479
480template <>
481struct erfc_impl<float> {
482 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float run(const float x) {
483#if defined(EIGEN_SYCL_DEVICE_ONLY)
484 return cl::sycl::erfc(x);
485#else
486 return generic_fast_erfc<float>::run(x);
487#endif
488 }
489};
490
491template <>
492struct erfc_impl<double> {
493 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double run(const double x) {
494#if defined(EIGEN_SYCL_DEVICE_ONLY)
495 return cl::sycl::erfc(x);
496#else
497 return generic_fast_erfc<double>::run(x);
498#endif
499 }
500};
501
502/****************************************************************************
503 * Implementation of erf.
504 ****************************************************************************/
505
506template <typename Scalar>
507struct generic_fast_erf {
508 template <typename T>
509 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T run(const T& x_in);
510};
511
518template <>
519template <typename T>
520EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_fast_erf<float>::run(const T& x) {
521 // The monomial coefficients of the numerator polynomial (odd).
522 constexpr float alpha[] = {2.123732201653183437883853912353515625e-06f, 2.861979592125862836837768554687500000e-04f,
523 3.658048342913389205932617187500000000e-03f, 5.243302136659622192382812500000000000e-02f,
524 1.874160766601562500000000000000000000e-01f, 1.128379106521606445312500000000000000e+00f};
525
526 // The monomial coefficients of the denominator polynomial (even).
527 constexpr float beta[] = {3.89185734093189239501953125000e-05f, 1.14329601638019084930419921875e-03f,
528 1.47520881146192550659179687500e-02f, 1.12945675849914550781250000000e-01f,
529 4.99425798654556274414062500000e-01f, 1.0f};
530
531 // Since the polynomials are odd/even, we need x^2.
532 // Since erf(4) == 1 in float, we clamp x^2 to 16 to avoid computing Inf/Inf below.
533 // NaN need not survive this clamp: multiplying by x below restores it.
534 const T x2 = pmin(pset1<T>(16.0f), pmul(x, x));
535
536 // Evaluate the numerator polynomial p.
537 T p = ppolevl<T, 5>::run(x2, alpha);
538 p = pmul(x, p);
539
540 // Evaluate the denominator polynomial q.
541 T q = ppolevl<T, 5>::run(x2, beta);
542 const T r = pdiv(p, q);
543
544 // Clamp to [-1:1].
545 return pmax<PropagateNaN>(pmin<PropagateNaN>(r, pset1<T>(1.0f)), pset1<T>(-1.0f));
546}
547
548template <>
549template <typename T>
550EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_fast_erf<double>::run(const T& x_in) {
551 // Clamp x to [-28:28] beyond which erf(x) is ±1 within double precision.
552 // This avoids NaN from twoprod and exp operations for infinite inputs.
553 constexpr double kClamp = 28.0;
554 const T x = pmin<PropagateNaN>(pmax<PropagateNaN>(x_in, pset1<T>(-kClamp)), pset1<T>(kClamp));
555 T x2 = pmul(x, x);
556 T erf_small = pmul(x, erf_over_x_double_small(x2));
557
558 // Return early if we don't need the more expensive approximation for any
559 // entry in a.
560 const T one = pset1<T>(1.0);
561 const T x_abs_gt_one_mask = pcmp_lt(one, x2);
562 if (!predux_any(x_abs_gt_one_mask)) return erf_small;
563
564 // For |x| > 1, use erf(x) = 1 - erfc(x).
565 const T erf_large = psub(one, erfc_double_large(x, x2));
566 return pselect(x_abs_gt_one_mask, erf_large, erf_small);
567}
568
569template <typename T>
570struct erf_impl {
571 using Scalar = typename unpacket_traits<T>::type;
572 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T& x) { return run_impl(x, std::is_same<T, Scalar>()); }
573
574 private:
575 // Packets of float/double: vectorized rational approximation.
576 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_impl(const T& x, std::false_type) {
577 return generic_fast_erf<Scalar>::run(x);
578 }
579 // Any other scalar type: defer to an erf found by argument-dependent lookup
580 // (or std::erf), keeping custom scalars on their own implementation instead
581 // of the float/double-tuned polynomials.
582 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_impl(const T& x, std::true_type) {
583 EIGEN_STATIC_ASSERT_NON_INTEGER(T)
584 return run_scalar(x, has_erf<T>());
585 }
586 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_scalar(const T& x, std::true_type) {
587 return special_function_overloads::erf_fn::call<T>(x);
588 }
589 // Reject the type here instead of letting overload resolution fail inside the
590 // call above: the approximations in this file are tuned for float and double
591 // and are not valid for an arbitrary scalar, so a scalar type that wants erf
592 // has to supply it.
593 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run_scalar(const T& x, std::false_type) {
594 EIGEN_STATIC_ASSERT(has_erf<T>::value, SCALAR_TYPE_MUST_PROVIDE_AN_ERF_OVERLOAD_FOUND_BY_ADL_OR_IN_NAMESPACE_STD)
595 return x;
596 }
597};
598
599template <>
600struct erf_impl<float> {
601 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float run(const float x) {
602#if defined(EIGEN_SYCL_DEVICE_ONLY)
603 return cl::sycl::erf(x);
604#else
605 return generic_fast_erf<float>::run(x);
606#endif
607 }
608};
609
610template <>
611struct erf_impl<double> {
612 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double run(const double x) {
613#if defined(EIGEN_SYCL_DEVICE_ONLY)
614 return cl::sycl::erf(x);
615#else
616 return generic_fast_erf<double>::run(x);
617#endif
618 }
619};
620
621/***************************************************************************
622 * Implementation of ndtri. *
623 ****************************************************************************/
624
625/* Inverse of Normal distribution function (modified for Eigen).
626 *
627 *
628 * SYNOPSIS:
629 *
630 * double x, y, ndtri();
631 *
632 * x = ndtri( y );
633 *
634 *
635 *
636 * DESCRIPTION:
637 *
638 * Returns the argument, x, for which the area under the
639 * Gaussian probability density function (integrated from
640 * minus infinity to x) is equal to y.
641 *
642 *
643 * For small arguments 0 < y < exp(-2), the program computes
644 * z = sqrt( -2.0 * log(y) ); then the approximation is
645 * x = z - log(z)/z - (1/z) P(1/z) / Q(1/z).
646 * There are two rational functions P/Q, one for 0 < y < exp(-32)
647 * and the other for y up to exp(-2). For larger arguments,
648 * w = y - 0.5, and x/sqrt(2pi) = w + w**3 R(w**2)/S(w**2)).
649 *
650 *
651 * ACCURACY:
652 *
653 * Relative error:
654 * arithmetic domain # trials peak rms
655 * DEC 0.125, 1 5500 9.5e-17 2.1e-17
656 * DEC 6e-39, 0.135 3500 5.7e-17 1.3e-17
657 * IEEE 0.125, 1 20000 7.2e-16 1.3e-16
658 * IEEE 3e-308, 0.135 50000 4.6e-16 9.8e-17
659 *
660 *
661 * ERROR MESSAGES:
662 *
663 * message condition value returned
664 * ndtri domain x == 0 -INF
665 * ndtri domain x == 1 INF
666 * ndtri domain x < 0, x > 1 NAN
667 */
668/*
669 Cephes Math Library Release 2.2: June, 1992
670 Copyright 1985, 1987, 1992 by Stephen L. Moshier
671 Direct inquiries to 30 Frost Street, Cambridge, MA 02140
672*/
673
674// TODO: Add a cheaper approximation for float.
675
676template <typename T, bool IsScalar = is_scalar<T>::value>
677struct flipsign_impl;
678
679template <typename T>
680struct flipsign_impl<T, false> {
681 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T run(const T& should_flipsign, const T& x) {
682 const T sign_mask = psignmask<T>();
683 const T sign_bit = pand<T>(should_flipsign, sign_mask);
684 return pxor<T>(sign_bit, x);
685 }
686};
687
688template <typename T>
689struct flipsign_impl<T, true> {
690 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T run(const T& should_flipsign, const T& x) {
691 return should_flipsign == T(0) ? x : -x;
692 }
693};
694
695template <typename T>
696EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T flipsign(const T& should_flipsign, const T& x) {
697 return flipsign_impl<T>::run(should_flipsign, x);
698}
699
700template <typename T, bool IsScalar = is_scalar<T>::value>
701struct ndtri_negative_infinity_impl;
702
703template <typename T>
704struct ndtri_negative_infinity_impl<T, false> {
705 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T run(const T& positive_infinity) {
706 return por(psignmask<T>(), positive_infinity);
707 }
708};
709
710template <typename T>
711struct ndtri_negative_infinity_impl<T, true> {
712 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T run(const T& positive_infinity) { return -positive_infinity; }
713};
714
715// We split this computation in to two so that in the scalar path
716// only one branch is evaluated (due to our template specialization of pselect
717// being an if statement.)
718
719template <typename T, typename ScalarType>
720EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_ndtri_gt_exp_neg_two(const T& b) {
721 const ScalarType p0[] = {ScalarType(-5.99633501014107895267e1), ScalarType(9.80010754185999661536e1),
722 ScalarType(-5.66762857469070293439e1), ScalarType(1.39312609387279679503e1),
723 ScalarType(-1.23916583867381258016e0)};
724 const ScalarType q0[] = {ScalarType(1.0),
725 ScalarType(1.95448858338141759834e0),
726 ScalarType(4.67627912898881538453e0),
727 ScalarType(8.63602421390890590575e1),
728 ScalarType(-2.25462687854119370527e2),
729 ScalarType(2.00260212380060660359e2),
730 ScalarType(-8.20372256168333339912e1),
731 ScalarType(1.59056225126211695515e1),
732 ScalarType(-1.18331621121330003142e0)};
733 const T sqrt2pi = pset1<T>(ScalarType(2.50662827463100050242e0));
734 const T half = pset1<T>(ScalarType(0.5));
735 T c, c2, ndtri_gt_exp_neg_two;
736
737 c = psub(b, half);
738 c2 = pmul(c, c);
739 ndtri_gt_exp_neg_two =
740 pmadd(c, pmul(c2, pdiv(internal::ppolevl<T, 4>::run(c2, p0), internal::ppolevl<T, 8>::run(c2, q0))), c);
741 return pmul(ndtri_gt_exp_neg_two, sqrt2pi);
742}
743
744template <typename T, typename ScalarType>
745EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_ndtri_lt_exp_neg_two(const T& b, const T& should_flipsign) {
746 /* Approximation for interval z = sqrt(-2 log a ) between 2 and 8
747 * i.e., a between exp(-2) = .135 and exp(-32) = 1.27e-14.
748 */
749 const ScalarType p1[] = {ScalarType(4.05544892305962419923e0), ScalarType(3.15251094599893866154e1),
750 ScalarType(5.71628192246421288162e1), ScalarType(4.40805073893200834700e1),
751 ScalarType(1.46849561928858024014e1), ScalarType(2.18663306850790267539e0),
752 ScalarType(-1.40256079171354495875e-1), ScalarType(-3.50424626827848203418e-2),
753 ScalarType(-8.57456785154685413611e-4)};
754 const ScalarType q1[] = {ScalarType(1.0),
755 ScalarType(1.57799883256466749731e1),
756 ScalarType(4.53907635128879210584e1),
757 ScalarType(4.13172038254672030440e1),
758 ScalarType(1.50425385692907503408e1),
759 ScalarType(2.50464946208309415979e0),
760 ScalarType(-1.42182922854787788574e-1),
761 ScalarType(-3.80806407691578277194e-2),
762 ScalarType(-9.33259480895457427372e-4)};
763 /* Approximation for interval z = sqrt(-2 log a ) between 8 and 64
764 * i.e., a between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890.
765 */
766 const ScalarType p2[] = {ScalarType(3.23774891776946035970e0), ScalarType(6.91522889068984211695e0),
767 ScalarType(3.93881025292474443415e0), ScalarType(1.33303460815807542389e0),
768 ScalarType(2.01485389549179081538e-1), ScalarType(1.23716634817820021358e-2),
769 ScalarType(3.01581553508235416007e-4), ScalarType(2.65806974686737550832e-6),
770 ScalarType(6.23974539184983293730e-9)};
771 const ScalarType q2[] = {ScalarType(1.0),
772 ScalarType(6.02427039364742014255e0),
773 ScalarType(3.67983563856160859403e0),
774 ScalarType(1.37702099489081330271e0),
775 ScalarType(2.16236993594496635890e-1),
776 ScalarType(1.34204006088543189037e-2),
777 ScalarType(3.28014464682127739104e-4),
778 ScalarType(2.89247864745380683936e-6),
779 ScalarType(6.79019408009981274425e-9)};
780 const T eight = pset1<T>(ScalarType(8.0));
781 const T neg_two = pset1<T>(ScalarType(-2));
782 T x, x0, correction, z;
783
784 x = psqrt(pmul(neg_two, plog(b)));
785 x0 = psub(x, pdiv(plog(x), x));
786 z = preciprocal(x);
787 correction =
788 pselect(pcmp_lt(x, eight), pdiv(internal::ppolevl<T, 8>::run(z, p1), internal::ppolevl<T, 8>::run(z, q1)),
789 pdiv(internal::ppolevl<T, 8>::run(z, p2), internal::ppolevl<T, 8>::run(z, q2)));
790 return flipsign(should_flipsign, pnmadd(z, correction, x0));
791}
792
793template <typename T, typename ScalarType>
794EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T generic_ndtri(const T& a) {
795 const T maxnum = pinf<T>();
796 const T neg_maxnum = ndtri_negative_infinity_impl<T>::run(maxnum);
797
798 const T zero = pset1<T>(ScalarType(0));
799 const T one = pset1<T>(ScalarType(1));
800 // exp(-2)
801 const T exp_neg_two = pset1<T>(ScalarType(0.13533528323661269189));
802 T b, ndtri, should_flipsign;
803
804 should_flipsign = pcmp_le(a, psub(one, exp_neg_two));
805 b = pselect(should_flipsign, a, psub(one, a));
806
807 ndtri = pselect(pcmp_lt(exp_neg_two, b), generic_ndtri_gt_exp_neg_two<T, ScalarType>(b),
808 generic_ndtri_lt_exp_neg_two<T, ScalarType>(b, should_flipsign));
809
810 return pselect(pcmp_eq(a, zero), neg_maxnum, pselect(pcmp_eq(one, a), maxnum, ndtri));
811}
812
813template <typename Scalar>
814struct ndtri_default_impl {
815 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar x) { return generic_ndtri<Scalar, Scalar>(x); }
816};
817
818template <typename Scalar>
819struct ndtri_impl
820 : special_function_overload_or<special_function_overloads::ndtri_fn, ndtri_default_impl<Scalar>, Scalar> {};
821
822/**************************************************************************************************************
823 * Implementation of igammac (complemented incomplete gamma integral), based on Cephes *
824 **************************************************************************************************************/
825
826// NOTE: cephes_helper is also used to implement zeta
827template <typename Scalar>
828struct cephes_helper {
829 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar machep() {
830 eigen_assert(false && "machep not supported for this type");
831 return 0.0;
832 }
833 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar big() {
834 eigen_assert(false && "big not supported for this type");
835 return 0.0;
836 }
837 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar biginv() {
838 eigen_assert(false && "biginv not supported for this type");
839 return 0.0;
840 }
841};
842
843template <>
844struct cephes_helper<float> {
845 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float machep() {
846 return NumTraits<float>::epsilon() / 2; // 1.0 - machep == 1.0
847 }
848 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float big() {
849 // use epsneg (1.0 - epsneg == 1.0)
850 return 1.0f / (NumTraits<float>::epsilon() / 2);
851 }
852 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float biginv() {
853 // epsneg
854 return machep();
855 }
856};
857
858template <>
859struct cephes_helper<double> {
860 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double machep() {
861 return NumTraits<double>::epsilon() / 2; // 1.0 - machep == 1.0
862 }
863 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double big() { return 1.0 / NumTraits<double>::epsilon(); }
864 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double biginv() {
865 // inverse of eps
866 return NumTraits<double>::epsilon();
867 }
868};
869
870enum IgammaComputationMode { VALUE, DERIVATIVE, SAMPLE_DERIVATIVE };
871
872template <typename Scalar>
873EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar main_igamma_term(Scalar a, Scalar x) {
874 /* Compute x**a * exp(-x) / gamma(a) */
875 Scalar logax = a * numext::log(x) - x - lgamma_impl<Scalar>::run(a);
876 if (logax < -numext::log(NumTraits<Scalar>::highest()) ||
877 // Assuming x and a aren't Nan.
878 (numext::isnan)(logax)) {
879 return Scalar(0);
880 }
881 return numext::exp(logax);
882}
883
884/* Clamp a probability to [0, 1], passing NaN through: numext::maxi(0, NaN) is 0, which would turn a failed
885 * evaluation into a confident answer. */
886template <typename Scalar>
887EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar igamma_clamp_to_unit_interval(Scalar r) {
888 return (numext::isnan)(r) ? r : numext::mini(Scalar(1), numext::maxi(Scalar(0), r));
889}
890
891template <typename Scalar, IgammaComputationMode mode>
892EIGEN_DEVICE_FUNC constexpr int igamma_num_iterations() {
893 /* Returns the maximum number of internal iterations for igamma computation.
894 */
895 return mode == VALUE ? 2000
896 : std::is_same<Scalar, float>::value ? 200
897 : std::is_same<Scalar, double>::value ? 500
898 : 2000;
899}
900
901/* log1p(d) - d for |d| < 1/4, with s = d / (2 + d), so that log1p(d) = 2 atanh(s):
902 * log1p(d) - d = -d s + 2 (s^3 / 3 + s^5 / 5 + ...), |s| < 1/7: the tail past s^21 / 21 is below 2^-60 relative. */
903template <typename Scalar>
904EIGEN_DEVICE_FUNC static Scalar igamma_log1p_minus_d(Scalar d) {
905 const Scalar s = d / (Scalar(2) + d);
906 const Scalar s2 = s * s;
907 Scalar power = s * s2;
908 Scalar sum = Scalar(0);
909 for (int k = 3; k <= 21; k += 2) {
910 sum += power / Scalar(k);
911 power *= s2;
912 }
913 return Scalar(2) * sum - d * s;
914}
915
916/* Temme's uniform asymptotic expansion of P = igamma(a, x) and Q = igammac(a, x) = 1 - P for large a
917 * (DLMF 8.12.3, 8.12.4 and 8.12.8; Temme, SIAM J. Math. Anal. 10, 1979):
918 *
919 * Q = erfc(z) / 2 + R, P = erfc(-z) / 2 - R, R = exp(-a psi) / sqrt(2 pi a) (c_0(eta) + c_1(eta) / a + O(a^-2)),
920 *
921 * with d = (x - a) / a, psi = d - log1p(d) = eta^2 / 2, sign(eta) = sign(d), z = eta sqrt(a / 2) = sign(d) sqrt(a psi),
922 * c_0(eta) = 1 / d - 1 / eta, c_1(eta) = 1 / eta^3 - 1 / d^3 - 1 / d^2 - 1 / (12 d).
923 * Both cancel for small eta and are evaluated from their Taylor series at eta = 0, c_0 = -1/3 + eta/12 - 2 eta^2 / 135
924 * + ..., c_1 = -1/540 - eta/288 + eta^2 / 378 - .... The coefficients were computed with GMP (mpq_class power series):
925 * d = u(eta) from eta^2 / 2 = d - log1p(d) by the fixed-point iteration u = eta / sqrt(h(u)), h(u) = 2 sum_{k >= 2}
926 * (-1)^k u^(k-2) / k, then the series of the closed forms above with d = u(eta). The leading terms of both match DLMF
927 * 8.12(ii).
928 *
929 * Used for |eta| <= 0.15, where the truncation after eta^12 (c_0) and eta^8 (c_1) is 9e-20 and 9e-16 absolute (c_1 / a
930 * is below 3e-19 relative to c_0), and a >= 1e5 (double), 1e4 (float). Outside, a psi > 1125 (112 in float), and P (x <
931 * a) or Q (x > a) is <= exp(-a psi) (Chernoff bound) < denorm_min / 2, so it is 0 and the other is 1. The error of the
932 * O(a^-2) term is the measured one: Q to 53 epsilon at a = 1e5 and |t|
933 * <= 8, t = (x - a) / sqrt(a), against mpfr_gamma_inc, 0.7 of 2 (log(a) / 2 + t^2 + 2) epsilon. It takes no iterations
934 * and is accurate near x = a for every a, where the continued fraction and the series need ~ sqrt(a) of them. */
935template <typename Scalar>
936EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE bool igamma_use_temme(Scalar a) {
937 return (numext::isfinite)(a) && a >= (sizeof(Scalar) == 4 ? Scalar(1e4) : Scalar(1e5));
938}
939
940template <typename Scalar>
941EIGEN_DEVICE_FUNC static void igamma_temme(Scalar a, Scalar x, Scalar* p, Scalar* q) {
942 const Scalar zero = 0, one = 1, half = Scalar(0.5);
943 const Scalar d = (x - a) / a;
944 // |d| >= 1/4 gives |eta| >= 0.23. The series for log1p(d) - d needs |d| < 1/4.
945 const Scalar psi = numext::abs(d) < Scalar(0.25) ? -igamma_log1p_minus_d(d) : Scalar(1);
946 if (!(Scalar(2) * psi <= Scalar(0.15) * Scalar(0.15))) {
947 *p = d > zero ? one : zero;
948 *q = one - *p;
949 return;
950 }
951 const Scalar eta = (d < zero ? -one : one) * numext::sqrt(Scalar(2) * psi);
952 const Scalar c0[] = {Scalar(-1) / Scalar(3),
953 Scalar(1) / Scalar(12),
954 Scalar(-2) / Scalar(135),
955 Scalar(1) / Scalar(864),
956 Scalar(1) / Scalar(2835),
957 Scalar(-139) / Scalar(777600),
958 Scalar(1) / Scalar(25515),
959 Scalar(-571) / Scalar(261273600),
960 Scalar(-281) / Scalar(151559100),
961 Scalar(163879) / Scalar(197522841600.0),
962 Scalar(-5221) / Scalar(29554024500.0),
963 Scalar(5246819) / Scalar(782190452736000.0),
964 Scalar(5459) / Scalar(531972441000.0)};
965 const Scalar c1[] = {Scalar(-1) / Scalar(540), Scalar(-1) / Scalar(288),
966 Scalar(1) / Scalar(378), Scalar(-77) / Scalar(77760),
967 Scalar(1) / Scalar(4860), Scalar(-1) / Scalar(2488320),
968 Scalar(-2743) / Scalar(151559100), Scalar(41969) / Scalar(5486745600.0),
969 Scalar(-11) / Scalar(6823440)};
970 Scalar c0_eta = c0[12], c1_eta = c1[8];
971 for (int k = 11; k >= 0; --k) c0_eta = c0_eta * eta + c0[k];
972 for (int k = 7; k >= 0; --k) c1_eta = c1_eta * eta + c1[k];
973 const Scalar a_psi = a * psi;
974 const Scalar r = numext::exp(-a_psi) / (numext::sqrt(Scalar(2 * EIGEN_PI)) * numext::sqrt(a)) * (c0_eta + c1_eta / a);
975 const Scalar half_erfc = half * erfc_impl<Scalar>::run(numext::sqrt(a_psi));
976 if (d >= zero) {
977 *q = igamma_clamp_to_unit_interval(half_erfc + r);
978 *p = one - *q;
979 } else {
980 *p = igamma_clamp_to_unit_interval(half_erfc - r);
981 *q = one - *p;
982 }
983}
984
985/* The iteration limit of the power series of igamma(a, x) for x <= a in VALUE mode. The terms are
986 * c_k = prod_{j <= k} x / (a + j) <= exp(-k^2 / (2 a)) for x <= a, so the sum has converged to machep (c_k <= machep,
987 * and the sum is >= 1) once k >= sqrt(-2 a log(machep)), at most 8.6 sqrt(a) in double and 5.8 sqrt(a) in float, which
988 * exceeds the limit 2000 of igamma_num_iterations for a >~ 5e4 (double) and 1.2e5 (float). The limit is 1.25 times
989 * that, but at most 1e5. */
990template <typename Scalar>
991EIGEN_DEVICE_FUNC static int igamma_series_num_iterations(Scalar a) {
992 const Scalar n = Scalar(1.25) * numext::sqrt(-Scalar(2) * a * numext::log(cephes_helper<Scalar>::machep()));
993 return !(n > Scalar(2000)) ? 2000 : n > Scalar(100000) ? 100000 : static_cast<int>(n);
994}
995
996/* x^a exp(-x) / Gamma(a) for x > 0 and a >> 1 from Stirling's series. a log(x) - x - lgamma(a) in main_igamma_term
997 * cancels to an absolute error of about eps a log(a), more than 1 for a >~ 1 / eps. With d = (x - a) / a:
998 *
999 * log(x^a exp(-x) / Gamma(a)) = a (log1p(d) - d) + (1/2) log(a / (2 pi)) - 1 / (12 a) + O(a^-3),
1000 * with log1p(d) - d from igamma_log1p_minus_d for -1/4 < d < 1/4.
1001 * For d <= -1/4 (x <= 3a/4), 1 + d = x / a is formed by the division, not as 1 + d, which has the absolute error eps
1002 * and so the relative error eps / (1 + d) for x << a. */
1003template <typename Scalar>
1004EIGEN_DEVICE_FUNC static Scalar main_igamma_term_stirling(Scalar a, Scalar x) {
1005 const Scalar d = (x - a) / a;
1006 Scalar log1pmx;
1007 if (d >= Scalar(0.25)) {
1008 log1pmx = numext::log1p(d) - d;
1009 } else if (d <= Scalar(-0.25)) {
1010 log1pmx = numext::log(x / a) - d;
1011 } else {
1012 log1pmx = igamma_log1p_minus_d(d);
1013 }
1014 const Scalar logax =
1015 a * log1pmx + Scalar(0.5) * (numext::log(a) - numext::log(Scalar(2 * EIGEN_PI))) - Scalar(1) / (Scalar(12) * a);
1016 // Written so that a NaN, from a = inf, gives 0 as main_igamma_term does.
1017 return !(logax >= -numext::log(NumTraits<Scalar>::highest())) ? Scalar(0) : numext::exp(logax);
1018}
1019
1020/* Whether igammac_cf_impl evaluates igammac(a, x), x >= a, as main_igamma_term_stirling * igammac_cf_lentz rather
1021 * than main_igamma_term * recurrence: true once the error 1 / (360 a^3) of Stirling's series for log Gamma(a),
1022 * truncated after 1 / (12 a), is below eps, i.e. a >~ 2.3e4 (double), a >~ 29 (float), and when a^3 overflows.
1023 * The ordinary main term has the absolute error eps a log(a) in its exponent: better for a <~ 1500 (double),
1024 * a <~ 16 (float), worse above, and meaningless for a >~ 1 / eps. */
1025template <typename Scalar>
1026EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE bool igamma_use_stirling_main_term(Scalar a) {
1027 return Scalar(360) * NumTraits<Scalar>::epsilon() * a * a * a >= Scalar(1);
1028}
1029
1030/* The continued fraction of igammac(a, x) / main_igamma_term(a, x), for x >= a > 0, by the modified Lentz algorithm
1031 * (Thompson and Barnett, J. Comput. Phys. 64, 1986; Press et al., Numerical Recipes, 3rd ed., section 6.2):
1032 *
1033 * K = 1 / (b_0 + a_1 / (b_1 + a_2 / (b_2 + ...))), b_i = x + 2i + 1 - a, a_i = -i (i - a).
1034 *
1035 * The forward recurrence of igammac_cf_impl evaluates the odd convergents of the Legendre fraction, Lentz's method
1036 * its even part (the same limit). The recurrence forms z x with z = x + 2 - a, which overflows once (x - a) x exceeds
1037 * the largest number; Lentz's method forms no product of two large quantities, and a_i * d is grouped as
1038 * -i * ((i - a) * d) so that it does not overflow for a near the largest number.
1039 *
1040 * The fraction needs ~ 355 / t^2 iterations (double), t = (x - a) / sqrt(a), for large a. It does not converge within
1041 * the iteration limit from (measured) a ~ 1.1e7 at t = 0, 1.8e7 at t = 0.1, 3.3e7 at t = 0.2, 1.4e8 at t = 0.3 and
1042 * 8e10 at t = 0.4 in double, and from a ~ 5.6e7 at t = 0 and 2.2e8 at t = 0.1 in float. Then *converged is false and
1043 * the returned value is meaningless; igammac_cf_impl returns NaN. igamma and igammac use igamma_temme from a = 1e5
1044 * (double), 1e4 (float), so this band is not reached through them. */
1045template <typename Scalar>
1046EIGEN_DEVICE_FUNC static Scalar igammac_cf_lentz(Scalar a, Scalar x, bool* converged) {
1047 const Scalar one = 1;
1048 const Scalar tiny = (numext::numeric_limits<Scalar>::min)();
1049 const Scalar machep = cephes_helper<Scalar>::machep();
1050 Scalar b = (x - a) + one; // x - a is exact for a <= x <= 2a; in (x + 1) - a the 1 is lost for x >= 2 / eps.
1051 Scalar c = one / tiny;
1052 Scalar d = one / b;
1053 Scalar h = d;
1054 for (int i = 1; i <= igamma_num_iterations<Scalar, VALUE>(); i++) {
1055 const Scalar ci = Scalar(i);
1056 b += Scalar(2);
1057 d = b - ci * ((ci - a) * d);
1058 if (numext::abs(d) < tiny) d = tiny;
1059 c = b - ci * ((ci - a) / c);
1060 if (numext::abs(c) < tiny) c = tiny;
1061 d = one / d;
1062 const Scalar delta = d * c;
1063 h *= delta;
1064 if (numext::abs(delta - one) <= machep) {
1065 *converged = true;
1066 return h;
1067 }
1068 }
1069 *converged = false;
1070 return h;
1071}
1072
1073template <typename Scalar, IgammaComputationMode mode>
1074struct igammac_cf_impl {
1075 /* Computes igamc(a, x) or derivative (depending on the mode)
1076 * using the continued fraction expansion of the complementary
1077 * incomplete Gamma function.
1078 *
1079 * Preconditions:
1080 * a > 0
1081 * x >= 1
1082 * x >= a
1083 */
1084 EIGEN_DEVICE_FUNC static Scalar run(Scalar a, Scalar x) {
1085 const Scalar zero = 0;
1086 const Scalar one = 1;
1087 const Scalar two = 2;
1088 const Scalar machep = cephes_helper<Scalar>::machep();
1089 const Scalar big = cephes_helper<Scalar>::big();
1090 const Scalar biginv = cephes_helper<Scalar>::biginv();
1091
1092 if ((numext::isinf)(x)) {
1093 return zero;
1094 }
1095
1096 if (mode == VALUE && igamma_use_stirling_main_term(a)) {
1097 // Where the main term underflows so does Q. The fraction ~ 1 / x is below the smallest normal number for
1098 // x > 1 / min (8.5e37 in float, 4.5e307 in double), where Lentz's method clamps it and does not converge.
1099 const Scalar ax_stirling = main_igamma_term_stirling<Scalar>(a, x);
1100 if (ax_stirling == zero) return zero;
1101 bool converged;
1102 const Scalar h = igammac_cf_lentz<Scalar>(a, x, &converged);
1103 // Unconverged only in the band documented at igammac_cf_lentz, where igamma_temme is used instead. The recurrence
1104 // and the ordinary main term are wrong there (values above 1, or float igammac(1e8, 1e8) = 1.25e-4 for a true
1105 // value ~ 0.5), so the result is NaN: a converged fraction or NaN.
1106 if (!converged) return NumTraits<Scalar>::quiet_NaN();
1107 return ax_stirling * h;
1108 }
1109
1110 Scalar ax = main_igamma_term<Scalar>(a, x);
1111 // This is independent of mode. If this value is zero,
1112 // then the function value is zero. If the function value is zero,
1113 // then we are in a neighborhood where the function value evaluates to zero,
1114 // so the derivative is zero.
1115 if (ax == zero) {
1116 return zero;
1117 }
1118
1119 // continued fraction
1120 Scalar y = one - a;
1121 Scalar z = x + y + one;
1122 Scalar c = zero;
1123 Scalar pkm2 = one;
1124 Scalar qkm2 = x;
1125 Scalar pkm1 = x + one;
1126 Scalar qkm1 = z * x;
1127 Scalar ans = pkm1 / qkm1;
1128
1129 Scalar dpkm2_da = zero;
1130 Scalar dqkm2_da = zero;
1131 Scalar dpkm1_da = zero;
1132 Scalar dqkm1_da = -x;
1133 Scalar dans_da = (dpkm1_da - ans * dqkm1_da) / qkm1;
1134
1135 for (int i = 0; i < igamma_num_iterations<Scalar, mode>(); i++) {
1136 c += one;
1137 y += one;
1138 z += two;
1139
1140 Scalar yc = y * c;
1141 Scalar pk = pkm1 * z - pkm2 * yc;
1142 Scalar qk = qkm1 * z - qkm2 * yc;
1143
1144 Scalar dpk_da = dpkm1_da * z - pkm1 - dpkm2_da * yc + pkm2 * c;
1145 Scalar dqk_da = dqkm1_da * z - qkm1 - dqkm2_da * yc + qkm2 * c;
1146
1147 if (qk != zero) {
1148 Scalar ans_prev = ans;
1149 ans = pk / qk;
1150
1151 Scalar dans_da_prev = dans_da;
1152 dans_da = (dpk_da - ans * dqk_da) / qk;
1153
1154 if (mode == VALUE) {
1155 if (numext::abs(ans_prev - ans) <= machep * numext::abs(ans)) {
1156 break;
1157 }
1158 } else {
1159 if (numext::abs(dans_da - dans_da_prev) <= machep) {
1160 break;
1161 }
1162 }
1163 }
1164
1165 pkm2 = pkm1;
1166 pkm1 = pk;
1167 qkm2 = qkm1;
1168 qkm1 = qk;
1169
1170 dpkm2_da = dpkm1_da;
1171 dpkm1_da = dpk_da;
1172 dqkm2_da = dqkm1_da;
1173 dqkm1_da = dqk_da;
1174
1175 if (numext::abs(pk) > big) {
1176 pkm2 *= biginv;
1177 pkm1 *= biginv;
1178 qkm2 *= biginv;
1179 qkm1 *= biginv;
1180
1181 dpkm2_da *= biginv;
1182 dpkm1_da *= biginv;
1183 dqkm2_da *= biginv;
1184 dqkm1_da *= biginv;
1185 }
1186 }
1187
1188 /* Compute x**a * exp(-x) / gamma(a) */
1189 Scalar dlogax_da = numext::log(x) - digamma_impl<Scalar>::run(a);
1190 Scalar dax_da = ax * dlogax_da;
1191
1192 switch (mode) {
1193 case VALUE: {
1194 // An overflow of the recurrence (inf - inf) is reported as NaN rather than returned as inf or a silent 0.
1195 const Scalar result = ans * ax;
1196 return EIGEN_PREDICT_FALSE(!(numext::isfinite)(result)) ? NumTraits<Scalar>::quiet_NaN() : result;
1197 }
1198 case DERIVATIVE:
1199 return ans * dax_da + dans_da * ax;
1200 case SAMPLE_DERIVATIVE:
1201 default: // this is needed to suppress clang warning
1202 return -(dans_da + ans * dlogax_da) * x;
1203 }
1204 }
1205};
1206
1207template <typename Scalar, IgammaComputationMode mode>
1208struct igamma_series_impl {
1209 /* Computes igam(a, x) or its derivative (depending on the mode)
1210 * using the series expansion of the incomplete Gamma function.
1211 *
1212 * Preconditions:
1213 * x > 0
1214 * a > 0
1215 * !(x > 1 && x > a)
1216 */
1217 EIGEN_DEVICE_FUNC static Scalar run(Scalar a, Scalar x) {
1218 const Scalar zero = 0;
1219 const Scalar one = 1;
1220 const Scalar machep = cephes_helper<Scalar>::machep();
1221
1222 const bool stirling = mode == VALUE && igamma_use_stirling_main_term(a);
1223 Scalar ax = stirling ? main_igamma_term_stirling<Scalar>(a, x) : main_igamma_term<Scalar>(a, x);
1224
1225 // This is independent of mode. If this value is zero,
1226 // then the function value is zero. If the function value is zero,
1227 // then we are in a neighborhood where the function value evaluates to zero,
1228 // so the derivative is zero.
1229 if (ax == zero) {
1230 return zero;
1231 }
1232
1233 ax /= a;
1234
1235 /* power series */
1236 Scalar r = a;
1237 Scalar c = one;
1238 Scalar ans = one;
1239
1240 Scalar dc_da = zero;
1241 Scalar dans_da = zero;
1242
1243 const int num_iterations = mode == VALUE ? igamma_series_num_iterations(a) : igamma_num_iterations<Scalar, mode>();
1244 bool converged = false;
1245 for (int i = 0; i < num_iterations; i++) {
1246 // r += 1 stalls once a >= 2^24 in float: a + 1 rounds to a.
1247 r = mode == VALUE ? a + Scalar(i + 1) : r + one;
1248 Scalar term = x / r;
1249 Scalar dterm_da = -x / (r * r);
1250 dc_da = term * dc_da + dterm_da * c;
1251 dans_da += dc_da;
1252 c *= term;
1253 ans += c;
1254
1255 if (mode == VALUE) {
1256 if (c <= machep * ans) {
1257 converged = true;
1258 break;
1259 }
1260 } else {
1261 if (numext::abs(dc_da) <= machep * numext::abs(dans_da)) {
1262 break;
1263 }
1264 }
1265 }
1266 // A truncated sum is wrong by an unbounded amount (double igamma(1e6, 1e6) was 0.477, true 0.500): a converged sum
1267 // or NaN.
1268 if (mode == VALUE && !converged) return NumTraits<Scalar>::quiet_NaN();
1269
1270 Scalar dlogax_da = numext::log(x) - digamma_impl<Scalar>::run(a + one);
1271 Scalar dax_da = ax * dlogax_da;
1272
1273 switch (mode) {
1274 case VALUE:
1275 return ans * ax;
1276 case DERIVATIVE:
1277 return ans * dax_da + dans_da * ax;
1278 case SAMPLE_DERIVATIVE:
1279 default: // this is needed to suppress clang warning
1280 return -(dans_da + ans * dlogax_da) * x / a;
1281 }
1282 }
1283};
1284
1285template <typename Scalar>
1286struct igammac_default_impl {
1287 EIGEN_DEVICE_FUNC static Scalar run(Scalar a, Scalar x) {
1288 /* igamc()
1289 *
1290 * Incomplete gamma integral (modified for Eigen)
1291 *
1292 *
1293 *
1294 * SYNOPSIS:
1295 *
1296 * double a, x, y, igamc();
1297 *
1298 * y = igamc( a, x );
1299 *
1300 * DESCRIPTION:
1301 *
1302 * The function is defined by
1303 *
1304 *
1305 * igamc(a,x) = 1 - igam(a,x)
1306 *
1307 * inf.
1308 * -
1309 * 1 | | -t a-1
1310 * = ----- | e t dt.
1311 * - | |
1312 * | (a) -
1313 * x
1314 *
1315 *
1316 * In this implementation both arguments must be positive.
1317 * The integral is evaluated by either a power series or
1318 * continued fraction expansion, depending on the relative
1319 * values of a and x.
1320 *
1321 * ACCURACY (float):
1322 *
1323 * Relative error:
1324 * arithmetic domain # trials peak rms
1325 * IEEE 0,30 30000 7.8e-6 5.9e-7
1326 *
1327 *
1328 * ACCURACY (double):
1329 *
1330 * Tested at random a, x.
1331 * a x Relative error:
1332 * arithmetic domain domain # trials peak rms
1333 * IEEE 0.5,100 0,100 200000 1.9e-14 1.7e-15
1334 * IEEE 0.01,0.5 0,100 200000 1.4e-13 1.6e-15
1335 *
1336 */
1337 /*
1338 Cephes Math Library Release 2.2: June, 1992
1339 Copyright 1985, 1987, 1992 by Stephen L. Moshier
1340 Direct inquiries to 30 Frost Street, Cambridge, MA 02140
1341 */
1342 const Scalar zero = 0;
1343 const Scalar one = 1;
1344 const Scalar nan = NumTraits<Scalar>::quiet_NaN();
1345
1346 if ((x < zero) || (a <= zero)) {
1347 // domain error
1348 return nan;
1349 }
1350
1351 if ((numext::isnan)(a) || (numext::isnan)(x)) { // propagate nans
1352 return nan;
1353 }
1354
1355 if (igamma_use_temme(a)) {
1356 Scalar p, q;
1357 igamma_temme(a, x, &p, &q);
1358 return q;
1359 }
1360
1361 if ((x < one) || (x < a)) {
1362 // Clamp to [0,1] since 1-igamma can produce tiny negative values
1363 // due to floating-point cancellation for extreme arguments.
1364 return igamma_clamp_to_unit_interval(one - igamma_series_impl<Scalar, VALUE>::run(a, x));
1365 }
1366
1367 // NaN where Lentz's fraction does not converge (igammac_cf_impl); the clamp keeps NaN.
1368 return igamma_clamp_to_unit_interval(igammac_cf_impl<Scalar, VALUE>::run(a, x));
1369 }
1370};
1371
1372template <typename Scalar>
1373struct igammac_impl : special_function_overload_or<special_function_overloads::igammac_fn, igammac_default_impl<Scalar>,
1374 Scalar, Scalar> {};
1375
1376/************************************************************************************************
1377 * Implementation of igamma (incomplete gamma integral), based on Cephes *
1378 ************************************************************************************************/
1379
1380template <typename Scalar, IgammaComputationMode mode>
1381struct igamma_generic_impl {
1382 EIGEN_DEVICE_FUNC static Scalar run(Scalar a, Scalar x) {
1383 /* Depending on the mode, returns
1384 * - VALUE: incomplete Gamma function igamma(a, x)
1385 * - DERIVATIVE: derivative of incomplete Gamma function d/da igamma(a, x)
1386 * - SAMPLE_DERIVATIVE: implicit derivative of a Gamma random variable
1387 * x ~ Gamma(x | a, 1), dx/da = -1 / Gamma(x | a, 1) * d igamma(a, x) / dx
1388 *
1389 * Derivatives are implemented by forward-mode differentiation.
1390 */
1391 const Scalar zero = 0;
1392 const Scalar one = 1;
1393 const Scalar nan = NumTraits<Scalar>::quiet_NaN();
1394
1395 if ((numext::isnan)(a) || (numext::isnan)(x)) { // propagate nans
1396 return nan;
1397 }
1398
1399 if (x == zero) return zero;
1400
1401 if ((x < zero) || (a <= zero)) { // domain error
1402 return nan;
1403 }
1404
1405 if (mode == VALUE && igamma_use_temme(a)) {
1406 Scalar p, q;
1407 igamma_temme(a, x, &p, &q);
1408 return p;
1409 }
1410
1411 if ((x > one) && (x > a)) {
1412 Scalar ret = igammac_cf_impl<Scalar, mode>::run(a, x);
1413 if (mode == VALUE) {
1414 // Clamp to [0,1] since 1-igammac can produce tiny negative values
1415 // due to floating-point cancellation for extreme arguments.
1416 return igamma_clamp_to_unit_interval(one - ret);
1417 } else {
1418 return -ret;
1419 }
1420 }
1421
1422 Scalar ret = igamma_series_impl<Scalar, mode>::run(a, x);
1423 if (mode == VALUE) {
1424 // Clamp to [0,1] since accumulated series terms can slightly exceed 1.0
1425 // due to floating-point rounding for extreme arguments.
1426 return igamma_clamp_to_unit_interval(ret);
1427 }
1428 return ret;
1429 }
1430};
1431
1432template <typename Scalar>
1433struct igamma_impl : special_function_overload_or<special_function_overloads::igamma_fn,
1434 igamma_generic_impl<Scalar, VALUE>, Scalar, Scalar> {
1435 /* igam()
1436 * Incomplete gamma integral.
1437 *
1438 * The CDF of Gamma(a, 1) random variable at the point x.
1439 *
1440 * Accuracy estimation. For each a in [10^-2, 10^-1...10^3] we sample
1441 * 50 Gamma random variables x ~ Gamma(x | a, 1), a total of 300 points.
1442 * The ground truth is computed by mpmath. Mean absolute error:
1443 * float: 1.26713e-05
1444 * double: 2.33606e-12
1445 *
1446 * Cephes documentation below.
1447 *
1448 * SYNOPSIS:
1449 *
1450 * double a, x, y, igam();
1451 *
1452 * y = igam( a, x );
1453 *
1454 * DESCRIPTION:
1455 *
1456 * The function is defined by
1457 *
1458 * x
1459 * -
1460 * 1 | | -t a-1
1461 * igam(a,x) = ----- | e t dt.
1462 * - | |
1463 * | (a) -
1464 * 0
1465 *
1466 *
1467 * In this implementation both arguments must be positive.
1468 * The integral is evaluated by either a power series or
1469 * continued fraction expansion, depending on the relative
1470 * values of a and x.
1471 *
1472 * ACCURACY (double):
1473 *
1474 * Relative error:
1475 * arithmetic domain # trials peak rms
1476 * IEEE 0,30 200000 3.6e-14 2.9e-15
1477 * IEEE 0,100 300000 9.9e-14 1.5e-14
1478 *
1479 *
1480 * ACCURACY (float):
1481 *
1482 * Relative error:
1483 * arithmetic domain # trials peak rms
1484 * IEEE 0,30 20000 7.8e-6 5.9e-7
1485 *
1486 */
1487 /*
1488 Cephes Math Library Release 2.2: June, 1992
1489 Copyright 1985, 1987, 1992 by Stephen L. Moshier
1490 Direct inquiries to 30 Frost Street, Cambridge, MA 02140
1491 */
1492
1493 /* left tail of incomplete gamma function:
1494 *
1495 * inf. k
1496 * a -x - x
1497 * x e > ----------
1498 * - -
1499 * k=0 | (a+k+1)
1500 *
1501 */
1502};
1503
1504template <typename Scalar>
1505struct igamma_der_a_impl : special_function_overload_or<special_function_overloads::igamma_der_a_fn,
1506 igamma_generic_impl<Scalar, DERIVATIVE>, Scalar, Scalar> {
1507 /* Derivative of the incomplete Gamma function with respect to a.
1508 *
1509 * Computes d/da igamma(a, x) by forward differentiation of the igamma code.
1510 *
1511 * Accuracy estimation. For each a in [10^-2, 10^-1...10^3] we sample
1512 * 50 Gamma random variables x ~ Gamma(x | a, 1), a total of 300 points.
1513 * The ground truth is computed by mpmath. Mean absolute error:
1514 * float: 6.17992e-07
1515 * double: 4.60453e-12
1516 *
1517 * Reference:
1518 * R. Moore. "Algorithm AS 187: Derivatives of the incomplete gamma
1519 * integral". Journal of the Royal Statistical Society. 1982
1520 */
1521};
1522
1523template <typename Scalar>
1524struct gamma_sample_der_alpha_impl
1525 : special_function_overload_or<special_function_overloads::gamma_sample_der_alpha_fn,
1526 igamma_generic_impl<Scalar, SAMPLE_DERIVATIVE>, Scalar, Scalar> {
1527 /* Derivative of a Gamma random variable sample with respect to alpha.
1528 *
1529 * Consider a sample of a Gamma random variable with the concentration
1530 * parameter alpha: sample ~ Gamma(alpha, 1). The reparameterization
1531 * derivative that we want to compute is dsample / dalpha =
1532 * d igammainv(alpha, u) / dalpha, where u = igamma(alpha, sample).
1533 * However, this formula is numerically unstable and expensive, so instead
1534 * we use implicit differentiation:
1535 *
1536 * igamma(alpha, sample) = u, where u ~ Uniform(0, 1).
1537 * Apply d / dalpha to both sides:
1538 * d igamma(alpha, sample) / dalpha
1539 * + d igamma(alpha, sample) / dsample * dsample/dalpha = 0
1540 * d igamma(alpha, sample) / dalpha
1541 * + Gamma(sample | alpha, 1) dsample / dalpha = 0
1542 * dsample/dalpha = - (d igamma(alpha, sample) / dalpha)
1543 * / Gamma(sample | alpha, 1)
1544 *
1545 * Here Gamma(sample | alpha, 1) is the PDF of the Gamma distribution
1546 * (note that the derivative of the CDF w.r.t. sample is the PDF).
1547 * See the reference below for more details.
1548 *
1549 * The derivative of igamma(alpha, sample) is computed by forward
1550 * differentiation of the igamma code. Division by the Gamma PDF is performed
1551 * in the same code, increasing the accuracy and speed due to cancellation
1552 * of some terms.
1553 *
1554 * Accuracy estimation. For each alpha in [10^-2, 10^-1...10^3] we sample
1555 * 50 Gamma random variables sample ~ Gamma(sample | alpha, 1), a total of 300
1556 * points. The ground truth is computed by mpmath. Mean absolute error:
1557 * float: 2.1686e-06
1558 * double: 1.4774e-12
1559 *
1560 * Reference:
1561 * M. Figurnov, S. Mohamed, A. Mnih "Implicit Reparameterization Gradients".
1562 * 2018
1563 */
1564};
1565
1566/*****************************************************************************
1567 * Implementation of Riemann zeta function of two arguments, based on Cephes *
1568 *****************************************************************************/
1569
1570// For q < -kZetaMaxNegativeQ, zeta(x, q) is evaluated by a reflection rather than by summing about |q| terms.
1571constexpr int kZetaMaxNegativeQ = 1000;
1572
1573template <typename Scalar>
1574struct zeta_impl_series {
1575 EIGEN_STATIC_ASSERT((std::is_same<Scalar, Scalar>::value == false), THIS_TYPE_IS_NOT_SUPPORTED)
1576
1577 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { return Scalar(0); }
1578};
1579
1580template <>
1581struct zeta_impl_series<float> {
1582 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE bool run(float& a, float& b, float& s, const float x, const float machep,
1583 const float inv_scale) {
1584 int i = 0;
1585 while ((i < 9) || (a <= 9.0f)) {
1586 i += 1;
1587 a += 1.0f;
1588 b = numext::pow(a * inv_scale, -x);
1589 s += b;
1590 if (numext::abs(b / s) < machep) return true;
1591 }
1592
1593 // Return whether we are done
1594 return false;
1595 }
1596};
1597
1598template <>
1599struct zeta_impl_series<double> {
1600 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE bool run(double& a, double& b, double& s, const double x,
1601 const double machep, const double inv_scale) {
1602 int i = 0;
1603 while ((i < 9) || (a <= 9.0)) {
1604 i += 1;
1605 a += 1.0;
1606 b = numext::pow(a * inv_scale, -x);
1607 s += b;
1608 if (numext::abs(b / s) < machep) return true;
1609 }
1610
1611 // Return whether we are done
1612 return false;
1613 }
1614};
1615
1616template <typename Scalar>
1617struct zeta_default_impl {
1618 /* Euler-Maclaurin summation of the Hurwitz zeta function (see run()), for x > 1 and q > 0 or q < 0 non-integer, and
1619 * multiplied by scale^x where inv_scale = 1 / scale. Every term (k + q)^-x is computed as (inv_scale (k + q))^-x,
1620 * which does not underflow when scale is of the size of q, so scale = q gives a result of order 1 where zeta(x, q)
1621 * itself underflows. */
1622 EIGEN_DEVICE_FUNC static Scalar sum(Scalar x, Scalar q, Scalar inv_scale) {
1623 int i;
1624 Scalar a, b, k, s, t, w;
1625
1626 const Scalar A[] = {
1627 Scalar(12.0),
1628 Scalar(-720.0),
1629 Scalar(30240.0),
1630 Scalar(-1209600.0),
1631 Scalar(47900160.0),
1632 Scalar(-1.8924375803183791606e9), /*1.307674368e12/691*/
1633 Scalar(7.47242496e10),
1634 Scalar(-2.950130727918164224e12), /*1.067062284288e16/3617*/
1635 Scalar(1.1646782814350067249e14), /*5.109094217170944e18/43867*/
1636 Scalar(-4.5979787224074726105e15), /*8.028576626982912e20/174611*/
1637 Scalar(1.8152105401943546773e17), /*1.5511210043330985984e23/854513*/
1638 Scalar(-7.1661652561756670113e18) /*1.6938241367317436694528e27/236364091*/
1639 };
1640
1641 const Scalar zero = Scalar(0.0), half = Scalar(0.5), one = Scalar(1.0);
1642 const Scalar machep = cephes_helper<Scalar>::machep();
1643
1644 /* Permit negative q but continue sum until n+q > +9 . For q < -kZetaMaxNegativeQ, run() uses the reflection
1645 * below instead, so this runs for at most kZetaMaxNegativeQ + 10 iterations. */
1646 s = numext::pow(q * inv_scale, -x);
1647 a = q;
1648 b = zero;
1649 // Run the summation in a helper function that is specific to the floating precision
1650 if (zeta_impl_series<Scalar>::run(a, b, s, x, machep, inv_scale)) {
1651 return s;
1652 }
1653
1654 // If b is zero, then the tail sum will also end up being zero.
1655 // Exiting early here can prevent NaNs for some large inputs, where
1656 // the tail sum computed below has term `a` which can overflow to `inf`.
1657 if (numext::equal_strict(b, zero)) {
1658 return s;
1659 }
1660
1661 w = a;
1662 s += b * w / (x - one);
1663 s -= half * b;
1664 a = one;
1665 k = zero;
1666
1667 for (i = 0; i < 12; i++) {
1668 a *= x + k;
1669 b /= w;
1670 t = a * b / A[i];
1671 s = s + t;
1672 t = numext::abs(t / s);
1673 if (t < machep) {
1674 break;
1675 }
1676 k += one;
1677 a *= x + k;
1678 b /= w;
1679 k += one;
1680 }
1681 return s;
1682 }
1683
1684 /* zeta(x, q) = exp(log(sum(x, q, 1 / q)) - x log(q)), for q >= 1. The terms are scaled to ~ 1 and the sum to
1685 * ~ q / (x - 1), which is finite for x >= 2 and q <= max / 16; 1 / q is then also normal under flush to zero. */
1686 EIGEN_DEVICE_FUNC static Scalar log_domain_sum_scaled_by_q(Scalar x, Scalar q) {
1687 return numext::exp(numext::log(sum(x, q, Scalar(1) / q)) - x * numext::log(q));
1688 }
1689
1690 /* The same for any finite q >= 1 and x > 1, with the terms scaled to ~ 1 / q_c, q_c = min(q, 1 / (16 min)), so
1691 * that neither the first term nor the sum ~ q / (q_c (x - 1)) <= 64 / (x - 1) leaves the normal range, however
1692 * close x is to 1 and up to q = max. With L = log(q), L_c = log(q_c) and e = L_c - x L = (L_c - L) - (x - 1) L:
1693 * zeta(x, q) = exp(log(sum(x, q, exp(e / x))) + e).
1694 * The relative error is ~ eps (x - 1) log(q). Where e < log(denorm_min) - 6, x - 1 > 1 and the sum is < 64, so zeta
1695 * rounds to 0; returning it there also avoids exp(e / x) ~ 1 / q, which is subnormal or flushed to zero. */
1696 EIGEN_DEVICE_FUNC static Scalar log_domain_sum_rescaled(Scalar x, Scalar q) {
1697 const Scalar log_q = numext::log(q);
1698 const Scalar q_c = numext::mini(q, Scalar(1) / (Scalar(16) * (numext::numeric_limits<Scalar>::min)()));
1699 const Scalar e = (numext::log(q_c) - log_q) - (x - Scalar(1)) * log_q;
1700 const Scalar log_denorm_min = numext::log((numext::numeric_limits<Scalar>::min)()) -
1701 Scalar(numext::numeric_limits<Scalar>::digits - 1) * Scalar(0.6931471805599453);
1702 if (e < log_denorm_min - Scalar(6)) return Scalar(0);
1703 return numext::exp(numext::log(sum(x, q, numext::exp(e / x))) + e);
1704 }
1705
1706 /* sum(x, q, 1) for q >= 1, also where q^-x is subnormal or zero but the sum ~ q^(1-x) / (x - 1) is normal. The
1707 * first term b = q^-x = min 2^-k then has the relative error ~ eps 2^k and dominates the sum for x near 1. Once
1708 * that exceeds the error ~ eps (1 + 2 (x - 1) log(q)) of a log-domain form, use one. For x >= 2 and q <= max / 16
1709 * that is the scaling by 1 / q; otherwise the rescaled form, since the sum ~ q / (x - 1) of the first overflows for
1710 * x - 1 < 1/16 and its 1 / q is subnormal, or flushed to zero, for q > max / 16. q^-x < min is x log(q) > -log(min);
1711 * this also excludes q = 1. */
1712 EIGEN_DEVICE_FUNC static Scalar sum_without_underflow(Scalar x, Scalar q) {
1713 if (q >= Scalar(1) && !(numext::isinf)(x)) {
1714 const Scalar log_q = numext::log(q);
1715 const Scalar x_log_q = x * log_q;
1716 const Scalar log_min = numext::log((numext::numeric_limits<Scalar>::min)());
1717 if (x_log_q > -log_min && x_log_q + log_min > numext::log(Scalar(2) * (Scalar(1) + (x - Scalar(1)) * log_q))) {
1718 if (x >= Scalar(2) && q <= (numext::numeric_limits<Scalar>::max)() / Scalar(16)) {
1719 return log_domain_sum_scaled_by_q(x, q);
1720 }
1721 return log_domain_sum_rescaled(x, q);
1722 }
1723 }
1724 return sum(x, q, Scalar(1));
1725 }
1726
1727 EIGEN_DEVICE_FUNC static Scalar run(Scalar x, Scalar q) {
1728 /* zeta.c
1729 *
1730 * Riemann zeta function of two arguments
1731 *
1732 *
1733 *
1734 * SYNOPSIS:
1735 *
1736 * double x, q, y, zeta();
1737 *
1738 * y = zeta( x, q );
1739 *
1740 *
1741 *
1742 * DESCRIPTION:
1743 *
1744 *
1745 *
1746 * inf.
1747 * - -x
1748 * zeta(x,q) = > (k+q)
1749 * -
1750 * k=0
1751 *
1752 * where x > 1 and q is not a negative integer or zero.
1753 * The Euler-Maclaurin summation formula is used to obtain
1754 * the expansion
1755 *
1756 * n
1757 * - -x
1758 * zeta(x,q) = > (k+q)
1759 * -
1760 * k=1
1761 *
1762 * 1-x inf. B x(x+1)...(x+2j)
1763 * (n+q) 1 - 2j
1764 * + --------- - ------- + > --------------------
1765 * x-1 x - x+2j+1
1766 * 2(n+q) j=1 (2j)! (n+q)
1767 *
1768 * where the B2j are Bernoulli numbers. Note that (see zetac.c)
1769 * zeta(x,1) = zetac(x) + 1.
1770 *
1771 *
1772 *
1773 * ACCURACY:
1774 *
1775 * Relative error for single precision:
1776 * arithmetic domain # trials peak rms
1777 * IEEE 0,25 10000 6.9e-7 1.0e-7
1778 *
1779 * Large arguments may produce underflow in powf(), in which
1780 * case the results are inaccurate.
1781 *
1782 * REFERENCE:
1783 *
1784 * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals,
1785 * Series, and Products, p. 1073; Academic Press, 1980.
1786 *
1787 */
1788
1789 Scalar p, r;
1790
1791 const Scalar maxnum = NumTraits<Scalar>::infinity();
1792 const Scalar zero = Scalar(0.0), half = Scalar(0.5), one = Scalar(1.0);
1793 const Scalar nan = NumTraits<Scalar>::quiet_NaN();
1794
1795 if (x == one) return maxnum;
1796
1797 if (x < one) {
1798 return nan;
1799 }
1800
1801 if (q <= zero) {
1802 if (q == numext::floor(q)) {
1803 if (numext::rint(Scalar(0.5) * x) == Scalar(0.5) * x) {
1804 return maxnum;
1805 } else {
1806 return nan;
1807 }
1808 }
1809 p = x;
1810 r = numext::floor(p);
1811 if (p != r) return nan;
1812 }
1813
1814 /* The sum for q < 0 has about |q| terms. Beyond kZetaMaxNegativeQ split it at the sign change of k + q, with
1815 * q = f - M, f in (0, 1) and M a positive integer, for integer x (checked above):
1816 *
1817 * zeta(x, q) = zeta(x, f) + sum_{j=1}^M (f - j)^-x
1818 * = zeta(x, f) + (-1)^x (zeta(x, 1 - f) - zeta(x, 1 - q)),
1819 *
1820 * using sum_{j=1}^M (j - f)^-x = zeta(x, 1 - f) - zeta(x, M + 1 - f) and M + 1 - f = 1 - q. */
1821 if (q < -Scalar(kZetaMaxNegativeQ)) {
1822 const Scalar f = q - numext::floor(q);
1823 const Scalar x_is_even = (numext::rint(half * x) == half * x) ? one : -one;
1824 return (sum(x, f, one) + x_is_even * sum(x, one - f, one)) - x_is_even * sum_without_underflow(x, one - q);
1825 }
1826
1827 return sum_without_underflow(x, q);
1828 }
1829};
1830
1831template <typename Scalar>
1832struct zeta_impl
1833 : special_function_overload_or<special_function_overloads::zeta_fn, zeta_default_impl<Scalar>, Scalar, Scalar> {};
1834
1835/****************************************************************************
1836 * Implementation of polygamma function *
1837 ****************************************************************************/
1838
1839template <typename Scalar>
1840struct polygamma_default_impl {
1841 EIGEN_DEVICE_FUNC static Scalar run(Scalar n, Scalar x) {
1842 Scalar zero = 0.0, one = 1.0;
1843 Scalar nplus = n + one;
1844 const Scalar nan = NumTraits<Scalar>::quiet_NaN();
1845
1846 // Check that n is a non-negative integer
1847 if (numext::floor(n) != n || n < zero || (numext::isinf)(n)) {
1848 return nan;
1849 }
1850 // Just return the digamma function for n = 0
1851 else if (n == zero) {
1852 return digamma_impl<Scalar>::run(x);
1853 }
1854 // Use the same implementation as scipy
1855 else {
1856 // (-1)^(n+1) from the parity of n: n + 1 is not representable for n >= 2^24 (float), 2^53 (double).
1857 const Scalar half = Scalar(0.5);
1858 const bool n_is_even = numext::floor(half * n) == half * n;
1859 const Scalar sign = n_is_even ? -one : one;
1860 // For odd n + 1 and x = -M - 1/2 < -kZetaMaxNegativeQ the reflection in zeta_impl reduces exactly to
1861 // zeta(n + 1, x) = zeta(n + 1, 1 - x); with 1 - x > 0 the log-domain evaluation below applies.
1862 if (n_is_even && x < -Scalar(kZetaMaxNegativeQ) && x - numext::floor(x) == half) x = one - x;
1863 Scalar factorial = numext::exp(lgamma_impl<Scalar>::run(nplus));
1864 Scalar zeta = zeta_impl<Scalar>::run(nplus, x);
1865 // The limit at +inf is 0, with the sign of (-1)^(n+1); n! zeta(n + 1, inf) would be NaN for n! = inf.
1866 if (x == NumTraits<Scalar>::infinity()) return sign * zero;
1867 // 1 / x must be a normal number, also when subnormals are flushed to zero: for x <= max / 16 it is >= 16 / max,
1868 // which is above the smallest normal number (4.7e-38 vs 1.2e-38 in float, 8.9e-308 vs 2.2e-308 in double).
1869 if (x > zero && x <= (numext::numeric_limits<Scalar>::max)() / Scalar(16) &&
1870 ((numext::isinf)(factorial) || !(zeta >= (numext::numeric_limits<Scalar>::min)()))) {
1871 // n! overflows, or zeta(n + 1, x) ~ x^-(n+1) underflows, while n! zeta(n + 1, x) can be representable (a
1872 // product of inf and 0 is NaN). With Z = x^(n+1) zeta(n + 1, x), which is >= 1 and ~ x / n for x >> n, form
1873 // the product in the log domain:
1874 // n! zeta(n + 1, x) = exp(lgamma(n + 1) - (n + 1) log x + log Z).
1875 const Scalar log_z = numext::log(zeta_default_impl<Scalar>::sum(nplus, x, one / x));
1876 if ((numext::isfinite)(log_z)) {
1877 return sign * numext::exp(lgamma_impl<Scalar>::run(nplus) - nplus * numext::log(x) + log_z);
1878 }
1879 }
1880 // x < 0: zeta(n + 1, x) = 0 where the sums cancel exactly (x = -N - 1/2) and the true value, n! zeta(n + 1, 1 -
1881 // x) with 1 - x > 1000, underflows; likewise for x > max / 16, where n! x^-n underflows. inf * 0 would be NaN.
1882 if ((numext::isinf)(factorial) && zeta == zero) return sign * zero;
1883 return sign * factorial * zeta;
1884 }
1885 }
1886};
1887
1888template <typename Scalar>
1889struct polygamma_impl : special_function_overload_or<special_function_overloads::polygamma_fn,
1890 polygamma_default_impl<Scalar>, Scalar, Scalar> {};
1891
1892/************************************************************************************************
1893 * Implementation of betainc (incomplete beta integral), based on Cephes *
1894 ************************************************************************************************/
1895
1896template <typename Scalar>
1897struct betainc_default_impl {
1898 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar, Scalar, Scalar) {
1899 EIGEN_STATIC_ASSERT((!std::is_same<Scalar, Scalar>::value), THIS_TYPE_IS_NOT_SUPPORTED)
1900 /* betaincf.c
1901 *
1902 * Incomplete beta integral
1903 *
1904 *
1905 * SYNOPSIS:
1906 *
1907 * float a, b, x, y, betaincf();
1908 *
1909 * y = betaincf( a, b, x );
1910 *
1911 *
1912 * DESCRIPTION:
1913 *
1914 * Returns incomplete beta integral of the arguments, evaluated
1915 * from zero to x. The function is defined as
1916 *
1917 * x
1918 * - -
1919 * | (a+b) | | a-1 b-1
1920 * ----------- | t (1-t) dt.
1921 * - - | |
1922 * | (a) | (b) -
1923 * 0
1924 *
1925 * The domain of definition is 0 <= x <= 1. In this
1926 * implementation a and b are restricted to positive values.
1927 * The integral from x to 1 may be obtained by the symmetry
1928 * relation
1929 *
1930 * 1 - betainc( a, b, x ) = betainc( b, a, 1-x ).
1931 *
1932 * The integral is evaluated by a continued fraction expansion.
1933 * If a < 1, the function calls itself recursively after a
1934 * transformation to increase a to a+1.
1935 *
1936 * ACCURACY (float):
1937 *
1938 * Tested at random points (a,b,x) with a and b in the indicated
1939 * interval and x between 0 and 1.
1940 *
1941 * arithmetic domain # trials peak rms
1942 * Relative error:
1943 * IEEE 0,30 10000 3.7e-5 5.1e-6
1944 * IEEE 0,100 10000 1.7e-4 2.5e-5
1945 * The useful domain for relative error is limited by underflow
1946 * of the single precision exponential function.
1947 * Absolute error:
1948 * IEEE 0,30 100000 2.2e-5 9.6e-7
1949 * IEEE 0,100 10000 6.5e-5 3.7e-6
1950 *
1951 * Larger errors may occur for extreme ratios of a and b.
1952 *
1953 * ACCURACY (double):
1954 * arithmetic domain # trials peak rms
1955 * IEEE 0,5 10000 6.9e-15 4.5e-16
1956 * IEEE 0,85 250000 2.2e-13 1.7e-14
1957 * IEEE 0,1000 30000 5.3e-12 6.3e-13
1958 * IEEE 0,10000 250000 9.3e-11 7.1e-12
1959 * IEEE 0,100000 10000 8.7e-10 4.8e-11
1960 * Outputs smaller than the IEEE gradual underflow threshold
1961 * were excluded from these statistics.
1962 *
1963 * ERROR MESSAGES:
1964 * message condition value returned
1965 * incbet domain x<0, x>1 nan
1966 * incbet underflow nan
1967 */
1968 return Scalar(0);
1969 }
1970};
1971
1972template <typename Scalar>
1973struct betainc_impl : special_function_overload_or<special_function_overloads::betainc_fn, betainc_default_impl<Scalar>,
1974 Scalar, Scalar, Scalar> {};
1975
1976/* Continued fraction expansion #1 for incomplete beta integral (small_branch = True)
1977 * Continued fraction expansion #2 for incomplete beta integral (small_branch = False)
1978 */
1979template <typename Scalar>
1980struct incbeta_cfe {
1981 EIGEN_STATIC_ASSERT((std::is_same<Scalar, float>::value || std::is_same<Scalar, double>::value),
1982 THIS_TYPE_IS_NOT_SUPPORTED)
1983
1984 // xc is 1 - x: for x close to 1 it cannot be recovered from x, so the caller may supply it.
1985 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar a, Scalar b, Scalar x, Scalar xc, bool small_branch) {
1986 const Scalar big = cephes_helper<Scalar>::big();
1987 const Scalar machep = cephes_helper<Scalar>::machep();
1988 const Scalar biginv = cephes_helper<Scalar>::biginv();
1989
1990 const Scalar zero = 0;
1991 const Scalar one = 1;
1992 const Scalar two = 2;
1993
1994 Scalar xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
1995 Scalar k1, k2, k3, k4, k5, k6, k7, k8, k26update;
1996 Scalar ans;
1997 int n;
1998
1999 constexpr int num_iters = (std::is_same<Scalar, float>::value) ? 100 : 300;
2000 const Scalar thresh = (std::is_same<Scalar, float>::value) ? machep : Scalar(3) * machep;
2001 Scalar r = (std::is_same<Scalar, float>::value) ? zero : one;
2002
2003 if (small_branch) {
2004 k1 = a;
2005 k2 = a + b;
2006 k3 = a;
2007 k4 = a + one;
2008 k5 = one;
2009 k6 = b - one;
2010 k7 = k4;
2011 k8 = a + two;
2012 k26update = one;
2013 } else {
2014 k1 = a;
2015 k2 = b - one;
2016 k3 = a;
2017 k4 = a + one;
2018 k5 = one;
2019 k6 = a + b;
2020 k7 = a + one;
2021 k8 = a + two;
2022 k26update = -one;
2023 x = x / xc;
2024 }
2025
2026 pkm2 = zero;
2027 qkm2 = one;
2028 pkm1 = one;
2029 qkm1 = one;
2030 ans = one;
2031 n = 0;
2032
2033 do {
2034 xk = -(x * k1 * k2) / (k3 * k4);
2035 pk = pkm1 + pkm2 * xk;
2036 qk = qkm1 + qkm2 * xk;
2037 pkm2 = pkm1;
2038 pkm1 = pk;
2039 qkm2 = qkm1;
2040 qkm1 = qk;
2041
2042 xk = (x * k5 * k6) / (k7 * k8);
2043 pk = pkm1 + pkm2 * xk;
2044 qk = qkm1 + qkm2 * xk;
2045 pkm2 = pkm1;
2046 pkm1 = pk;
2047 qkm2 = qkm1;
2048 qkm1 = qk;
2049
2050 if (qk != zero) {
2051 r = pk / qk;
2052 if (numext::abs(ans - r) < numext::abs(r) * thresh) {
2053 return r;
2054 }
2055 ans = r;
2056 }
2057
2058 k1 += one;
2059 k2 += k26update;
2060 k3 += two;
2061 k4 += two;
2062 k5 += one;
2063 k6 -= k26update;
2064 k7 += two;
2065 k8 += two;
2066
2067 if ((numext::abs(qk) + numext::abs(pk)) > big) {
2068 pkm2 *= biginv;
2069 pkm1 *= biginv;
2070 qkm2 *= biginv;
2071 qkm1 *= biginv;
2072 }
2073 if ((numext::abs(qk) < biginv) || (numext::abs(pk) < biginv)) {
2074 pkm2 *= big;
2075 pkm1 *= big;
2076 qkm2 *= big;
2077 qkm1 *= big;
2078 }
2079 } while (++n < num_iters);
2080
2081 return ans;
2082 }
2083};
2084
2085/* log(Gamma(a + b) / (Gamma(a) Gamma(b))) is evaluated as lgamma(a + b) - lgamma(a) - lgamma(b), whose error is about
2086 * eps M (log M - 1) for M = max(a, b), the rounding of lgamma(M), which the caller's exp() turns into relative error.
2087 * Where that reaches ~0.1, i.e. M >= 1 / (64 eps) (1.3e5 in float, 7e13 in double), the result is garbage and
2088 * betainc_stirling_ratio, which has no such cancellation when m = min(a, b) <= M / 4, is used instead. Below that
2089 * threshold the sum is kept: its rounding errors are correlated with those of the continued fraction, which uses the
2090 * same a + b, and the Stirling form is not systematically better there. The callers apply this only where 1 - x
2091 * rounds to 1, the inputs that otherwise hang; every other input keeps the original arithmetic. */
2092template <typename Scalar>
2093EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE bool betainc_use_stirling_ratio(Scalar a, Scalar b) {
2094 const Scalar big = numext::maxi(a, b);
2095 return big * NumTraits<Scalar>::epsilon() >= Scalar(1.0 / 64) && Scalar(4) * numext::mini(a, b) <= big;
2096}
2097
2098/* Stirling's series (DLMF 5.11.1) with the large terms combined, for L = M + m, M >= 1 / (64 eps):
2099 * lgamma(L) - lgamma(M) = m log M + (L - 1/2) log1p(m / M) - m + (1/12)(1/L - 1/M) - (1/360)(1/L^3 - 1/M^3) + O(M^-5)
2100 * and the remaining term is -lgamma(m). */
2101template <typename Scalar>
2102EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar betainc_stirling_ratio(Scalar a, Scalar b) {
2103 const Scalar M = numext::maxi(a, b);
2104 const Scalar m = numext::mini(a, b);
2105 const Scalar sum = M + m;
2106 const Scalar sum_inv = Scalar(1) / sum;
2107 const Scalar M_inv = Scalar(1) / M;
2108 Scalar d = m * numext::log(M) + (sum - Scalar(0.5)) * numext::log1p(m / M) - m;
2109 d += (Scalar(1) / Scalar(12)) * (sum_inv - M_inv) -
2110 (Scalar(1) / Scalar(360)) * (sum_inv * sum_inv * sum_inv - M_inv * M_inv * M_inv);
2111 return d - lgamma_impl<Scalar>::run(m);
2112}
2113
2114/* Helper functions depending on the Scalar type */
2115template <typename Scalar>
2116struct betainc_helper {};
2117
2118template <>
2119struct betainc_helper<float> {
2120 /* Core implementation, assumes a large (> 1.0) */
2121 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float incbsa(float aa, float bb, float xx) {
2122 float ans, a, b, t, x, onemx, xc, logx;
2123 bool reversed_a_b = false;
2124
2125 onemx = 1.0f - xx;
2126 // 1 - xx rounds to 1: after reversing, x would be 1 and its complement x / (1 - x) infinite.
2127 const bool onemx_is_one = (onemx == 1.0f);
2128
2129 /* see if x is greater than the mean */
2130 if (xx > (aa / (aa + bb))) {
2131 reversed_a_b = true;
2132 a = bb;
2133 b = aa;
2134 t = xx;
2135 x = onemx;
2136 } else {
2137 a = aa;
2138 b = bb;
2139 t = onemx;
2140 x = xx;
2141 }
2142
2143 // In the degenerate case use the exact 1 - x = xx (reversed) or log(1 - xx) = log1p(-xx) in place of the rounded 1.
2144 const bool degenerate = reversed_a_b && onemx_is_one;
2145 xc = degenerate ? t : 1.0f - x;
2146 logx = degenerate ? numext::log1p(-xx) : numext::log(x);
2147
2148 /* Choose expansion for optimal convergence */
2149 if (b > 10.0f) {
2150 if (numext::abs(b * x / a) < 0.3f) {
2151 t = betainc_helper<float>::incbps(a, b, x, xc, logx, degenerate ? numext::log(t) : numext::log1p(-x),
2152 onemx_is_one);
2153 if (reversed_a_b) t = 1.0f - t;
2154 return t;
2155 }
2156 }
2157
2158 const float log_t = (onemx_is_one && !reversed_a_b) ? numext::log1p(-xx) : numext::log(t);
2159 ans = x * (a + b - 2.0f) / (a - 1.0f);
2160 if (ans < 1.0f) {
2161 ans = incbeta_cfe<float>::run(a, b, x, xc, true /* small_branch */);
2162 t = b * log_t;
2163 } else {
2164 ans = incbeta_cfe<float>::run(a, b, x, xc, false /* small_branch */);
2165 t = (b - 1.0f) * log_t;
2166 }
2167
2168 if (onemx_is_one && betainc_use_stirling_ratio(a, b)) {
2169 t += a * logx + betainc_stirling_ratio(a, b);
2170 } else {
2171 t += a * logx + lgamma_impl<float>::run(a + b) - lgamma_impl<float>::run(a) - lgamma_impl<float>::run(b);
2172 }
2173 t += numext::log(ans / a);
2174 t = numext::exp(t);
2175
2176 if (reversed_a_b) t = 1.0f - t;
2177 return t;
2178 }
2179
2180 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float incbps(float a, float b, float x, float xc, float logx,
2181 float logxc, bool xc_rounds_to_one) {
2182 float t, u, y, s;
2183 const float machep = cephes_helper<float>::machep();
2184
2185 y = a * logx + (b - 1.0f) * logxc - numext::log(a);
2186 if (xc_rounds_to_one && betainc_use_stirling_ratio(a, b)) {
2187 y += betainc_stirling_ratio(a, b);
2188 } else {
2189 y -= lgamma_impl<float>::run(a) + lgamma_impl<float>::run(b);
2190 y += lgamma_impl<float>::run(a + b);
2191 }
2192
2193 t = x / xc;
2194 s = 0.0f;
2195 u = 1.0f;
2196 // Safety net against an endless loop: for b >= 2^24, b -= 1 changes nothing, and a ratio u_{k+1} / u_k of 1 never
2197 // decays. Convergent sums need at most b + 1 < 2^24 iterations (thousands for b ~ 5e4 with t b / a ~ 1).
2198 int n = 0;
2199 do {
2200 b -= 1.0f;
2201 if (b == 0.0f) {
2202 break;
2203 }
2204 a += 1.0f;
2205 u *= t * b / a;
2206 s += u;
2207 } while (numext::abs(u) > machep && ++n < (1 << 24));
2208
2209 return numext::exp(y) * (1.0f + s);
2210 }
2211};
2212
2213template <>
2214struct betainc_impl<float> {
2215 EIGEN_DEVICE_FUNC static float run(float a, float b, float x) {
2216 const float nan = NumTraits<float>::quiet_NaN();
2217 float ans, t;
2218
2219 if ((numext::isnan)(a) || (numext::isnan)(b) || (numext::isnan)(x)) return nan;
2220 if (a == 0.0f && b == 0.0f) return nan;
2221 if (x < 0.0f || x > 1.0f) return nan;
2222 if (a < 0.0f) return nan;
2223 if (b < 0.0f) return nan;
2224 if (a == 0.0f) return 1.0f;
2225 if (b == 0.0f) return 0.0f;
2226 if (x == 0.0f) return 0.0f;
2227 if (x == 1.0f) return 1.0f;
2228 // mtherr("betaincf", DOMAIN);
2229
2230 /* transformation for small aa */
2231 if (a <= 1.0f) {
2232 ans = betainc_helper<float>::incbsa(a + 1.0f, b, x);
2233 if (1.0f - x == 1.0f && betainc_use_stirling_ratio(a + 1.0f, b)) {
2234 // Gamma(a + b) / (Gamma(a + 1) Gamma(b)) = Gamma(a + 1 + b) / (Gamma(a + 1) Gamma(b)) / (a + b).
2235 t = a * numext::log(x) + b * numext::log1p(-x) + betainc_stirling_ratio(a + 1.0f, b) - numext::log(a + b);
2236 } else {
2237 t = a * numext::log(x) + b * numext::log1p(-x) + lgamma_impl<float>::run(a + b) -
2238 lgamma_impl<float>::run(a + 1.0f) - lgamma_impl<float>::run(b);
2239 }
2240 return (ans + numext::exp(t));
2241 } else {
2242 return betainc_helper<float>::incbsa(a, b, x);
2243 }
2244 }
2245};
2246
2247template <>
2248struct betainc_helper<double> {
2249 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE double incbps(double a, double b, double x) {
2250 const double machep = cephes_helper<double>::machep();
2251
2252 double s, t, u, v, n, t1, z, ai;
2253
2254 ai = 1.0 / a;
2255 u = (1.0 - b) * x;
2256 v = u / (a + 1.0);
2257 t1 = v;
2258 t = u;
2259 n = 2.0;
2260 s = 0.0;
2261 z = machep * ai;
2262 while (numext::abs(v) > z) {
2263 u = (n - b) * x / n;
2264 t *= u;
2265 v = t / (a + n);
2266 s += v;
2267 n += 1.0;
2268 }
2269 s += t1;
2270 s += ai;
2271
2272 u = a * numext::log(x);
2273 // TODO: gamma() is not directly implemented in Eigen.
2274 /*
2275 if ((a + b) < maxgam && numext::abs(u) < maxlog) {
2276 t = gamma(a + b) / (gamma(a) * gamma(b));
2277 s = s * t * pow(x, a);
2278 }
2279 */
2280 if (1.0 - x == 1.0 && betainc_use_stirling_ratio(a, b)) {
2281 t = betainc_stirling_ratio(a, b) + u + numext::log(s);
2282 } else {
2283 t = lgamma_impl<double>::run(a + b) - lgamma_impl<double>::run(a) - lgamma_impl<double>::run(b) + u +
2284 numext::log(s);
2285 }
2286 return numext::exp(t);
2287 }
2288};
2289
2290template <>
2291struct betainc_impl<double> {
2292 EIGEN_DEVICE_FUNC static double run(double aa, double bb, double xx) {
2293 const double nan = NumTraits<double>::quiet_NaN();
2294 const double machep = cephes_helper<double>::machep();
2295 double a, b, t, x, xc, w, y;
2296 bool reversed_a_b = false;
2297
2298 if ((numext::isnan)(aa) || (numext::isnan)(bb) || (numext::isnan)(xx)) return nan;
2299 if (aa == 0.0 && bb == 0.0) return nan;
2300 if (xx < 0.0 || xx > 1.0) return nan;
2301 if (aa < 0.0) return nan;
2302 if (bb < 0.0) return nan;
2303 if (aa == 0.0) return 1.0;
2304 if (bb == 0.0) return 0.0;
2305 if (xx == 0.0) return 0.0;
2306 if (xx == 1.0) return 1.0;
2307 // mtherr("incbet", DOMAIN);
2308
2309 if ((bb * xx) <= 1.0 && xx <= 0.95) {
2310 return betainc_helper<double>::incbps(aa, bb, xx);
2311 }
2312
2313 w = 1.0 - xx;
2314
2315 /* Reverse a and b if x is greater than the mean. If 1 - xx rounds to 1, x = w = 1 below and its complement
2316 * x / (1 - x) is infinite: use the exact xc = xx instead. */
2317 const bool w_is_one = (w == 1.0);
2318 if (xx > (aa / (aa + bb))) {
2319 reversed_a_b = true;
2320 a = bb;
2321 b = aa;
2322 xc = xx;
2323 x = w;
2324 } else {
2325 a = aa;
2326 b = bb;
2327 xc = w;
2328 x = xx;
2329 }
2330
2331 if (reversed_a_b && (b * x) <= 1.0 && x <= 0.95) {
2332 t = betainc_helper<double>::incbps(a, b, x);
2333 if (t <= machep) {
2334 t = 1.0 - machep;
2335 } else {
2336 t = 1.0 - t;
2337 }
2338 return t;
2339 }
2340
2341 /* Choose expansion for better convergence. */
2342 y = x * (a + b - 2.0) - (a - 1.0);
2343 if (y < 0.0) {
2344 w = incbeta_cfe<double>::run(a, b, x, reversed_a_b && w_is_one ? xc : 1.0 - x, true /* small_branch */);
2345 } else {
2346 w = incbeta_cfe<double>::run(a, b, x, reversed_a_b && w_is_one ? xc : 1.0 - x, false /* small_branch */) / xc;
2347 }
2348
2349 /* Multiply w by the factor
2350 a b _ _ _
2351 x (1-x) | (a+b) / ( a | (a) | (b) ) . */
2352
2353 y = a * ((reversed_a_b && w_is_one) ? numext::log1p(-xx) : numext::log(x));
2354 t = b * ((xc < 1.0) ? numext::log(xc) : numext::log1p(-xx));
2355 // TODO: gamma is not directly implemented in Eigen.
2356 /*
2357 if ((a + b) < maxgam && numext::abs(y) < maxlog && numext::abs(t) < maxlog)
2358 {
2359 t = pow(xc, b);
2360 t *= pow(x, a);
2361 t /= a;
2362 t *= w;
2363 t *= gamma(a + b) / (gamma(a) * gamma(b));
2364 } else {
2365 */
2366 /* Resort to logarithms. */
2367 if (w_is_one && betainc_use_stirling_ratio(a, b)) {
2368 y += t + betainc_stirling_ratio(a, b);
2369 } else {
2370 y += t + lgamma_impl<double>::run(a + b) - lgamma_impl<double>::run(a) - lgamma_impl<double>::run(b);
2371 }
2372 y += numext::log(w / a);
2373 t = numext::exp(y);
2374
2375 /* } */
2376 // done:
2377
2378 if (reversed_a_b) {
2379 if (t <= machep) {
2380 t = 1.0 - machep;
2381 } else {
2382 t = 1.0 - t;
2383 }
2384 }
2385 return t;
2386 }
2387};
2388
2389} // end namespace internal
2390
2391namespace numext {
2392
2393template <typename Scalar>
2394EIGEN_DEVICE_FUNC inline auto lgamma(const Scalar& x) -> decltype(EIGEN_MATHFUNC_IMPL(lgamma, Scalar)::run(x)) {
2395 return EIGEN_MATHFUNC_IMPL(lgamma, Scalar)::run(x);
2396}
2397
2398template <typename Scalar>
2399EIGEN_DEVICE_FUNC inline auto digamma(const Scalar& x) -> decltype(EIGEN_MATHFUNC_IMPL(digamma, Scalar)::run(x)) {
2400 return EIGEN_MATHFUNC_IMPL(digamma, Scalar)::run(x);
2401}
2402
2403template <typename Scalar>
2404EIGEN_DEVICE_FUNC inline auto zeta(const Scalar& x, const Scalar& q)
2405 -> decltype(EIGEN_MATHFUNC_IMPL(zeta, Scalar)::run(x, q)) {
2406 return EIGEN_MATHFUNC_IMPL(zeta, Scalar)::run(x, q);
2407}
2408
2409template <typename Scalar>
2410EIGEN_DEVICE_FUNC inline auto polygamma(const Scalar& n, const Scalar& x)
2411 -> decltype(EIGEN_MATHFUNC_IMPL(polygamma, Scalar)::run(n, x)) {
2412 return EIGEN_MATHFUNC_IMPL(polygamma, Scalar)::run(n, x);
2413}
2414
2415template <typename Scalar>
2416EIGEN_DEVICE_FUNC inline auto erf(const Scalar& x) -> decltype(EIGEN_MATHFUNC_IMPL(erf, Scalar)::run(x)) {
2417 return EIGEN_MATHFUNC_IMPL(erf, Scalar)::run(x);
2418}
2419
2420template <typename Scalar>
2421EIGEN_DEVICE_FUNC inline auto erfc(const Scalar& x) -> decltype(EIGEN_MATHFUNC_IMPL(erfc, Scalar)::run(x)) {
2422 return EIGEN_MATHFUNC_IMPL(erfc, Scalar)::run(x);
2423}
2424
2425template <typename Scalar>
2426EIGEN_DEVICE_FUNC inline auto ndtri(const Scalar& x) -> decltype(EIGEN_MATHFUNC_IMPL(ndtri, Scalar)::run(x)) {
2427 return EIGEN_MATHFUNC_IMPL(ndtri, Scalar)::run(x);
2428}
2429
2430template <typename Scalar>
2431EIGEN_DEVICE_FUNC inline auto igamma(const Scalar& a, const Scalar& x)
2432 -> decltype(EIGEN_MATHFUNC_IMPL(igamma, Scalar)::run(a, x)) {
2433 return EIGEN_MATHFUNC_IMPL(igamma, Scalar)::run(a, x);
2434}
2435
2436template <typename Scalar>
2437EIGEN_DEVICE_FUNC inline auto igamma_der_a(const Scalar& a, const Scalar& x)
2438 -> decltype(EIGEN_MATHFUNC_IMPL(igamma_der_a, Scalar)::run(a, x)) {
2439 return EIGEN_MATHFUNC_IMPL(igamma_der_a, Scalar)::run(a, x);
2440}
2441
2442template <typename Scalar>
2443EIGEN_DEVICE_FUNC inline auto gamma_sample_der_alpha(const Scalar& a, const Scalar& x)
2444 -> decltype(EIGEN_MATHFUNC_IMPL(gamma_sample_der_alpha, Scalar)::run(a, x)) {
2445 return EIGEN_MATHFUNC_IMPL(gamma_sample_der_alpha, Scalar)::run(a, x);
2446}
2447
2448template <typename Scalar>
2449EIGEN_DEVICE_FUNC inline auto igammac(const Scalar& a, const Scalar& x)
2450 -> decltype(EIGEN_MATHFUNC_IMPL(igammac, Scalar)::run(a, x)) {
2451 return EIGEN_MATHFUNC_IMPL(igammac, Scalar)::run(a, x);
2452}
2453
2454template <typename Scalar>
2455EIGEN_DEVICE_FUNC inline auto betainc(const Scalar& a, const Scalar& b, const Scalar& x)
2456 -> decltype(EIGEN_MATHFUNC_IMPL(betainc, Scalar)::run(a, b, x)) {
2457 return EIGEN_MATHFUNC_IMPL(betainc, Scalar)::run(a, b, x);
2458}
2459
2460} // end namespace numext
2461} // end namespace Eigen
2462
2463#endif // EIGEN_SPECIAL_FUNCTIONS_H
Namespace containing all symbols from the Eigen library.
const Eigen::CwiseBinaryOp< Eigen::internal::scalar_zeta_op< typename DerivedX::Scalar >, const DerivedX, const DerivedQ > zeta(const Eigen::ArrayBase< DerivedX > &x, const Eigen::ArrayBase< DerivedQ > &q)
Definition SpecialFunctionsArrayAPI.h:141