Home > Enterprise >  Why do Pi and E have different precision in java.lang.Math?
Why do Pi and E have different precision in java.lang.Math?

Time:12-02

In java.lang.Math, we can see two constants:

public static final double E = 2.7182818284590452354;

public static final double PI = 3.14159265358979323846;

I'm curious why pi is accurate to 20 decimal places, and E to 19.

CodePudding user response:

It's irrelevant since the Math.E version can't hold the precision specifed in the library. The trunc version is missing the next 4 digits but the IEEE754 bits are identical to both.

long elib = Double.doubleToLongBits(2.7182818284590452354);
String elibbits =Long.toBinaryString(elib);
long etrunc = Double.doubleToLongBits(2.718281828459045);
String etruncbits = Long.toBinaryString(etrunc);
System.out.println(elibbits);
System.out.println(etruncbits);
System.out.println(elibbits.equals(etruncbits));

prints

100000000000101101111110000101010001011000101000101011101101001
100000000000101101111110000101010001011000101000101011101101001
true

Perhaps the author knew that beyond a certain number of decimal places that extraneous digits would be ignored.

Here is the linke to the IEEE754 Wiki page. The table says that 64 bits can hold a maximum of 15.95 digits.

  • Related