为什么,在Python/numpy的:蟒蛇NumPy的奇怪的布尔运算的行为
from numpy import asarray
bools=asarray([False,True])
print(bools)
[False True]
print(1*bools, 0+bools, 0-bools) # False, True are valued as 0, 1
[0 1] [0 1] [ 0 -1]
print(-2*bools, -bools*2) # !? expected same result! :-/
[0 -2] [2 0]
print(-bools) # this is the reason!
[True False]
我认为这是奇怪的是-bools
返回logical_not(bools)
,因为在所有其他情况下的行为是“算术”,而不是“逻辑” 。
一个谁想要使用布尔数组作为一个0/1面具(或“特色功能”)被强制使用某种方式渐开线表达式,如(0-bools)
或(-1)*bools
,并且可以很容易招致成的bug,如果他忘了这个。
为什么会这样,而且这将是获得所期望的行为最好的可以接受的方式? (旁当然评论)
我不明白为什么有人会使用一组布尔值作为掩码,而不是(0,1),这更直观,但我确实看到了一个观点。什么是期望的行为虽然做-2 *假? –
+在Python中一切都是合乎逻辑的。如“blabla”为True(因此有点布尔)和一个字符串在同一时间。 –
@ Ev.Kounis,当我想通过下面的代码写出一个延迟的指数衰减时,我偶然发现了它:delExpDecay = lambda t,d,a,tau:a * exp( - (t
lurix66