Skip to content
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

np.sum(arr) not equal to reduce(lambda a, b: a+b, arr) #15122

Closed
colin-zhou opened this issue Dec 17, 2019 · 1 comment
Closed

np.sum(arr) not equal to reduce(lambda a, b: a+b, arr) #15122

colin-zhou opened this issue Dec 17, 2019 · 1 comment

Comments

@colin-zhou
Copy link

a random array of np.float64 sum not equal to reduce(lambda a, b: a+b, arr) version

Reproducing code example:

import numpy as np
import sys
x = np.random.random(200)
print("np_sum    ", np.sum(x), file=sys.stderr)
print("reduce_sum", functools.reduce(lambda a,b: b + a, x), file=sys.stderr)

Error message:

the result shows some thing like this (this should be equal)

np_sum 99.13225730835295
reduce_sum 99.13225730835288

Numpy/Python version information:

1.15.2 3.5.6 (default, Nov 16 2018, 15:50:58)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

@eric-wieser
Copy link
Member

eric-wieser commented Dec 17, 2019

Floating point addition is not associative, ie (a + b) + c != a + (b + c) is not always true. Numpy uses pairwise summation, so does not perform the additions in the same order. This tends to produce a more accurate answer than the left-to-right approach used by reduce.

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

No branches or pull requests

2 participants