I am getting an unexpected result when using mod '%' in Python.
When I type

``print(356%3.56)``

I would expect the result to be 0 as 3.56 goes in to 356 exactly 100 times. However when I run the code it returns 3.5599999999999947.
What is the reason for returning this number and not 0?

3
Contributors
3
Replies
58
Views
5 Months
Discussion Span
Last Post by Gribouillis

Hi,

You could try with `Decimal()`:

``````from decimal import Decimal

# with binary floating points
print(divmod(356, 3.56))
(99.0, 3.5599999999999947)

# with arbitrary roundings
print(Decimal('356') % Decimal('3.56'))
0.0``````

Example: http://ideone.com/a6UDRi

On my computer, when I write

``f = 3.56``

in a python program, the following bits are stored in memory

``0 10000000000 1100011110101110000101000111101011100001010001111011``

This is the IEEE 754 representation of the floating point number 3.56 according to my machine's precision. The corresponding real value is not exactly 3.56, it is

``Fraction(8016407336719483, 2251799813685248)``

This is equal to

``Fraction(356, 100) + Fraction(3, 56294995342131200)``

The error is approximately `5.3290705182e-17`

Also have a look at https://docs.python.org/3/tutorial/floatingpoint.html

Edited by Gribouillis

well written!
That's accurate.