Question about slight deviations when using integer division with large integers.

Chris Angelico rosuav at gmail.com
Mon Dec 31 02:47:24 EST 2018


On Mon, Dec 31, 2018 at 6:36 PM Ian Kelly <ian.g.kelly at gmail.com> wrote:
>
> The Google group has an initial post in this thread that didn't make it
> through to the mailing list for whatever reason. For posterity, here
> it is:

Thanks Ian.

> > Why are the following two similar prints slightly different and how fix?
> >
> > >>> x = 0x739ad43ed636
> >
> > >>> print(x + (-x) // 2048)
> > 127046758190683
> >
> > >>> print(x - x // 2048)
> > 127046758190684
> >
> > I'm working in an area where such deviations matter.  It would nice to understand what is happening.

This is a distinctly different order of operations. Remember from
grade school that division is done before addition and subtraction;
the first one will calculate (-x)//2048 and then add that onto x, and
the second will calculate x//2048 and then subtract that from x. As
has already been pointed out, Python's // operator is *floor
division*, meaning that it will always round down, whether the number
is positive or negative.

ChrisA


More information about the Python-list mailing list