How to simulate C style integer division?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Thu Jan 21 05:13:37 EST 2016


Jussi Piitulainen writes:
> Shiyao Ma writes:
>
>> 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?
>
> The general principle is to define a function when something is too
> laborious to do inline. def truncdiv(a, b): ...
>
> But math.trunc rounds towards 0. Maybe you want to use that here.

It's actually best to avoid floating point altogether. The following
answer by Abhijit was linked from the StackOverflow page[1] where I
found out about C99 integer division:

def trunc_div(a,b):
    q, r = divmod(a,b)
    if  q < 0 and r:
        q += 1
    return q

It adjusts a negative floored quotient towards zero if there was a
remainder.

[1] http://stackoverflow.com/questions/15633787/truncated-versus-floored-division-in-python?rq=1



More information about the Python-list mailing list