On 30Dec2018 23:33, Christian Seberino <cseber...@gmail.com> wrote:
Thanks.  I didn’t post new code.  I was just referring back to original
post.

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 BigIntegers do
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):

   class JavaBigInteger(int):

       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
           return JavaBigOnteger(result)

i.e. convert both operands to positive values, divide, adjust the sign.

Some notes:

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__ and __rdivmod__.

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)

Cheers,
Cameron Simpson <c...@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to