Numpy - arange: Why does the following example not end with 10

I am a beginner in Python. Dive in to learn numpy.

import numpy as np
x = np.arange(0.5, 10.4, 0.8, int)

      

output:

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 ]

      

I expected it to return (last item 10.4):

[ 0  1  2  3  4  5  6  7  8  9 10 ]

      

Apart from the above, if I do this (understand this example):

x = np.arange(0.5, 10.4, 0.8)
print(x)

      

It prints:

[  0.5  1.3  2.1  2.9  3.7  4.5  5.3  6.1  6.9  7.7  8.5  9.3  10.1 ]

      

+3


source to share


1 answer


This is a rather strange way to call arange

. The behavior is undocumented and I don't think there was much thought involved. Here's what's going on, at least in the current version, based on source .

Using the original arguments you passed, 0.5, 10.4, and 0.8, NumPy calculates the length of the result and the second element using a _calc_length

helper function. These calculations are done in Python object arithmetic, and the length is converted to an integer npy_intp

. In your case, the length is calculated as 13.



NumPy then allocates an array of the requested datatype and computed length, and stores the first two elements in the array. When items are stored, they undergo normal NumPy dtype transformations. In your case, the first two elements are coerced to 0 and 1.

Finally, NumPy calls a new array fill

to fill the array with the values ​​computed from the first two elements. The function fill

resets the step from the first two elements, so it calculates step 1 and fills the array with integers from 0 to 12.

+7


source







All Articles