-2

While working with the division remainder operator % in python 2.7 I faced an unexpected behavior (at least for me) when using it with decimal denominators. Bellow an example:

>>> 0.1%0.1
0.0                 # as expected
>>> 0.2%0.1
0.0                 # as expected
>>> 0.3%0.1
0.09999999999999998 # what the hell?
>>> 0.4%0.1
0.0                 # aw expected
>>> 0.5%0.1
0.09999999999999998 # what the hell?

Why the operations 0.3%0.1 and 0.5%0.1 return the result above instead of 0.0 as in the other cases and as I was expecting?

Thanks

Randerson
  • 775
  • 1
  • 5
  • 19
  • 1
    Looks like floating point numbers being inaccurate, see: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – shuttle87 Feb 07 '17 at 13:05

1 Answers1

0

It's how floats behave :

>>> '%.30f' % 0.2
'0.200000000000000011102230246252'
>>> '%.30f' % 0.3
'0.299999999999999988897769753748'

If you want exact results, you could multiply every number by 10 and work with integers.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124