user9210757
user9210757

Reputation:

Floating point division vs integer division gives different answer

I had some issues with a piece of code and ended up doing the following command line snippet.This was just an experiment and I didn't store such large values in any variable in the real code(modulo 10**9 +7).

>>> a=1
>>> for i in range(1,101):
...     a=a*i
...
>>> b=1
>>> for i in range(1,51):
...     b=b*i
...
>>> c=pow(2,50)
>>> a//(b*c)
2725392139750729502980713245400918633290796330545803413734328823443106201171875
>>> a/(b*c)
2.7253921397507295e+78
>>> (a//(b*c))%(10**9 +7)
196932377
>>> (a/(b*c))%(10**9 +7)
45708938.0
>>>

I don't understand why integer divison gives the correct output while floating point divison fails.

Basically I calculated: ( (100!) / ((50!)*(2^50)) ) % (10**9 +7)

Upvotes: 1

Views: 2411

Answers (2)

Green Cloak Guy
Green Cloak Guy

Reputation: 24681

Because of precision.

Integers and floats are coded differently. In particular, in python 3, integers can be arbitrarily large - the one you gave, for example, is more than 250 bits large when you convert it to binary. They're stored in a way that can accommodate however large they are.

However, floating-point numbers are constrained to a certain size - usually 64 bits. These 64 bits are divided into a sign (1 bit), mantissa, and exponent - the number of bits in the mantissa limit how precise the number can be. Python's documentation contains a section on this limitation.

So, when you do

(a//(b*c))%(10**9 +7)

you're performing that calculation with integers, which, again, are arbitrarily large. However, when you do this:

(a/(b*c))%(10**9 +7)

you're performing that calculation with a number that only has 18 significant digits - it's already imprecise, and doing more calculations with it only further corrupts the answer.

What you can do to avoid this, if you need to use very large floating-point numbers, is use python's decimal module (which is part of the standard library), which will not have these problems.

Upvotes: 2

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

The reason is that integers are precise, but floats are limited by the floating point precision: Python2.7 default float precision

Upvotes: 1

Related Questions