首页 > 解决方案 > Numpy Boolean 按位意外行为

问题描述

我有一个代码,它采用一个 numpy 价格数组,并在所需范围内找到折扣。
由于某种原因,输出不如预期。

我的代码是:

# prices
prices = np.arange(5, (1-0.4-0.01)*5, -0.1)

# calculate discounts for each price
discounts_calculated =  (max(prices)-prices)/max(prices)

# choose prices in range of (10,30) percent discount
chosen_inds = (0.1<=discounts_calculated) & (discounts_calculated<=0.3) 
chosen_discounts = discounts_calculated[ chosen_inds ]

# show output
print(prices)
print(discounts_calculated)
print(chosen_discounts)

输出是:

[5.  4.9 4.8 4.7 4.6 4.5 4.4 4.3 4.2 4.1 4.  3.9 3.8 3.7 3.6 3.5 3.4 3.3
 3.2 3.1 3. ]
[0.   0.02 0.04 0.06 0.08 0.1  0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26
 0.28 0.3  0.32 0.34 0.36 0.38 0.4 ]
[0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26 0.28 0.3 ]

而预期的输出应该包括.1最后一个数组中的元素:

[5.  4.9 4.8 4.7 4.6 4.5 4.4 4.3 4.2 4.1 4.  3.9 3.8 3.7 3.6 3.5 3.4 3.3
 3.2 3.1 3. ]
[0.   0.02 0.04 0.06 0.08 0.1  0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26
 0.28 0.3  0.32 0.34 0.36 0.38 0.4 ]
[0.1 0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26 0.28 0.3 ]

如何更改代码以便按位比较起作用?

标签: numpyindexingbitwise-and

解决方案


推荐阅读