10000 Minor accuracy improvement for statistics.correlation() by rhettinger · Pull Request #107781 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

Minor accuracy improvement for statistics.correlation() #107781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 8, 2023

Conversation

rhettinger
Copy link
Contributor

Perform sqrt(x * y) with only a single rounding. For example with x=0.1836988816815257 and y=0.9200609291953, the new computation gives 0.4111133222993899 instead of 0.41111332229938985.

Here's a script to demonstrate the improvement:

from math import sumprod, sqrt
from random import random
from decimal import Decimal, getcontext

getcontext().prec = 100

def sqrtprod_baseline(x: float, y: float) -> float:
    return sqrt(x * y)

def sqrtprod_decimal(x: float, y: float) -> float:
    x, y = map(Decimal, (x, y))
    return float((x * y).sqrt())

def sqrtprod_new(x: float, y: float) -> float:
    h = sqrt(x * y)
    x = sumprod((x, h), (y, -h))
    return h + x / (2.0 * h)

for i in range(100):
    x, y = random(), random()
    assert sqrtprod_new(x, y) == sqrtprod_decimal(x, y)
    if sqrtprod_baseline(x, y) != sqrtprod_decimal(x, y):
        print(i, x, y)
        print(sqrtprod_baseline(x, y))
        print(sqrtprod_decimal(x, y))
        print(sqrtprod_new(x, y))
        print()
    

Sample output:

@rhettinger rhettinger merged commit d4ac094 into python:main Aug 8, 2023
@rhettinger rhettinger deleted the statistics_sqrtprod branch August 8, 2023 16:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.13 bugs and security fixes skip issue skip news
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0