bizi
bizi

Reputation: 3457

Error with Python modulo on scientific notation

I hope someone can help me with an explanation for this strange result on large divisor, or suggest me with some keywords so can I get a better search.

>>> m = 1e9+9
>>> n = 1000000009
>>> m == n
True
>>> 2549015908609065 % m
885667930.0
>>> 2549015908609065 % n
885667930
>>> 2549015908609065L % n
885667930L
>>> 2549015908609065L % m
885667930.0

>>> 254901590860906524041412370460835L % m
98506080.0
>>> 254901590860906524041412370460835L % n
327998297L

>>> 254901590860906524041412370460835L % int(m)
327998297L

Upvotes: 1

Views: 1138

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 76907

m = 1e9+9 stores the number as a float; however n = 1000000009 stores the numbers as an integer.

When you divide an integer number by a float, python implicitly outputs a float as a result; However, when you divide an integer by another integer, you get the integral quotient. The precision of Float over bigger numbers gets reduced.

If you notice,

>>> 254901590860906524041412370460835L % m
98506080.0
#outputted a float with different precision

>>> 254901590860906524041412370460835L % n
327998297L
#outputted a long int

Check http://www.tutorialspoint.com/python/python_numbers.htm for a basic tutorial on python numbers

Upvotes: 1

Dhara
Dhara

Reputation: 6767

The reason you are seeing strange results is because you are performing modulo on floating point numbers, which have an inexact representation. The documentation on the decimal module highlights this quite well.

To perform exact operations on very large number, you can use the decimal class as follows:

from decimal import *
print Decimal(2549015908609065) % Decimal(1e9) # Gives the answer you expect

Upvotes: 2

Related Questions