How to simulate C style integer division?
Terry Reedy
tjreedy at udel.edu
Thu Jan 21 22:27:52 EST 2016
On 1/21/2016 9:56 PM, Terry Reedy wrote:
> On 1/21/2016 3:39 AM, Shiyao Ma wrote:
>
>> I wanna simulate C style integer division in Python3.
>
> There are two problems with this spec: it assumes that 'C style integer
> division' is well defined and that we know the definition. Better:
>
> "How do I write a function 'div' in Python 3 so that the following (with
> values added after each '==') is True:
>
> all((div(1,2) == , div(-1,-2) == , dif(-1,2) == , dif(1,-2) == ))"
>
> For '//', the values would be 0, 0, -1, -1. If you want 0, 0, 0, 0
> (truncation toward 0), then
>
> def div(i, j):
> return (i // j) + ((i < 0) ^ (j < 0))
>
> print(all((div(1,2) == 0, div(-1,-2) == 0,
> div(-1,2) == 0, div(1,-2) == 0)))
>
> prints 'True'.
But fails with remainder 0, as others noted. Lesson: include corner
cases in validation test. Anyway, my main point about writing a clear
spec remains true.
--
Terry Jan Reedy
More information about the Python-list
mailing list