Python gotcha (got me at least)

Armitage

Banned
Feb 23, 2001
8,086
0
0
Here's a neat trick:

-(1/2) != -1/2

C & Fortran programmers are familiar with integer division truncating the result, so in C:

1/2 = -1/2 = 0

Python instead takes the floor of the result:

1/2 = 0
-1/2 = -1

Turns out this is an occasionally debated topic on comp.lang.python. The Python method has some argument for being more mathematically correct, but I bet it bites lots of C programmers!
It took me the better part of the afternoon to figure out what was wrong with some code I brought over from one of my C++ tools.

Oh well ... off to rebuild a 3 GB database :disgust:
 

Chaotic42

Lifer
Jun 15, 2001
34,546
1,708
126


<< Here's a neat trick:

-(1/2) != -1/2
>>



Lol, that got me too. Python is still my favorite language though.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0


<<

<< Here's a neat trick:

-(1/2) != -1/2
>>



Lol, that got me too. Python is still my favorite language though.
>>



Yea, well it gets worse actually. If you use NumPy (Numerical Python), it passes the integer division straight through to the C library. So now you can have two different behaviors for a fundemental operation in the same language depending on what library you use. I really like Python, but that bites. They need to pick a standard and stick to it.

Well, I know to never assume anything about integer division again :D
I just wonder what other suprises are lurking in there.