0

I encountered a question when I wanted to generate a numpy array using numpy.arange. For example, I want to generate an array that contains 3862 elements:

array1=numpy.arange(3.5678,3.5678+3862*0.0001,0.0001)

But the shape of array1 is (3863,). And what made me more confused is this:

In:
numpy.arange(3.5678,3.5678+3860*0.0001,0.0001).shape
numpy.arange(3.5678,3.5678+3861*0.0001,0.0001).shape
numpy.arange(3.5678,3.5678+3862*0.0001,0.0001).shape
numpy.arange(3.5678,3.5678+3863*0.0001,0.0001).shape
Out:
(3861,);(3861,);(3863,);(3863,)

Why did this happen? Due to the precision?

Many thanks!

yangyong
  • 51
  • 1
  • 1
  • 2

1 Answers1

0

According to numpy doc:

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.

And also:

stop number: End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

You can check out this duplicate question or this one for more detail and info on how to deal with the situation.

Ehsan
  • 12,072
  • 2
  • 20
  • 33