Skip to content

statistics.pstdev and statistics.stdev round some exact Decimal ties to the odd neighbor #162645

Backlog

Description

@limadog9

Bug report

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.

from decimal import Decimal, ROUND_HALF_EVEN, localcontext
from statistics import pstdev, stdev

with localcontext(prec=2, rounding=ROUND_HALF_EVEN):
    zero = Decimal(0)
    for x in map(Decimal, (23, 25)):
        print(pstdev([zero, x]), stdev([zero, zero, zero, x]), x / 2)

Output:

11 11 12
13 13 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).

CPython versions tested on:

3.12, CPython main branch, 3.13, 3.14, 3.15

Operating systems tested on:

Linux

Activity

  1. added
    type-bug
    on Nov 25, 2026
  2. added
    stdlib
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions