6

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?

0

3 Answers 3

6

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])
Sign up to request clarification or add additional context in comments.

Comments

4

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. ])

Comments

0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.