Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does division "/" and floored division "//" operators in python gives different results for divisions with a remainder = 0?

When dividing somewhat large integers with numbers that divides them, I get different results from division / and floored division //.

for instance:

In [1]: a = 123456789012345678

In [2]: int(a/2)
Out[2]: 61728394506172840

In [3]: a//2
Out[3]: 61728394506172839

clearly 2|a, and out[3] is the correct answer, so why the inconsistency from the division operator? what is going on? and, How to make / behave correctly?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

/ is the floating division operator, thus your integer is stored into a float type. This type cannot store exactly every value, only approximations, see:

>>> a = 123456789012345678
>>> a/2
6.172839450617284e+16

You lose the last digit… 123456789012345678 approximately equals to 6.172839450617284 * 10^16.
Look what happens for "huge" numbers:

>>> float(1234512345123451234512345)
1.2345123451234512e+24

Floats are basically scientific notation with fixed size mantissa.

While // is the integer division operator, and integer type (in Python) is of arbitrary precision (only in the domain of integers):

>>> 2**1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading