Skip to main content

Modules/_statistics.c

Source:

cpython 3.14 @ ab2d84fe1023/Modules/_statistics.c

Modules/_statistics.c is a small C accelerator for the statistics module. It provides _normal_dist_inv_cdf, the inverse cumulative distribution function (quantile function) for the normal distribution, using a rational-approximation algorithm that avoids floating-point precision loss for extreme probability values.

Map

LinesSymbolRole
1-50includes, ndtri_cCephes ndtri function inclusion
51-150_statistics__normal_dist_inv_cdf_implPython wrapper around ndtri
151-200Module init_statistics module definition

Reading

Inverse CDF for normal distribution

The inverse CDF (ndtri) maps a probability p in (0, 1) to the z-score of the standard normal distribution. The implementation uses the Cephes library's rational polynomial approximation which provides high accuracy across the full range including the tails.

// Modules/_statistics.c:51 _statistics__normal_dist_inv_cdf_impl
static PyObject *
_statistics__normal_dist_inv_cdf_impl(PyObject *module, double p,
double mu, double sigma)
{
if (p <= 0.0 || p >= 1.0) {
PyErr_SetString(PyExc_StatisticsError,
"p must be in the range 0.0 < p < 1.0");
return NULL;
}
double x = ndtri(p) * sigma + mu;
return PyFloat_FromDouble(x);
}

Special values

For p very close to 0 or 1 (beyond what doubles can represent as non-zero), ndtri returns -inf or +inf respectively. The Python wrapper does not clamp these; callers must handle them.

Relationship to statistics.NormalDist

statistics.NormalDist.inv_cdf(p) calls _statistics._normal_dist_inv_cdf(p, mu, sigma) in the fast path. The pure-Python fallback in statistics.py uses _bisect_root on erf which is considerably slower.

gopy notes

Not yet ported. The planned package path is module/statistics/. Go's gonum.org/v1/gonum/stat/distuv package provides Normal.Quantile(p) with the same functionality.