[英]Python — confused by numpy's piecewise function
I'm trying to implement a piecewise function in Python. 我正在尝试在Python中实现分段函数。 Since I'm using quite a few tools from numpy, I simply import everything from it (ie from numpy import *
). 由于我使用了numpy中的一些工具,我只需从中导入所有内容(即from numpy import *
)。 My piecewise function is defined as 我的分段函数定义为
LinQuad = piecewise( t, [t < 1, t >= 1], [lambda t : t, lambda t : t**2] )
which results in the error NameError: global name 't' is not defined
. 导致错误NameError: global name 't' is not defined
。 I don't understand why I should define t
— after all, it is not necessary to define t
for a simple lambda function Lin = lambda t : t
. 我不明白为什么我应该定义t
-毕竟,这是没有必要定义t
了一个简单的lambda函数Lin = lambda t : t
In some examples the domain of t
is defined, but I don't know at which values the function LinQuad
will be evaluated. 在一些示例中,定义了t
的域,但是我不知道将评估LinQuad
函数的值。 What to do? 该怎么办?
I'm no numpy expert, but it looks to me like you're expecting piecewise to return a function that you can then use elsewhere. 我不是一个笨拙的专家,但它看起来像你期待分段返回一个你可以在其他地方使用的功能。 That's not what it does - it calculates the function result itself. 这不是它的作用 - 它计算功能结果本身。 You could probably write a lambda expression that would take an arbitrary domain and return your calculation on it: 您可以编写一个lambda表达式,该表达式将采用任意域并返回您的计算:
LinQuad = lambda x: piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])
I am none too sure about defining the condlist boolean arrays there - presumably that's something specific to numpy. 我不太确定在那里定义condlist布尔数组 - 大概是numpy特有的东西。
Or if appropriate to your situation: 或者,如果适合您的情况:
def LinQuad(x):
return piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])
np.piecewise
requires that you define the input domain at the time you call it: np.piecewise
要求您在调用时定义输入域:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html http://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html
You can't really get around how the method is specified. 你无法真正了解如何指定方法。 While you can use lambda functions with it, np.piecewise
does not generate a method that can then be applied against arbitrary domains. 虽然你可以使用lambda函数,但np.piecewise
不会生成一个可以应用于任意域的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.