Is there a trick for computing the expression $x + (exp(x)-x)/(exp(2*x) + 1)$ while avoiding an overflow? Currently, computation seems to fail for any $x \geq 710$, presumably because computing $exp(2*x)$ leads to an overflow. The expression as such never produces particularly large numbers, but exponentiation seems to cause problems.

I'm working in R, but the same problem occurs in C++ as well.

If there is no trick for computing it, I'd be just as happy using another non-negative monotonic function which is nearly linear for $x > 10$.


1 Answer 1


Yes, when $x\ge355$, computing $e^{2x}$ as a double-precision float in IEEE 754-1985 standard, leads to an overflow.

$$x + \frac{e^x-x}{e^{2x} + 1}= x + e^{-x} - \frac{x+e^{-x}}{e^{2x} + 1}\approx x+ e^{-x}$$

The difference between the two sides of the approximate sign is smaller than the minimal positive number in IEEE 754-1985 standard, $2^{−1022} \approx 2.225×10^{−308}$, when $x>367.2$.

So, once $x>367.2$, you can just use $x+e^{-x}$ instead.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.