-1

On basic operator / and // in Python. Why 99/9.9 returns 10.0 and 99//9.9 returns 9.0?

/ - returns result in float // - returns quotient without reminder in int

so why:

>>> 99/9.9
10.0
>>> 99//9.9
9.0
>>> 9.9*9.0
89.10000000000001

when

>>> 9.9*10.0
99.0
M.wol
  • 901
  • 3
  • 10
  • 21

3 Answers3

3

// is for integer division and returns the floor of the quotient. 5//2 = 2, whereas 5/2 = 2.5. It wouldn’t make sense to use // with floats. As explained by others here, floats are inexactly represented and attempted integer division on them yields unexpected results.

pakpe
  • 5,391
  • 2
  • 8
  • 23
2

9.9 can't be exactly represented as a float (although it is closer than 10^-13 so just typing 9.9 doesn't show 9.9000000001 or anything like that). So a float created from the literal 9.9 is actually slightly greater than 9.9 and 99//9.9 is 9. Similarly, 99%9.9 is 9.899999999999997 and not 0 as we would expect if 9.9 could be exactly represented.

Moral of the story: "//" is mostly for integers and can produce headaches when used on floats.

hacatu
  • 638
  • 6
  • 15
0

That is common.

"Beware that due to the limitations of floating point arithmetic, rounding errors can cause unexpected results" from here.). In that reference you can see with all detail.

Rafael Valero
  • 2,736
  • 18
  • 28