Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

According to this documentation, np.arange restores an array with the values from the first to the last (Excluding the last) with a division you pick. 

My example:

In[600]: np.arange(1,11,1)

Out[600]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

In [602]: np.arange(1,4,0.2)

Out[602]: array([ 1. ,  1.2,  1.4,  1.6,  1.8,  2. ,  2.2,  2.4,  2.6,  2.8,  3. ,

    3.2,  3.4,  3.6,  3.8])

In [604]: np.arange(3.24,3.6,0.04)

Out[604]: array([ 3.24,  3.28,  3.32,  3.36,  3.4 ,  3.44,  3.48,  3.52,  3.56])

But:

In [605]: np.arange(14.04, 14.84, 0.08)

Out[605]: array([ 14.04,  14.12,  14.2 ,  14.28,  14.36,  14.44,  14.52,  14.6 ,

    14.68,  14.76,  14.84])

What's up with this last one? For what reason does it return 14.84 as opposed to halting at 14.76? 

I have been seeing that it happens here and there, however, I'm not ready to see a supporter or something like that. What's happening?

1 Answer

0 votes
by (26.4k points)

It's Floating point precision.

For example, just look at this question.

You can actually get around it like so: 

>>> np.arange(14.04, 14.839, 0.08)

array([ 14.04, 14.12, 14.2, 14.28, 14.36, 14.44, 14.52, 14.6, 14.68, 14.76])

be that as it may, this is quite hacky. It's normally a superior plan to utilize numpy.linspace(), yet then you need to give the quantity of steps, not the span (interval), so it tends to be somewhat of a pain.

>>> np.linspace(14.04, 14.76, 9)

array([ 14.04,  14.13,  14.22,  14.31, 14.4, 14.49,  14.58, 14.67, 14.76])

Looking for a best python tutorial course? Then join the python certification course.

For more details, do check out the below video tutorial...

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...