Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 551
JACKY Li Avatar asked Mar 03 '23 22:03

JACKY Li


1 Answers

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])
like image 173
user3483203 Avatar answered May 12 '23 17:05

user3483203