How to simulate C style integer division?
Steven D'Aprano
steve at pearwood.info
Thu Jan 21 07:42:53 EST 2016
On Thu, 21 Jan 2016 08:11 pm, Ben Finney wrote:
> Shiyao Ma <i at introo.me> writes:
>
>> I wanna simulate C style integer division in Python3.
>
> I'm not sure I know exactly what behaviour you want (“C style” may mean
> different things to each of us).
Surely is means "whatever the C standard defines integer division to mean".
Are their any C programmers here who can tell us what the C standard says?
According to this:
http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c
the behaviour of integer division was implementation dependent in C89, but
has now been specified in detail since C99. The answer is that a/b for
integers a and b *truncate towards zero*. That is, it returns the integer
part with no fractional part:
Both arguments are positive, or both negative:
11/2 = 5.5 so throw away the 0.5 and return 5
-11/-2 = 5.5 so throw away the 0.5 and return 5
One argument is positive and the other negative:
-11/2 = -5.5 so throw away the 0.5 and return -5
11/-2 = -5.5 so throw away the 0.5 and return -5
Python's integer division // performs flooring, not truncating, so it
disagrees in the case that exactly one of the arguments are negative:
py> 11//2
5
py> -11//-2
5
py> 11//-2
-6
py> -11//2
-6
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
--
Steven
More information about the Python-list
mailing list