Question about slight deviations when using integer division with large integers.
cs at cskk.id.au
Mon Dec 31 04:48:02 EST 2018
On 30Dec2018 23:33, Christian Seberino <cseberino at gmail.com> wrote:
>Thanks. I didn’t post new code. I was just referring back to original
I think Ian looked up the first post on Google Groups, where your code
was evident. The message was incomplete when it got here (the mailing
list); I don't know why.
>I need to duplicate the exact behavior of Java’s BigIntegers.
>I’m guessing difference between Java and Python is that Java
>not switch to floor for negatives.
>Possible to tweak rounding of Python to be like Java?
Directly but hacking the int type? Probably not. What you probably want
to do is to make a JavaBigInteger Python class which subclasses int, and
change its operator implementation. Eg (totally untested):
def __floordiv__(self, other):
sign = 1
if self < 0:
self = -self
sign = -1
if other < 0:
other = - other
sign *= -1
result = self // other
result *= sign
i.e. convert both operands to positive values, divide, adjust the sign.
Changing __floordiv__ needs to have matching changes to __divmod__ and
__mod__ because they're supposed to be consistent.
You probably also need to implement __truediv__, probably a lot like
__floordiv__. There are also __rtruediv__ and __rfloordiv__ and __rmod__
You need to turn whatever integers you're working with into
JavaBigIntegers to make them use the new operator methods, and those
methods should themselves return JavaBigIntegers to keep the behaviour:
# x and y are ints
x = 11
y = -2
print(x // y)
# you already have x and y from somewhere, eg a file
# they are ints, make new JavaBigIntegers from them
xj = JavaBigInteger(x)
yj = JavaBigInteger(y)
print(xj // yj)
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list