How to simulate C style integer division?
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Thu Jan 21 09:22:12 EST 2016
On 1/21/2016 15:00, Jussi Piitulainen wrote:
> Steven D'Aprano writes:
>
>> So my guess is that the fastest, and certainly the most obvious, way
>> to get the same integer division behaviour as C99 would be:
>>
>> def intdiv(a, b):
>> # C99 style integer division with truncation towards zero.
>> n = a//b
>> if (a < 0) != (b < 0):
>> n += 1
>> return n
>
> You should only increment if there is a (non-zero) remainder.
>
Right. Merging Steven's suggestion and fractions.Fraction.__trunc__
implementation I think the right answer may be:
def intdiv2(a,b):
# C99 style integer division with truncation towards zero.
if (a < 0) != (b < 0):
return -(-a // b)
else:
return a // b
Cheers,
Wolfgang
---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus
More information about the Python-list
mailing list