Skip to content

statistics.variance() can return a negative result for data containing infinity #160034

Open

Description

@tonghuaroot

Bug description

statistics.variance([-math.inf, 1.0, 2.0]) returns -inf, a negative
variance. Since variance is a mean of squared deviations, a negative value is
impossible. variance() and pvariance() return a non-finite result for any
data containing inf or nan, instead of raising ValueError the way
stdev() and pstdev() already do:

>>> import statistics, math
>>> statistics.variance([-math.inf, 1.0, 2.0])
-inf
>>> statistics.variance([1.0, math.inf])
inf
>>> statistics.pvariance([1.0, math.nan])
nan
>>> statistics.stdev([1.0, math.inf])
Traceback (most recent call last):
  ...
ValueError: inf or nan encountered in data

The result is also internally inconsistent: with an explicit xbar,
variance([-math.inf, 1.0, 2.0], 0.0) returns +inf for the same data.

gh-140938 added the inf or nan encountered in data guard to stdev() and
pstdev() but left variance() and pvariance() unguarded, even though
stdev is the square root of variance.

CPython versions tested on

3.14, 3.15, CPython main branch

Operating systems tested on

macOS

Linked PRs

Activity

  1. tonghuaroot commented on Oct 21, 2026

    @tonghuaroot
    ContributorAuthor

    i have a patch ready for this, same guard as the stdev/pstdev one, plus tests:
    main...tonghuaroot:gh-160034-variance-pvariance-inf-nan

    my account can't open prs at the moment. i'll open the pr as soon as that's resolved.

  2. jadhavroshani713-sys commented on Oct 21, 2026

    @jadhavroshani713-sys

    Thanks for working on this! I was also looking into this issue. I'll review your patch and tests to understand the proposed fix. Please let us know when the PR is available so i can follow the discussion.

  3. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 21, 2026
  4. NekoAsakura commented on Oct 21, 2026

    @NekoAsakura
    Member

    @hugovk bypass for @tonghuaroot? 54 merged, their past PRs look fine.

  5. hugovk commented on Oct 21, 2026

    @hugovk
    Member

    @tonghuaroot You're now in the bypass list.

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

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions