Tilde differences Python vs. Matlab
For those transitioning between Matlab/Octave and Python, the “logical not” tilde ~
operator of Matlab/Octave is NOT matched in Python.
In Python (on non-Numpy variables), ~
means
unary complement.
~
operates on the bits of the byte underlying each non-Numpy Boolean (in Matlab/Octave, boolean is class logical
)
tl;dr:
- Numpy does not allow the word
not
for Numpy arrays. - safest way (if cumbersome) is to always use
numpy.logical_not()
. - If you know you won’t have any Numpy arrays, you can use the word
not
. - If you know you always have Numpy arrays, you can use
~
, but it’s safer to usenumpy.logical_not()
. not
will at least throw aValueError
if you use it on a Numpy array, rather than silently giving the wrong value as~
will on non-Numpy arrays.
We use not
or logical_not()
and avoid ~
to avoid silent failures.
Type | ~ operation |
---|---|
non-Numpy | unary complement ~False ==- 1; ~True == -2 |
Numpy | logical not x=numpy.array(False); ~x==True; ~~x==False |
Matlab | logical not ~false = true; ~true==false |
This critically important distinction comes from the short int (byte) inherited by the Python bool
.