Woj*_*chR 5 python numpy logarithm numeric hyperbolic-function
我的模拟需要实现
np.log(np.cosh(x))
Run Code Online (Sandbox Code Playgroud)
这会溢出 large x,即我收到RuntimeWarning: overflow encountered in cosh警告。原则上,随着对数减少所讨论的数字,在 的某个范围内x,cosh应该溢出而不log(cosh())应该溢出。
在 NumPy 中是否有任何解决方案,例如在精神上与np.log1p()功能相似?
提供更多信息:我知道一个可能的解决方案可能是符号使用 SymPy https://github.com/sympy/sympy/issues/12671 但是模拟应该很快,并且符号计算 AFAIK 可能会显着减慢它的速度。
以下实现log(cosh(x))应该是数值稳定的:
import numpy as np
def logcosh(x):
# s always has real part >= 0
s = np.sign(x) * x
p = np.exp(-2 * s)
return s + np.log1p(p) - np.log(2)
Run Code Online (Sandbox Code Playgroud)
解释:
对于实际值,您可以使用以下标识:
log(cosh(x)) = logaddexp(x, -x) - log(2)
= abs(x) + log1p(exp(-2 * abs(x))) - log(2)
Run Code Online (Sandbox Code Playgroud)
这在数值上是稳定的,因为 的参数exp总是非正的。对于复数,我们要求参数 toexp具有非正实部,我们通过使用-xwhenreal(x) > 0和xelse来实现。