How to simulate C style integer division?

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jan 21 05:22:51 EST 2016


On 21 January 2016 at 08:39, Shiyao Ma <i at introo.me> wrote:
>
> I wanna simulate C style integer division in Python3.
>
> So far what I've got is:
> # a, b = 3, 4
>
> import math
> result = float(a) / b
> if result > 0:
>   result = math.floor(result)
> else:
>   result = math.ceil(result)
>
>
> I found it's too laborious. Any quick way?

How precise do you want to be? I think that having a negative divisor
doesn't come up much in practise but this matches in all cases anyway:

   atruncb = abs(a) // abs(b) if a * b > 0 else - (abs(a) // abs(b))

If you don't care about the negative divisor case then it becomes:

   atruncb = abs(a) // b if a > 0 else - (abs(a) // b)

Note that for integers in Python these are exact and will work for
integers of any size. Using floating point is unnecessary here and
would have overflow problems.

--
Oscar



More information about the Python-list mailing list