Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top