Skip to content

Minor improvement to statistics.pdf()#148500

Merged
rhettinger merged 1 commit intopython:mainfrom
rhettinger:statistics_pdf
Apr 13, 2026
Merged

Minor improvement to statistics.pdf()#148500
rhettinger merged 1 commit intopython:mainfrom
rhettinger:statistics_pdf

Conversation

@rhettinger
Copy link
Copy Markdown
Contributor

@rhettinger rhettinger commented Apr 13, 2026

The current code squares sigma and then takes the square root of the result. The unnecessary round-trip increases overflow/underflow risks, costs a little time, and loses a tiny bit of numerical accuracy.

Avoid the round trip by normalizing the data first.

% python3.15 -m timeit -s 'from statistics import NormalDist as ND' -s 'iq=ND(100,15)' 'iq.pdf(121.1)'
2000000 loops, best of 5: 121 nsec per loop

% python3.15 -m timeit -s 'from statistics import NormalDist as ND' -s 'iq=ND(100,15)' 'iq.pdf2(121.1)'
5000000 loops, best of 5: 99.5 nsec per loop

This also makes the error message slightly more accurate. Formerly, a subnormal sigma could underflow the variance to zero and the message would report that sigma itself was zero.

@rhettinger rhettinger added performance Performance or resource usage skip issue skip news labels Apr 13, 2026
@rhettinger rhettinger merged commit e689394 into python:main Apr 13, 2026
56 checks passed
@rhettinger rhettinger deleted the statistics_pdf branch April 13, 2026 16:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance or resource usage skip issue skip news

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant