My simulation needs to implement
np.log(np.cosh(x))
This overflows for large x, i. e. I'm getting the RuntimeWarning: overflow encountered in cosh warning. In principle, as logarithm decreases the number in question, in some range of x, cosh should overflow while log(cosh()) should not.
Is there any solution for that in NumPy, for example similar in spirit to the np.log1p() function?
To provide more info: I am aware that a possible solution might be symbolic using SymPy https://github.com/sympy/sympy/issues/12671 however the simulation should be fast, and symbolic calculation AFAIK might slow it down significantly.
The following implementation of
log(cosh(x))should be numerically stable:Explanation:
For real values you could use the following identity:
which is numerically stable because the argument to
expis always non-positive. For complex numbers we instead require that the argument toexphas non-positive real part, which we achieve by using-xwhenreal(x) > 0andxotherwise.