Skip to content

variance is inaccurate for arrays of identical, large values (Trac #1098) #1696

Closed

Description

@thouis

Original ticket http://projects.scipy.org/numpy/ticket/1098 on 2009-04-29 by @thouis, assigned to @charris.

Variance calculation is inaccurate for arrays of large, identical values:

from numpy import *
(ones(100000)10.0*20).var()
52756253943791624.0

There are more accurate algorithms for computing variance. One example from Welford (1962) is in the attached file.

Activity

  1. thouis commented on Oct 19, 2012

    @thouis
    ContributorAuthor

    Attachment added by @thouis on 2009-04-29: test_var.py

  2. thouis commented on Oct 19, 2012

    @thouis
    ContributorAuthor

    Milestone changed to 1.4.0 by @cournape on 2009-06-01

  3. thouis commented on Oct 19, 2012

    @thouis
    ContributorAuthor

    Milestone changed to Unscheduled by @cournape on 2009-11-27

  4. thouis commented on Oct 19, 2012

    @thouis
    ContributorAuthor

    @bsouthey wrote on 2011-01-26

    At least on Linux, this can be addressed by the dtype argument:

    import numpy as np
    >>> (np.ones(100000)*10.0**20).var(dtype=np.float64)
    52756253943791624.0
    >>> (np.ones(100000)*10.0**20).var(dtype=np.float128)
    0.0
    

    Of course it just delays the situation when using even larger numbers.

  5. charris commented on Feb 20, 2014

    @charris
    Member

    This is much improved after #3685. Note that the relative error in each term is ~1ulp.

    In [13]: a.std()/1e20
    Out[13]: 1.6383999999999999e-16
    

    The error arises from the determination of the mean combined with the fact that all error are the same, hence no cancellation when adding up the variance. Using Python's "exact" fsum doesn't do any better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions