Skip to content

BUG: np.sum gives inconsistent results with np.float32 reshaped arrays #20458

@mlazzarin

Description

@mlazzarin

Describe the issue:

If I create an array of dtype np.float32 and of shape (2 ** n, ), then I reshape it, the sum over all elements of the array depends on the shape.

In the code below, I create an array of shape (2 ** n,) that sums to 1.
If I reshape it to (2 ** (n-t), 2 ** t), I sum over the first axis, then over the second one, I obtain 0.5.
If I sum over the second axis, then over the first one, I obtain 1.

More precisely, with n = 25 + k, the np.sum(np.sum(x, axis=0)) gives 2 ** (t-k-1) instead of 1, unless t-k>=1.

Finally, if I replace the array of ones with a random array and manipulate it a bit (commented line in the code below), I can obtain inconsistent results also with smaller values of n e.g. n = 20, even if the difference is less striking than in the previous case.

Reproduce the code example:

import numpy as np

n = 26
t = 1

x = np.ones(2 ** n) / 2 ** n
# x = np.random.random(2 ** n) ** 2 / (2 ** n)
x = x.astype(np.float32)
x = np.reshape(x, (2 ** (n - t), 2 ** t))

print(np.sum(x))
print(np.sum(np.sum(x, axis=0)))
print(np.sum(np.sum(x, axis=1)))

Error message:

No response

NumPy/Python version information:

1.21.4 3.9.7 (default, Sep 16 2021, 13:09:58)
[GCC 7.5.0]

Metadata

Metadata

Assignees

No one assigned

    Labels

    57 - Close?Issues which may be closable unless discussion continued

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions