[英]numpy.piecewise returns incorrect answer when using lambda
I'm trying to "splice" a function by inserting a constant part into it using numpy.piecewise: 我试图通过使用numpy.piecewise将常量部分插入其中来“拼接”一个函数:
import numpy as np
func = lambda x: 20 -x
bid_price = 15.0
bid_power = 1.0
bid_start = 5.0
new_func = lambda x: np.piecewise(x, [0 <= x < bid_start,
(x>= bid_start) & (x < bid_start + bid_power), x >= bid_start + bid_power],
[lambda t: func(t), lambda t : bid_price,
lambda t: func(t - bid_power)])
While the function gives correct result for x's that match the first condition, any other x gives me a zero: 虽然函数给出了与第一个条件匹配的x的正确结果,但是任何其他x都给出了零:
In[65]: new_func(15.0)
Out[65]: array(0.0)
I looked through the code of numpy. 我查看了numpy的代码。 piecewise (can't quite debug it), but it doesn't seem like there's anything there to cause this behavior.
分段(不能完全调试它),但似乎没有任何东西导致这种行为。 Casting x to numpy.array doesn't help.
将x转换为numpy.array并没有帮助。 What am I doing wrong here?
我在这做错了什么?
Well, it works if you input a non-scalar np.array
: 好吧,如果您输入非标量
np.array
,它会起作用:
>>> new_func(np.array([15]))
array([6])
With a minor modification (0 <= x) & (x < bid_start)
instead of 0 <= x < bid_start
it also works on an extended array: 稍微修改
(0 <= x) & (x < bid_start)
而不是0 <= x < bid_start
它也适用于扩展数组:
>>> new_func(np.arange(20))
array([20, 19, 18, 17, 16, 15, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2])
I guess np.piecewise
is probably designed not to accept scalars (it's a replacement function for arrays after all) or it's a Bug. 我猜
np.piecewise
可能设计为不接受标量(毕竟它是数组的替代函数)或者它是一个Bug。 But if you want to process scalars you should code it in pure python that's way faster: 但是如果你想处理标量,你应该用纯python编写代码, 这样会更快:
def new_func(x):
if x < 0:
raise ValueError()
elif x < bid_start:
return 20 - x
elif x < bid_start + bid_power:
return bid_price
else:
return 20 - x + bid_power
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.