numpy `arange` exceeds end value?

安稳与你 提交于 2019-12-13 01:51:01

问题


I had expected numpy's arange(start,end) to produce values in the range [start,end]. The following example demonstrates that that's not always true (the final value is larger than end):

  import numpy as np
  start=2e9
  end=start+321
  step=0.066833171999
  x=np.arange(start,end,step=step)
  print x[-1]>end  # Prints "True"
  print x[-1]-end  # Prints 0.00013661384582519531

The error seems far too large to be caused by machine precision (but perhaps I'm thinking about it incorrectly). What's going on?

PS: I'm using Numpy version 1.10.1


回答1:


From the arange docs:

Array of evenly spaced values.

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.

Your step times the length of the array is larger than 321. linspace is more careful about end points.



来源:https://stackoverflow.com/questions/35376101/numpy-arange-exceeds-end-value

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