I was testing a code in the console and got this:
>>> import numpy as np
>>> np.arange(0.6, 0.68, 0.01)
array([0.6 , 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68])
>>> np.arange(0.6, 0.69, 0.01)
array([0.6 , 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68])
>>> np.arange(0.6, 0.70, 0.01)
array([0.6 , 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69])
Why does np.arange(0.6, 0.68, 0.01) include the number 0.68?
I suppose this might be a problem with the numerical accuracy, but I don't know why.
From the official documentation:
For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.
In this case:
>>> (0.68 - 0.6)/0.01
8.000000000000007
Taking the ceiling of that gives you 9, which means numerical accuracy is indeed to blame here.
The documentation recommends using np.linspace instead when specifying a non-integer step.
Beyond the fact that floating point representation is the culprit here, which others have explained quite well, a way around the issue could be to build the range using integers (which have no such representation issues) and divide by the precision scale:
np.arange(60,68,1)/100
array([0.6 , 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With