简体   繁体   English

numpy中的分段函数具有多个参数

[英]Piecewise function in numpy with multiple arguments

I tried to define a function (tent map) as following: 我试图定义一个函数(帐篷图),如下所示:

def f(r, x):
    return np.piecewise([r, x], [x < 0.5, x >= 0.5], [lambda r, x: 2*r*x, lambda r, x: 2*r*(1-x)])

And r, x will be numpy arrays: r,x将是numpy数组:

no_r = 10001
r = np.linspace(0, 4, no_r)
x = np.random.rand(no_r)

I would like the result to be a numpy array matching the shapes of r and x, calculated using each pairs of elements of arrays r and x with the same indicies. 我希望结果是一个匹配r和x形状的numpy数组,该数组使用具有相同索引的数组r和x的每对元素来计算。 For example if r = [0, 1, 2, 3] and x = [0.1, 0.7, 0.3, 1], the result should be [0, 0.6, 1.2, 0]. 例如,如果r = [0,1,2,3]和x = [0.1,0.7,0.3,1],则结果应为[0,0.6,1.2,0]。 An error occured: "boolean index did not match indexed array along dimension 0; dimension is 2 but corresponding boolean dimension is 10001" So what should I do to achieve the intended purpose? 发生错误:“布尔索引与维度0上的索引数组不匹配;维度为2,但相应的布尔维度为10001”那么我应该怎么做才能达到预期的目的?

what you want to get as result can be done with np.select such as: 您想要得到的结果可以通过np.select完成,例如:

def f(r, x):
    return np.select([x < 0.5,x >= 0.5], [2*r*x, 2*r*(1-x)])

Then with 然后用

r = np.array([0, 1, 2, 3])
x = np.array([0.1, 0.7, 0.3, 1])

print (f(r,x))
[0.  0.6 1.2 0. ]

EDIT: in this case, with only 2 conditions that are exclusive, you can also use np.where : 编辑:在这种情况下,只有两个条件是互斥的,您也可以使用np.where

def f(r,x):
    return np.where(x<0.5,2*r*x, 2*r*(1-x))

will give the same result. 将给出相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM