Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does np.arange(0.6, 0.68, 0.01) include 0.68? [duplicate]

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.

like image 287
jhhuang Avatar asked Dec 12 '25 16:12

jhhuang


2 Answers

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.

like image 95
Seon Avatar answered Dec 14 '25 05:12

Seon


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])
like image 45
Alain T. Avatar answered Dec 14 '25 04:12

Alain T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!