Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why does ~True evaluate to -2 ? #293

Open
lcrmorin opened this issue Jun 4, 2022 · 3 comments
Open

Why does ~True evaluate to -2 ? #293

lcrmorin opened this issue Jun 4, 2022 · 3 comments

Comments

@lcrmorin
Copy link

lcrmorin commented Jun 4, 2022

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 ?

@lcrmorin lcrmorin changed the title Why ~True evaluate to -2 ? Why does ~True evaluate to -2 ? Jun 4, 2022
@satwikkansal
Copy link
Owner

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
Copy link
Author

lcrmorin commented Jun 4, 2022

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

@jablka
Copy link

jablka commented Dec 21, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants