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

Paul Moore p.f.moore at gmail.com
Mon Dec 31 06:12:06 EST 2018


On Mon, 31 Dec 2018 at 09:00, Christian Seberino <cseberino at gmail.com> wrote:
>
> Thanks.  I didn’t post new code.  I was just referring back to original
> post.  I need to duplicate the exact behavior of Java’s BigIntegers.
>
> I’m guessing difference between Java and Python is that Java BigIntegers do
> not switch to floor for negatives.

Presumably Java BigInteger division consistently rounds to zero,
whereas Python's // operator consistently rounds down.

> Possible to tweak rounding of Python to be like Java?

The correct answer is to have your developers understand the behaviour
of the language they are using, and not assume it's like another
language that they are more familiar with. But I appreciate that's not
always easy. So what you are looking for are ways to help your
developers avoid errors.

Python doesn't have any way to change the behaviour of the //
operator. I assume Java doesn't have a way to make BigInteger division
round down, either?

I doubt that using a custom-defined class in Python would help much -
developers would likely not use it, unless they understood the reason
for it (at which point, they wouldn't need it!). Code reviews,
focusing on the use of the // operator, might be an answer (hopefully
only needed short term until your developers understood the different
behaviours of Java and Python). Or maybe some form of coding
convention (all uses of // must be covered by unit tests that check
all combinations of signs of the 2 operands). Or maybe a function
java_style_divide(), that your conventions mandate must be used in
preference to //

Paul


More information about the Python-list mailing list