Evaluation of log(1 + large number) without overflow

132 Views Asked by At

In the middle of some involved computations, I came across the following expression: $$f(x,y) = \ln (\cosh x + \sinh x\tanh y)$$

where $x,y$ are real numbers. I need to evaluate $f(x,y)$ over a wide range of values of $x,y$. In particular, $x,y$ can get very large (positive or negative). In this case $\sinh x,\tanh y$ may overflow, although the logarithm remains reasonable.

What numerical tricks can I use to evaluate $f(x,y)$ without risk overflow/underflow?

3

There are 3 best solutions below

2
On BEST ANSWER

hint

$$f (x,y)=$$ $$\ln (\cosh (x))+\ln (1+\tanh (x)\tanh (y)) $$

with

$$\ln (\cosh (x))=\ln (\frac {e^x+e^{-x}}{2}) $$

$$=\ln (e^x\frac {1+e^{-2x}}{2}) $$ $$=x-\ln (2)+\ln (1+e^{-2x}) $$ $$\approx x-\ln (2)+e^{-2x} $$ for large values of $x$.

0
On

$-1 < \tanh(y) < 1$, so that shouldn't overflow if computed with a good algorithm.

$$ f(x,y) = \cases{x + \ln\left(\frac{1+\exp(-2x)}{2} + \frac{1-\exp(-2x)}{2} \tanh(y)\right) & if $x \ge 0$\cr -x + \ln \left(\frac{1+ \exp(2x)}{2} - \frac{1 - \exp(2x)}{2} \tanh(y)\right) & if $x < 0$\cr} $$

0
On

Many computer libraries have a log1p routine that uses a series to compute $\ln(1+x)$ for small $x$. This can help when used with the other answers. (If only, say, to let the computer do the thinking at the point of the $\approx$ sign in Salahamam Fatima's answer.)