Which is more accurate? java.lang.Math.E or Math.e

2020-08-09 06:18发布

问题:

Reading the Javadocs, I see that Math.E is "The double value that is closer than any other to e, the base of the natural logarithms.". The printed value for Math.E is 2.718281828459045 while the value of Math.exp(1.0), which should be the same value is: 2.7182818284590455 (one more 5 at the end).

From the docs, it sounds like the bits in Math.E have been "manually adjusted" to get closer to the actual value of e than the calculation produced by Math.exp(1.0). Is this correct, or am I reading the docs incorrectly?

If that is correct, then is using Math.pow(Math.E, n) more accurate than Math.exp(n), or less? I've Googled and search SO, but can't find anything on this particular issue.

回答1:

The actual value to 16 decimal places is 2.7182818284590452; 2 is closer to 0 than to 5, so the constant is closer.

Note that when doing floating point calculations with either number it's quite likely the error in the floating point representation of your answer will make which one you use largely irrelevant.



回答2:

Math.E

2.718281828459045

Math.exp(1.0)

2.7182818284590455

So this is the value from Wikipedia, 2.7182818284590452 The only difference I can see is a rounding error on the last digit of the Math.exp(1.0) where the value is 5 instead of 2. So strictly speaking Math.E is more accurate but unless you're doing some really crazy stuff, it won't matter for precision.

There may be speed considerations for using the precalculated Math.E instead of Math.exp(1.0). You might want to check that out too.



标签: java math