Search code examples
pythonpython-3.xlong-integerinteger-division

Handling long integer-divisions in python


I observed data loss in python integer division. Below is a sample:

In [37]: 1881676377427221798261593926550420634004875213170503083 * 123456789789456123
Out[37]: 232305724979817822068561403710502859128427941904411569030164388864727209

In [38]: int(232305724979817822068561403710502859128427941904411569030164388864727209 / 123456789789456123)
Out[38]: 1881676377427221679799422390196630516487239698149801984

In [39]: 232305724979817822068561403710502859128427941904411569030164388864727209 / 123456789789456123
Out[39]: 1.8816763774272217e+54

Observation: Over multiple attempts with random long integers, I observed that the numbers seem to differ near about where it loses precision in the mantissa-exponent format.

Can anyone please help me know where I am missing? (Or is this really a limitation!)


Solution

  • In Python 3 integer division is no longer the default. If you would like to use integer division in Python 3 you need to use the // operator rather than /.

    >>> 232305724979817822068561403710502859128427941904411569030164388864727209 / 123456789789456123
    1.8816763774272217e+54
    
    >>> 232305724979817822068561403710502859128427941904411569030164388864727209 // 123456789789456123
    1881676377427221798261593926550420634004875213170503083