문제

How many significant digits should I use when defining a double literal in Java? This is assuming that I am trying to represent a number with more significant figures than a double can hold.

In Math.java I see 20 and 21:

public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;

This is more than the 15-17 significant digits provided by IEEE 754. So what's the general rule-of-thumb?

도움이 되었습니까?

해결책

A double has 15-17 decimal digits precision.

I can't answer why those constants appear with 20 decimals, but you'll find that those digits are dropped:

2.7182818284590452354d == 2.718281828459045d

다른 팁

If you read the javadocs for Math.E and Math.PI you'll see this (emphasis mine):

The double value that is closer than any other [...]

If your literals can be exactly represented as a double, then do that. Otherwise, find the closest value that is representable.

Of course, depending on how your values are used, it may not matter if you are 'only' accurate to, say, 10 significant figures.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top