Repository navigation
gh-162743: Fix correlation and covariance for large common offsets - #162801
PriyansuMaurya wants to merge 1 commit into
Conversation
Centering on the rounded mean discards the signal when every value shares a large offset, since the deviations are tiny next to the values being subtracted. Center on a shifted frame instead, which keeps the deviations exact, and reuse that for covariance(), which had the same defect.
|
The following commit authors need to sign the Contributor License Agreement: |
|
A human must sign the CLA. |
|
But considering the PR description, this looks entirely generated by an LLM. |
|
Thank you for your interest in contributing to Python. This is a community-driven project, and we want it to be a welcoming place to learn and collaborate. Contributors are responsible for reviewing and understanding what they submit, checking its claims, and being able to explain changes in their own words. This helps reviewers focus on the contribution and leaves more time to support other contributors. We believe this contribution does not meet our guidelines for using AI tools, so we're closing it. If you think we've misunderstood your contribution, please let us know. You're welcome to explain your approach or ask questions about the guidelines. Please read our guidelines for using AI tools. |
|
It's also a duplication of an existing PR. @python/organization-owners Please ban this account. |
Summary
statistics.correlation()andstatistics.covariance()centered the data on a mean computed asfsum(data) / n. When every value shares a large offset, that mean is rounded much more coarsely than the spread of the data, so the deviations lose the signal. For the values in the issue, correlation returns-0.2instead of1.0, and covariance returns-32768.0instead of65536.0.This centers the data on a shifted frame instead: subtract the first value, take the mean of the small remainders, and use those remainders as the deviations. The common offset cancels out exactly, so nothing large is ever rounded. If the shifted values, or their deviations, are not finite, it falls back to the previous computation.
Both functions now share the
_center()helper, because they had the same defect.Test Plan
TestCorrelationAndCovariance.test_large_offset, covering the reported values for correlation and covariance.python -m unittest test.test_statisticspasses: 406 tests.StatisticsError,Decimalstill raisesTypeError, andsetandFractioninputs still work.Relationship to gh-162799
gh-162799 also addresses this issue, by compensating the mean in
correlation()only. Measured against exact rational arithmetic on 10,473 randomized integer datasets with offsets up to 1e18, the shifted-frame version here was closer to the exact value in 9,521 cases and never further away, while the compensation approach left covariance unpatched and made 889 correlation results worse than the unpatched code. Happy to defer if reviewers prefer to fold this into that PR instead.