I have noticed that with an array of completely random numbers, using np.sum vs using a for-loop to iteratively add values seems to produce different values. I have provided the code below.
I want to assume there is some floating-point number related innacuracies going on, but I can’t see why this would be the case/ One thing I have attempted is to truncate/round to a finite number of decimal places, but this also seems to trigger a similar problem.
Python 3.9.12
Numpy 1.21.5
Windows 10 Pro
Thanks in advance.
import numpy as np
np.random.seed(1)
x = np.round( np.random.uniform(0, 1, 100), 3)
y = np.sum(x.copy())
z = 0.0
for xi in x.copy():
z += xi
print("y", y) # With seed=1, y=48.585
print("z", z) # With seed=1, z=48.585000000000015
print(y-z)
I have tried truncating/rounding to a finite number of decimal places.
user25055065 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.