1/2
gives
0
as it should. However,
-1/2
gives
-1
Python's default division of integers is return the floor (towards negative infinity) with no ability to change that. You can read the BDFL's reason why.
To do 'round up' division, you would use:
>>> a=1
>>> b=2
>>> (a+(-a%b))//b
1
>>> a,b=-1,2
>>> (a+(-a%b))//b
0
To do truncation towards zero, and maintain integer division, you use (a+(-a%b))//b
if either a or b are negative and the default division if both are positive.
This will do integer division and always round towards zero:
>>> a=1
>>> b=2
>>> a//b if a*b>0 else (a+(-a%b))//b
0
>>> a=-1
>>> b=2
>>> a//b if a*b>0 else (a+(-a%b))//b
0
>>> a,b=-3,2
>>> a//b if a*b>0 else (a+(-a%b))//b
-1
>>> a,b=3,2
>>> a//b if a*b>0 else (a+(-a%b))//b
1
Interestingly enough, C99 declares that round towards zero is the default:
#include
int main(int argc, const char * argv[])
{
int a=-3;
int b=2;
printf("a=%d, b=%d, a/b=%d\n",a,b,a/b);
a=3;
printf("a=%d, b=%d, a/b=%d\n",a,b,a/b);
return 0;
}
Prints:
a=-3, b=2, a/b=-1
a=3, b=2, a/b=1