I have the following expression. $$ \tanh (x) = \frac{\sinh x}{\cosh x} = \frac{e^x - e^{-x}}{e^x + e^{-x}} $$ I know that they derive one from another , but how do I rewrite them in alternative forms in order to not get a NaN(not a number) when will be evaluating for big values. I get NaN for the last 2 formulas. Thank you.
Asked
Active
Viewed 1,895 times
2 Answers
1
For large positive $x$ rewrite the formula as $$ \tanh (x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}= \frac{e^x - e^{-x}}{e^x + e^{-x}}\frac{e^{-x}}{e^{-x}} = \frac{1 - e^{-2x}}{1 + e^{-2x}}\cdot $$ The last fraction can be evaluated without overflow. For negative $x$ use $\tanh(-x)=-\tanh(x).$
gammatester
- 18,827
0
Gammatester's solution avoids the $\infty/\infty$ problem, but $x$ doesn't have to be particularly large before the true result would round to 1.0 in machine floating point anyway.
In case you need the difference between $\tanh x$ and $1$ in your application, it would probably be beneficial to switch to something like $$ 1 - \tanh x = \frac{2}{e^{2x}+1} $$ when $x$ is larger than about $1$.
hmakholm left over Monica
- 286,031
-
-
@gammatester: If $e^{2x}$ overflows a double, then the true value of $1-\tanh x$ would underflow to
0.0anyway -- and that is exactly what machine arithmetic would produce here too, since $2/\infty=0$. (This happens around $x=700$, give or take a few). – hmakholm left over Monica Oct 08 '13 at 10:29 -
No it is better to write $$ 1 - \tanh x = \frac{2e^{-2x}}{1+e^{-2x}}$$ to get the complete asymptotic form of $1 - \tanh x.$ – gammatester Oct 08 '13 at 10:30
-
-
That depends on the machine/language/compiler: If the default action is overflow=exception and underflow=flush-to-zero, it is better to use the second form. – gammatester Oct 08 '13 at 10:38
1.0if $x$ is greater than about $40$. It will be closer to that than to the largest representable number less than $1$. – hmakholm left over Monica Oct 08 '13 at 10:27