4

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!)

3
  • 2
    Use // rather than /? For any integers a,b (even with hundreds of digits) a*b//b will always equal a. If you have a situation where integer division isn't adequate, use the fractions or decimal module. Commented Feb 11, 2019 at 20:34
  • 2
    / does a float division, and you run into floating point limitations. use // Commented Feb 11, 2019 at 20:34
  • 2
    You are using true division. This always resultsin a float object, which has a fixed sized. If you have int objects, and want no loss of precision, use the integer division operator: // int objects in Python are arbitrarily sized. As long as you have the memory/address space, you can do it. Commented Feb 11, 2019 at 20:34

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.