Reputation: 421
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?
Upvotes: 1
Views: 592
Reputation: 64
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
Upvotes: 0
Reputation: 2035
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)
Upvotes: 1