3

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?

sourcenouveau
  • 29,356
  • 35
  • 146
  • 243
  • 4
    First I would decide how many digits are needed for the problem at hand, and with that decide the data type (maybe it is worth switching to `BigDecimal`). – SJuan76 Nov 04 '13 at 15:43
  • I'm not an expert in this, but if you take the 13(?) hex digits from the hexadecimal number that is the closest approximation, and convert it to its exact decimal value, I wouldn't be surprised to end up with 20-21 decimal digits. – Teepeemm Nov 04 '13 at 15:52
  • See also http://stackoverflow.com/questions/13542944/how-many-significant-digits-have-floats-and-doubles-in-java – sourcenouveau Nov 04 '13 at 16:17

2 Answers2

4

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

Garrett Hall
  • 29,524
  • 10
  • 61
  • 76
1

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.

Meindratheal
  • 158
  • 2
  • 6
  • I believe this question is asking about the case that a literal can't be exactly represented as a double. Therefore the question is how many significant digits can be specified. – jzd Nov 04 '13 at 15:57