如何避免立方和的绝对值对数的数值溢出?

How to avoid numerical overflow in log of absolute value of sum of cubes?

我有兴趣计算数量日志(| sum_i [(x_i)^3] |);直接使用 np.log(abs((x**3).sum())) 的问题(其中 x 是一个元素数组,x**3 是将 cube 函数元素明智地应用于数组)是 x**3 中的某些值可能太大并且有潜在的数值问题。

我的计划是使用 logsumexp 技巧。但是,总和之外的绝对值是很难去掉的。有帮助吗?

我们可以使用一点数学来避免数值溢出。

假设 x 是一个 numpy 数组。

问题来自abs((x**3).sum()),特别是立方体操作。我们可以通过按常数缩小 x 中的每个数字来使计算更稳定。因为我们在立方之前除以数组内部的常数,所以我们需要乘以外部求和的常数立方。

换句话说:

abs((x**3).sum()) = (constant**3)*abs(((x/constant)**3).sum())

使用日志的属性,您可以将最终表达式简化为以下内容:

np.log(constant**3) + np.log(abs(((x/constant)**3).sum(0)))