Repository navigation
Description
Description
stats/base/dists/chi/pdf returns Infinity or NaN for large degrees of freedom, including at the mode, where the density is about 0.56. It also returns 0 in the upper tail for moderate k, where the density is still a normal double.
The implementation evaluates the density as a product of separately computed factors:
out = pow( 2.0, 1.0-kh ) * pow( x, k-1.0 ) * exp( -(x*x)/2.0 );
out /= gamma( kh );The intermediate factors overflow or underflow even though the result is well within range:
pow( x, k-1 )overflows once(k-1)*ln(x) > ~709.8. At the modex = sqrt(k-1), this happens forkabove about 250, givingInfinity.gamma( k/2 )also overflows fork > ~343, givingInfinity/Infinity = NaN.exp( -x*x/2 )underflows to0forx > ~38.6, so the result is0even when the true density is around1e-300(e.g.,k = 50,x = 40).
The same expression is in lib/main.js, lib/factory.js, and src/main.c. No other pdf package in stats/base/dists uses this pow/gamma product.
A possible fix is to evaluate the density from its logarithm, as chi/logpdf already does. In a quick check against mpmath over k from 0.5 to 1e6 and x from 0 to well past the mode, exp( logpdf( x, k ) ) had a maximum relative error of about 4e-13 for k <= 1000. It does need the x = 0, k = 1 case from #15604 handled. Another option is the identity pdf(x; k) = 2 x f(x^2; k), where f is the chi-square density (chisquare/pdf delegates to gamma/pdf). That gave about 1e-13 for k >= 2, but it needs separate handling when x*x underflows for k <= 1.
Found while comparing stats/base/dists functions against SciPy and mpmath. The comparison and this report were done with AI assistance (Claude Code); I checked the reproduction and reference values.
Related Issues
- fix: return
ln(sqrt(2/pi))instead ofNaNforx = 0andk = 1instats/base/dists/chi/logpdf#15604 (chi/logpdfreturnsNaNatx = 0fork = 1)
Questions
No.
Demo
No response
Reproduction
var pdf = require( '@stdlib/stats/base/dists/chi/pdf' );
console.log( pdf( 17.0, 300.0 ) );
console.log( pdf( 18.0, 350.0 ) );
console.log( pdf( 40.0, 50.0 ) );
console.log( pdf.factory( 350.0 )( 18.0 ) );Expected Results
0.51808778293712026
0.3525957422162523
1.1166793532743951e-300
0.3525957422162523
Reference values were computed with mpmath at 40 digits from the log-density. SciPy's `chi.pdf` agrees.Actual Results
Infinity
NaN
0
NaNVersion
develop (96a2da6); also @stdlib/stats-base-dists-chi-pdf 0.3.1
Environments
Node.js
Browser Version
N/A
Node.js / npm Version
Node.js v22.16.0
Platform
macOS
Checklist
- Read and understood the Code of Conduct.
- Searched for existing issues and pull requests.
Activity
stdlib-bot commentedon Dec 1, 2026
👋 Hi there! 👋
And thank you for opening your first issue! We will get back to you shortly. 🏃 💨
If you have any further questions while waiting for a response, please join our Zulip community to chat with project maintainers and other community members.