我有一个简单的Python函数
def positiveGauss(mean,stdev):
result = -1
while result < 0:
result = mean + np.random.randn()*stdev
return result
使用lambda能否做到同样的技巧?它需要在lambda内部进行迭代,但我仍然相信这是可能的。
lambda m, s: next(x for x in (m + np.random.randn() * s for _ in iter(int, 1)) if x >= 0)
iter
的两个参数形式和两个生成器表达式。
iter(int, 1)
会调用int()
直到它返回1
,但这是不可能发生的。因此内部生成器表达式(m + np.random.randn() * s for _ in iter(int, 1))
这是一个生成器,无限地计算和输出 m + np.random.randn() * s
。外部生成器表达式逐个从内部表达式中取值,但只产生大于等于零的值。然后 next
函数从外部生成器中获取第一个满足条件的内部生成器产生的值。
positive_gauss = lambda mean, stddev, result = -1: positive_gauss(mean, stddev, mean + np.random.randn()*stddev) if result < 0 else result
lambda mean, stddev, result = -1: # takes 3 parameters
positive_gauss(mean, stddev, mean + np.random.randn()*stddev) if result < 0
# ^ Your first condition, if its true call the same function modifying result
else result # if the above one fails just return result.
是的,正如@juanpa.arrivillaga所说,这不应该被使用,因为它失去了匿名函数的本质。
while
循环?因为有一种统计方法可以做到这一点。它与反归一化函数有关。你可以从区间 [0, t](其中 0 < t < 1)中选择一个(随机的)实数。然后将反归一化函数应用于 _t_。不要忘记根据你的参数mean
和stdev
进行缩放。 - Elmex80s