Increasing range in np.arange by 1 increases range by 2 instead

江枫思渺然 提交于 2021-02-17 04:27:08

问题


I'm not sure if this is a bug or if I'm doing something wrong. I've got the following code:

r_div = 200
r_max = 1.4
numMax=.84

lowerBin = int((numMax - .2)/(r_max/r_div))
upperBin = int((numMax + .2)/(r_max/r_div))

k =np.arange((r_max/r_div)*lowerBin,(r_max/r_div)*(upperBin+1),r_max/r_div)

When I run np.shape(k), I get (59). Now, if I change the upper limit by one in the last line:

k =np.arange((r_max/r_div)*lowerBin,(r_max/r_div)*(upperBin),r_max/r_div)

and run np.shape(k) again, it gives me 57. I'm not really sure why it's changing by 2 when I'm only changing the upperbound on arange by 1.


回答1:


From arange docs:

arange([start,] stop[, step,], dtype=None)

....

When using a non-integer step, such as 0.1, the results will often not
be consistent.  It is better to use `numpy.linspace` for these cases.


来源:https://stackoverflow.com/questions/64489722/increasing-range-in-np-arange-by-1-increases-range-by-2-instead

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!