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
notfor Numpy arrays. - safest way (if cumbersome) is to always use
numpy.logical_not(). - If never using Numpy arrays,
notis usable. - If always using Numpy arrays,
~is usable, but it’s safer to usenumpy.logical_not(). notwill at least throw aValueErroron a Numpy array, rather than silently giving the wrong value as~will on non-Numpy arrays.
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.