1

I'm trying to use linspace to equally space a closed interval. My code is as next:

for i in np.linspace(-1,2,6,endpoint=True):
    print(i)

and its out put as next:

-1.0
-0.4
0.19999999999999996
0.7999999999999998
1.4
2.0

My question is about why linspace gives back 0.19999999999999996 and 0.7999999999999998 in the third and fourth places. As far as I understand linspace would increment the starting value with a rational number and as so it could be precisely represent all the values.

Am I right or I totally misunderstand something?

Seanny123
  • 8,776
  • 13
  • 68
  • 124
Gergely Mathe
  • 93
  • 2
  • 11

1 Answers1

0

Almost none of the float values that one uses every day are really precise. That's the nature of float. Most of the time however they are very close to the values we actually think they are, that we don't even notice, because python rounds the numbers before printing. You can use the decimal module to look at the (at least more precise) 'real' values:

from decimal import Decimal
for i in np.linspace(-1,2,6,endpoint=True):
    print(Decimal(i))

output:

-1
-0.40000000000000002220446049250313080847263336181640625
0.1999999999999999555910790149937383830547332763671875
0.79999999999999982236431605997495353221893310546875
1.399999999999999911182158029987476766109466552734375
2

As you can see, except for the first and last value, they are all not precise. The two values you noticed just happen to be a bit more inaccurate.

markuscosinus
  • 2,248
  • 1
  • 8
  • 19