JACKY88
JACKY88

Reputation: 3557

Generate equally-spaced values including the right end using NumPy.arange

Suppose I want to generate an array between 0 and 1 with spacing 0.1. In R, we can do

> seq(0, 1, 0.1)
 [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

In Python, since numpy.arange doesn't include the right end, I need to add a small amount to the stop.

np.arange(0, 1.01, 0.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

But that seems a little weird. Is it possible to force numpy.arange to include the right end? Or maybe some other functions can do it?

Upvotes: 6

Views: 2040

Answers (3)

Jörg J. Buchholz
Jörg J. Buchholz

Reputation: 79

Adding the step to the stop does not always work:

start = 1
stop = 2
step = 0.2

np.arange (start, stop + step, step)

# array([1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2])

Upvotes: 0

user3483203
user3483203

Reputation: 51155

You should be very careful using arange for floating point steps. From the docs:

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.

Instead, use linspace, which allows you to specify the exact number of values returned.

>>> np.linspace(0, 1, 11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

linspace also does in fact let you specify whether or not to include an endpoint (True by default):

>>> np.linspace(0, 1, 11, endpoint=True)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0, 1, 11, endpoint=False)
array([0.        , 0.09090909, 0.18181818, 0.27272727, 0.36363636,
       0.45454545, 0.54545455, 0.63636364, 0.72727273, 0.81818182,
       0.90909091])

Upvotes: 6

yatu
yatu

Reputation: 88236

No, as mentioned in the docs:

End of interval. The interval does not include this value...

For the end of the interval to include the actual ending value, you must add step to the end, there's no way around. Maybe a little cleaner:

step = 0.1
start = 0.
stop = 1.

np.arange(start, stop+step, step)
# array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

Upvotes: 4

Related Questions