jax icon indicating copy to clipboard operation
jax copied to clipboard

jax.scipy.special.gammaincc returns values far outside [0, 1] for large a (continued fraction stops unconverged)

Open the-Shallow opened this issue 2 months ago • 1 comments

Description

Description

For large a near x, jax.scipy.special.gammaincc(a, x) returns wrong values, including values far outside [0, 1]: 8.395 for a = x = 1e12 in float64 and 3521.56 for a = x = 1e7 in float32 (SciPy: about 0.5). The error grows with a (float64, a = x: relative error 1e-5 at 1e8, 5e-2 at 1e9, 0.9 at 1e10). _igammac_continued_fraction caps the iteration count at 2000 and returns the unconverged iterate. gammainc(a, x) + gammaincc(a, x) == 1 fails in the same range.

Steps to reproduce

import jax; jax.config.update("jax_enable_x64", True)
import numpy as np
from jax.scipy.special import gammaincc
print(gammaincc(1e12, 1e12))                        # 8.395158321148866   (SciPy 0.4999998670192399)
print(gammaincc(np.float32(1e7), np.float32(1e7)))  # 3521.5645           (SciPy 0.49995795)

Expected

Values in [0, 1] that match SciPy (about 0.5 here).

Suggested fix

For large a, use the uniform asymptotic expansion (Temme) that Cephes/SciPy igamc use when a is large and x is close to a, instead of the continued fraction; at the least, return NaN when the continued fraction has not converged.

System info (python version, jaxlib version, accelerator, etc.)

Environment

JAX / jaxlib 0.11.2 (the latest release, CPU) and 0.10.1, Python 3.12, Ubuntu 24.04, x86_64

the-Shallow avatar Oct 01 '26 21:10 the-Shallow

I'd like to work on this.

The issue is that _igammac_continued_fraction caps the iteration count at 2000 and returns the unconverged iterate for large a near x. The fix is to use the uniform asymptotic expansion (Temme) that Cephes/SciPy igamc use when a is large and x is close to a, instead of the continued fraction.

I'll add a regression test based on the reproducer in the issue.

DawnofGenX avatar Oct 03 '26 11:10 DawnofGenX