Should be a simple question, but I'm unable to find an answer anywhere. The ~
operator in python is a documented as a bitwise inversion operator. Fine. I have noticed seemingly schizophrenic behavior though, to wit:
~True -> -2
~1 -> -2
~False -> -1
~0 -> -1
~numpy.array([True,False],dtype=int) -> array([-2,-1])
~numpy.array([True,False],dtype=bool) -> array([False,True])
In the first 4 examples, I can see that python is implementing (as documented) ~x = -(x+1)
, with the input treated as an int even if it's boolean. Hence, for a scalar boolean, ~
is not treated as a logical negation. Not that the behavior is identical on a numpy array defined with boolean values by with an int type.
Why does ~
then work as a logical negation operator on a boolean array (Also notice: ~numpy.isfinite(numpy.inf) -> True
?)?
It is extremely annoying that I must use not()
on a scalar, but not()
won't work to negate an array. Then for an array, I must use ~
, but ~
won't work to negate a scalar...
&
and|
. I didn't know about those, and had used logical_and and logical_or instead. – Ovid