np.sum does not return exact summation

555 views Asked by At

Consider the following numpy vector of number:

a = np.array([.1, .2, .2, .2, .2, .1])

Obviously, the sum of these numbers gives 1. However, when computing

b = np.sum(a)

I get

print (b)
0.9999999999999999

Could you anyone explain why and how to solve this approximation issue?

2

There are 2 answers

0
Reza On

This is due to the machine floating point accuracy. It is explained here in detail: https://docs.python.org/3/tutorial/floatingpoint.html

You can use the following to fix it:

b = round(np.sum(a),5)
print(b)
1
NesteruS On

You can change precision choosing a different data type:

n = 1000

print(abs(1 - np.array([1 / n] * n).sum(dtype='float32')))
print(abs(1 - np.array([1 / n] * n).sum(dtype='float64')))
print(abs(1 - np.array([1 / n] * n).sum(dtype='float128')))

will produce:

1.1920928955078125e-07
4.440892098500626e-16
2.0816681711721685133e-17