Python中的条件计算

1 投票
2 回答
3189 浏览
提问于 2025-04-19 18:41

我正在尝试使用我自己修改过的 logsumexp() 函数,具体内容可以在这里找到: https://github.com/scipy/scipy/blob/v0.14.0/scipy/misc/common.py#L18

在第85行,有这样一个计算:

out = log(sum(exp(a - a_max), axis=0))

但是我有一个阈值,我不希望 a - a_max 超过这个阈值。 有没有办法进行条件计算,这样只有在差值不小于阈值的情况下才进行减法。 所以类似于:

out = log(sum(exp( (a - a_max < threshold) ? threshold : a - a_max), axis = 0))

2 个回答

1

这样怎么样

out = log(sum(exp( threshold if a - a_max < threshold else a - a_max), axis = 0))
1

在Python中,有一个条件内联语句:

Value1 if Condition else Value2

你的公式变成了:

out = log(sum(exp(threshold if a - a_max < threshold else a - a_max), axis = 0))

撰写回答