how to specify a range in numpy.piecewise (2 conditions per range)

Psw*_*s87 5 python numpy piecewise

I am trying to construct a piecewise function for some digital signal processing, but I cannot get numpy.piecewise to allow me to specify a range.

Here is what I want to input:

t = np.arange(-10,10,1)
x = lambda x: x**3
fx = np.piecewise(t, [t < -1 and t>-2, t <= 0 and t>-1, t>=0 and t<1,t>1 and t<2], [x(t + 2), x(-t),x(t),-x(2-t)])
plot(t,fx)
Run Code Online (Sandbox Code Playgroud)

However, I get the error: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

After dissecting the function, it seems the issue is that this function won't allow 2 conditions in one such as: t < -1 and t>-2

但在我看来,允许指定范围对于许多分段函数是必不可少的.有没有办法实现这个目标?

谢谢!

Nic*_*bey 5

这是因为你不能使用和numpy数组.您需要替换numpy布尔数组的andwith *orwith +.(并且不要忘记添加括号).


gg3*_*349 4

添加到 Nicolas 的答案中的另一个问题是,funclist如果您想使用piecewise. 您更正后的代码如下所示

t = np.arange(-2,2,.01)
f1 = lambda t: (t+2)**3
f2 = lambda t: (-t)**3
f3 = lambda t: (t)**3
f4 = lambda t: -(2-t)**3
fx = np.piecewise(t, [(t< -1)*(t>=-2), (t <= 0) * (t>=-1), (t>0) * (t<1),(t>=1) * (t<=2)], [f1,f2,f3,f4])
plot(t,fx)
Run Code Online (Sandbox Code Playgroud)

相反,你可以使用select

t = np.arange(-2,2,.01)
f = lambda x: x**3
fx = np.select([(t< -1)*(t>=-2), (t <= 0) * (t>=-1), (t>0) * (t<1),(t>=1) * (t<=2)], [f(t+2),f(-t),f(t),-f(2-t)])
plot(t,fx)
Run Code Online (Sandbox Code Playgroud)

此外,select允许您通过将默认值传递到参数中来设置定义的间隔之外的默认值default。如果您想坚持(-10,10)间隔范围,您可能需要它。