when to use expm1 instead of exp in java
Asked Answered
C

2

8

I am confused about using expm1 function in java The Oracle java doc for Math.expm1 says:

Returns exp(x) -1. Note that for values of x near 0, the exact sum of expm1(x) + 1 is much closer to the true result of ex than exp(x).

but this page says:

However, for negative values of x, roughly -4 and lower, the algorithm used to calculate Math.exp() is relatively ill-behaved and subject to round-off error. It's more accurate to calculate ex - 1 with a different algorithm and then add 1 to the final result.

should we use expm1(x) for negative x values or near 0 values?

Conduction answered 17/8, 2012 at 19:33 Comment(1)
You can always pull some other algorithm off the net and use it. No need to confine yourself to Java's library.Cameo
L
11

The implementation of double at the bit level means that you can store doubles near 0 with much more precision than doubles near 1. That's why expm1 can give you much more accuracy for near-zero powers than exp can, because double doesn't have enough precision to store very accurate numbers very close to 1.

I don't believe the article you're citing is correct, as far as the accuracy of Math.exp goes (modulo the limitations of double). The Math.exp specification guarantees that the result is within 1 ulp of the exact value, which means -- to oversimplify a bit -- a relative error of at most 2^-52, ish.

Likelihood answered 17/8, 2012 at 19:38 Comment(0)
P
8

You use expm1(x) for anything close to 0. Positive or negative.

The reason is because exp(x) of anything close to 0 will be very close to 1. Therefore exp(x) - 1 will suffer from destructive cancellation when x is close to 0.

expm1(x) is properly optimized to avoid this destructive cancellation.


From the mathematical side: If exp is implemented using its Taylor Series, then expm1(x) can be done by simply omitting the first +1.

Preemption answered 17/8, 2012 at 19:37 Comment(2)
But that page says: "roughly -4 and lower", does lower means here negative values close to 0 or smaller negative values?Conduction
@Conduction I actually disagree with that statement. It seems that the author is confusing two different sources of numerical instability in the taylor expansion of exp(x). If you apply the series directly to large negative numbers, then yes the it will be unstable. So in practice you flip x positive and take the reciprocal at the end. But I can't imagine that Math.exp(x) doesn't already do that.Preemption

© 2022 - 2024 — McMap. All rights reserved.