Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do I lose precision while multiplying and dividing whole ints?
    primarykey
    data
    text
    <p>I had thought Python3 is supposed to be able to handle numbers of arbitrary length, but I'm running into a problem where they don't seem to act consistently.</p> <p>After multiplying then dividing, my int seems to have changed it's internal representation, and no longer evaluates as a match for it's former self.</p> <p>I'm using whole numbers, without any decimals or fractions, but it's acting almost as if it's losing precision to rounding..?</p> <p>I'd appreciate any insight on why this is happening, and if there's something I should be doing differently. I have workarounds for my code, but since the result is counter-intuitive, I'd love to know what's behind the behavior ;)</p> <pre><code>Python 3.3.2 (default, Jul 30 2013, 00:52:04) [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; a = 313585730727764141482831584863 &gt;&gt;&gt; a 313585730727764141482831584863 &gt;&gt;&gt; b = a*2 &gt;&gt;&gt; c = b /2 &gt;&gt;&gt; a 313585730727764141482831584863 &gt;&gt;&gt; c 3.1358573072776415e+29 &gt;&gt;&gt; a == c False </code></pre> <p>This seems to work if I use floor division, however-</p> <pre><code>&gt;&gt;&gt; c = b//2 &gt;&gt;&gt; c 313585730727764141482831584863 &gt;&gt;&gt; a == c True </code></pre> <p>Python 2.7 also seems to avoid this scenerio, keeping them in <code>longs</code></p> <pre><code>&gt;&gt;&gt; a = 313585730727764141482831584863 &gt;&gt;&gt; a 313585730727764141482831584863L &gt;&gt;&gt; b = a*2 &gt;&gt;&gt; c = b /2 &gt;&gt;&gt; a 313585730727764141482831584863L &gt;&gt;&gt; c 313585730727764141482831584863L &gt;&gt;&gt; a == c True </code></pre> <p>I'd appreciate any insight! Thank you!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload