Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Range or numpy Arange with end limit include

Tags:

python

numpy

I am looking to get :

input:

arange(0.0,0.6,0.2)

output:

0.,0.4

I want

0.,0.2,0.4,0.6

how do i achieve using range or arange. If not what is alternate ?

like image 522
WPFKK Avatar asked May 11 '18 19:05

WPFKK


2 Answers

A simpler approach to get the desired output is to add the step size in the upper limit. For instance,

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

would allow you to include the end point as well. In your case:

np.arange(0.0, 0.6 + 0.2, 0.2)

would result in

array([0. , 0.2, 0.4, 0.6]).
like image 124
abm17 Avatar answered Sep 19 '22 19:09

abm17


Old question, but it can be done much easier.

def arange(start, stop, step=1, endpoint=True):
    arr = np.arange(start, stop, step)

    if endpoint and arr[-1]+step==stop:
        arr = np.concatenate([arr,[end]])

    return arr


print(arange(0, 4, 0.5, endpoint=True))
print(arange(0, 4, 0.5, endpoint=False))

which gives

[0.  0.5 1.  1.5 2.  2.5 3.  3.5 4. ]
[0.  0.5 1.  1.5 2.  2.5 3.  3.5]
like image 43
Mehdi Avatar answered Sep 19 '22 19:09

Mehdi