satwikkansal / wtfpython

What the f*ck Python? 😱
Do What The F*ck You Want To Public License
35.51k stars 2.65k forks source link

Why does ~True evaluate to -2 ? #293

Open lcrmorin opened 2 years ago

lcrmorin commented 2 years ago

I don't see it in the list. Working in a jupyter notebook ~True evaluates to -2. ( ~np.array(True) correctly evaluates to False).

Can someone explain the answer ? Does it need to be added in the list ?

satwikkansal commented 2 years ago

Thanks for the suggestion.

~ is a bitwise NOT operator, which essentially inverts all the 1s and 0s in the binary representation of the operand. The int value of True is 1. So essentially what you're seeing is ~1, which is -2. Why ~1 is -2 needs a bit tricky to explain. The negative numbers are internally represented as two's complement, and when you apply the ~, by flipping the bits, you end up exactly at the binary representation of -2. This StackOverflow thread explains it to some extent https://stackoverflow.com/a/12946226/4354153

I think this would be a good addition to the collection (if someone's up for the challenge, most welcome :), otherwise I'll add it in next major revision) because it's sometimes tempting to use ~ in the boolean conditional logic but it can lead to confusing results like

>>> True == ~False
False

and of course also because numpy handles it differently as you suggested (need to look deeper into it).

lcrmorin commented 2 years ago

Thanks for the explanation. This is frightening as I might have used this before...

jablka commented 1 year ago

thank you, this is interesting :)

>>> ~True
-2

>>> ~False
-1

>>> ~True + ~False
-3

and I didn't know you can even add True to integer:

>>> 5 + True
6