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

shripal mehta
  • 401
  • 4
  • 21
  • 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. – John Coleman Feb 11 '19 at 20:34
  • 2
    `/` does a float division, and you run into floating point limitations. use `//` – Paritosh Singh Feb 11 '19 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. – juanpa.arrivillaga Feb 11 '19 at 20:34

1 Answers1

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
Xorgon
  • 498
  • 1
  • 5
  • 20