-2

I can't understand the output of this code.

print(1//.2)
print(10//2)

The output of 1st is 4.0 and output of 2nd is 5

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 7
    What isn't clear? – Sayse Aug 13 '19 at 11:56
  • 1
    Floating point values are approximations. – khelwood Aug 13 '19 at 11:59
  • 7
    Since the question was prematurely closed, the answer is that the real number 0.2 has no exact representation as a floating-point value; the value you get is slightly larger than 0.2. As a result, `1 // 0.2` is slightly less than 5, and the `//` operator floors that to 4.0. – chepner Aug 13 '19 at 12:00
  • 1
    https://stackoverflow.com/questions/1535596/what-is-the-reason-for-having-in-python – 404pio Aug 13 '19 at 12:48

1 Answers1

1

To clarify this, the // operator will give you the integer part of the result. So:

10 // 2 = 5
11 // 2 = 5
12 // 2 = 6

To get the rest you can use the modulo operator %:

10 % 2 = 0 
11 % 2 = 1
12 % 2 = 0

Now, when you specify 0.2, this is taken as a floating point value. These are not 100% accurate in the way the system stores them, meaning the exact value of this is likely something like 0.2000000000000000001.

This means that when you do:

1 // 0.2

What you are really doing is:

1 // 0.2000000000000001

Which if course evaluates to 4. If you then try the modulo operator, you will see you get a value less than 0.2. When I ran this I saw:

>>> 1 // 0.2
4.0
>>> 1 % 0.2
0.19999999999999996
michjnich
  • 2,796
  • 3
  • 15
  • 31