Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not operator, seemingly wrong in Python?

I am new to python and created a small function that does a cluster analysis. The quick rundown is I have to compare two arrays a multitude of times, until it no longer changes. For that I have used a while loop, that loops as long as they are not equal, but I find that I get two different results from != and not ==. MWE:

import numpy as np

a = np.array([1,1,1])
b = np.array([1,2,1])

print((a != b).all())
print(not (a == b))
like image 692
Rewned Avatar asked Aug 24 '26 05:08

Rewned


1 Answers

not (a == b) will raise a ValueError because the truth-value of an array with multiple elements is ambiguous.

The way you invert a boolean array in numpy is with the ~ operator:

>>> a != b
array([False,  True, False], dtype=bool)
>>> ~ (a == b)
array([False,  True, False], dtype=bool)
>>> (~ (a == b)).all() == (a != b).all()
True
like image 83
timgeb Avatar answered Aug 26 '26 20:08

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!