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
>>> import math
>>> math.fmod(23,0.1)

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

Thanks in advance...

6 Years
Discussion Span
Last Post by ktsangop

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

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 .

Edited by Gribouillis: n/a


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

Thanks a lot for the enlightenment...


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.

Edited by Gribouillis: n/a


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.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.