Python —被numpy的分段函数所迷惑 [英] Python — confused by numpy's piecewise function
问题描述
我正在尝试在Python中实现分段功能.由于我使用了numpy中的许多工具,因此我仅从中导入所有内容(即from numpy import *
).我的分段函数定义为
I'm trying to implement a piecewise function in Python. Since I'm using quite a few tools from numpy, I simply import everything from it (i.e. from numpy import *
). My piecewise function is defined as
LinQuad = piecewise( t, [t < 1, t >= 1], [lambda t : t, lambda t : t**2] )
这将导致错误NameError: global name 't' is not defined
.我不明白为什么要定义t
—毕竟,没有必要为简单的lambda函数Lin = lambda t : t
定义t
.在某些示例中,定义了t
的域,但是我不知道函数LinQuad
将在哪个值上求值.该怎么办?
which results in the error 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
. In some examples the domain of t
is defined, but I don't know at which values the function LinQuad
will be evaluated. What to do?
推荐答案
我不是numpy专家,但是在我看来,您似乎希望分段返回一个可以在其他地方使用的函数.那不是它的作用-它自己计算函数结果.您可能会编写一个lambda表达式,该表达式将采用任意域并返回其计算结果:
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:
LinQuad = lambda x: piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])
我不太确定在那里定义condlist布尔数组-大概是numpy特有的.
I am none too sure about defining the condlist boolean arrays there - presumably that's something specific to numpy.
或者,如果适合您的情况:
Or if appropriate to your situation:
def LinQuad(x):
return piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])
这篇关于Python —被numpy的分段函数所迷惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!