1

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.

Arthur
  • 199,419
rhauder_
  • 111

2 Answers2

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
  • Thank you very much. It worked. – rhauder_ Oct 08 '13 at 10:16
  • That avoids the $\infty/\infty$ problem, but $x$ doesn't have to be particularly large before the floating-point result collapses to $1$ anyway. Perhaps what's really needed in the large-$x$ case is a numerically robust way to compute $1-\tanh x$ instead? – hmakholm left over Monica Oct 08 '13 at 10:16
  • Actually in my problem is said that I have to evaluate the function for big values(i.e. 1000)and to observe that I'm not getting a number.So I have to find another way to compute this function and be precise as possible. – rhauder_ Oct 08 '13 at 10:22
  • @rhauder: If you're representing the result as an IEEE double, you might as well compute it as the constant 1.0 if $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
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$.