You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
statistics.pstdev and statistics.stdev round some exact Decimal ties to the odd neighbor #162645
With Decimal precision set to 2 and rounding set to ROUND_HALF_EVEN, pstdev and stdev both return 11 for an exact standard deviation of 11.5 and 13 for an exact standard deviation of 12.5. Both values should round to 12.
The last column gives an independent check. The population variance of [0, x] and the sample variance of [0, 0, 0, x] are both exactly x²/4, so both standard deviations equal x/2.
In _decimal_sqrt_of_frac, the correction compares the exact variance with the squared midpoint between the initial estimate and its neighbor. Both comparisons are strict. When the values are equal, the helper keeps the initial estimate even if its last digit is odd. The two rows above exercise opposite sides of that check.
The same discrepancy occurs at the default precision of 28 with x = Decimal(2 * 10**27 + 3).
In _decimal_sqrt_of_frac() (Lib/statistics.py), both midpoint checks are strict (> and <), so exact ties just fall through to return root and keep whatever (Decimal(n) / Decimal(m)).sqrt() happened to give.
Quick question before I open a PR: should tie-breaking here respect getcontext().rounding (e.g. ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN), or always use ROUND_HALF_EVEN to match Decimal.sqrt()?
Thanks for looking into this! I’d use ROUND_HALF_EVEN for exact ties to match Decimal.sqrt(). It uses the active context’s precision and breaks ties to even regardless of getcontext().rounding.
At precision 2, the two examples in the report cover both directions: 11.5 rounds up to 12, and 12.5 rounds down to 12. Those would make good regression tests for the PR.
Activity
rxchitrx commentedon Nov 26, 2026
In
_decimal_sqrt_of_frac()(Lib/statistics.py), both midpoint checks are strict (>and<), so exact ties just fall through toreturn rootand keep whatever(Decimal(n) / Decimal(m)).sqrt()happened to give.Quick question before I open a PR: should tie-breaking here respect
getcontext().rounding(e.g.ROUND_HALF_UP,ROUND_HALF_DOWN,ROUND_HALF_EVEN), or always useROUND_HALF_EVENto matchDecimal.sqrt()?limadog9 commentedon Nov 26, 2026
Thanks for looking into this! I’d use ROUND_HALF_EVEN for exact ties to match Decimal.sqrt(). It uses the active context’s precision and breaks ties to even regardless of getcontext().rounding.
At precision 2, the two examples in the report cover both directions: 11.5 rounds up to 12, and 12.5 rounds down to 12. Those would make good regression tests for the PR.
rxchitrx commentedon Nov 26, 2026
Makes sense, thanks! Opened #162699 using
ROUND_HALF_EVENfor exact ties and included the11.5/12.5(prec=2) cases in the tests.