## ktsangop 23

Hi everybody.
Could someone explain me the usage of python's modulo operator and/or the fmod function?

why do i get these results?

>>> 23%0.1
0.099999999999998729
>>> import math
>>> math.fmod(23,0.1)
0.099999999999998729
>>>

normally 23 mod 0.1 = 0 because 23 / 0.1 = 230 exactly
is there anything wrong there or did i miss something???

## Gribouillis 1,391

The reason is that due to the binary representation of floating point numbers, the real number 0.1 cannot be represented exactly. On my computer

``````>>> "%.30f" % 0.1
'0.100000000000000005551115123126'``````

It means that 0.1 is slightly above 0.1 ( :) ) and the remainder of the division of 23 by 0.1 is not 0

``````>>> divmod(23, 0.1)
(229.0, 0.099999999999998729)``````

The Decimal class can be used to represent 0.1 exactly

``````>>> from decimal import Decimal
>>> divmod(23, Decimal("0.1"))
(Decimal('230'), Decimal('0.0'))``````

See the discussion here http://docs.python.org/library/decimal.html#module-decimal and also here http://docs.python.org/tutorial/floatingpoint.html .

## ktsangop 23

Ohh... nice... now i will never be sure about my calculations
:(
...unless i always use the decimal module...

Thanks a lot for the enlightenment...
:)

## Gribouillis 1,391

You don't need to worry too much about your calculations as long as you compute quantities which vary continuously (or slowly) with respect to the arguments. The problem is that the remainder modulo x is a discontinuous function. You should not compute a discontinuous function with floating point numbers near a point of discontinuity.

## ktsangop 23

Nice, now it's perfectly clear!

Every day i come to realise more and more that theory is more important than practice in software development...
:)

Thanks a lot.