How accurate is “double-precision floating-point f

2019-08-18 00:18发布

问题:

Let's say, using java, I type

double number;

If I need to use very big or very small values, how accurate can they be? I tried to read how doubles and floats work, but I don't really get it.

For my term project in intro to programming, I might need to use different numbers with big ranges of value (many orders of magnitude).

Let's say I create a while loop,

while (number[i-1] - number[i] > ERROR) {
     //does stuff
}

Does the limitation of ERROR depend on the size of number[i]? If so, how can I determine how small can ERROR be in order to quit the loop?

I know my teacher explained it at some point, but I can't seem to find it in my notes.

回答1:

Does the limitation of ERROR depend on the size of number[i]?

Yes.

If so, how can I determine how small can ERROR be in order to quit the loop?

You can get the "next largest" double using Math.nextUp (or the "next smallest" using Math.nextDown), e.g.

double nextLargest = Math.nextUp(number[i-1]);
double difference = nextLargest - number[i-1];

As Radiodef points out, you can also get the difference directly using Math.ulp:

double difference = Math.ulp(number[i-1]);

(but I don't think there's an equivalent method for "next smallest")



回答2:

If you don't tell us what you want to use it for, then we cannot answer anything more than what is standard knowledge: a double in java has about 16 significant digits, (that's digits of the decimal numbering system,) and the smallest possible value is 4.9 x 10-324. That's in all likelihood far higher precision than you will need.

The epsilon value (what you call "ERROR") in your question varies depending on your calculations, so there is no standard answer for it, but if you are using doubles for simple stuff as opposed to highly demanding scientific stuff, just use something like 1 x 10-9 and you will be fine.



回答3:

Both the float and double primitive types are limited in terms of the amount of data they can store. However, if you want to know the maximum values of the two types, then run the code below with your favourite IDE.

System.out.println(Float.MAX_VALUE);
System.out.println(Double.MAX_VALUE);
  • double data type is a double-precision 64-bit IEEE 754 floating point (digits of precision could be between 15 to 17 decimal digits).
  • float data type is a single-precision 32-bit IEEE 754 floating point (digits of precision could be between 6 to 9 decimal digits).

After running the code above, if you're not satisfied with their ranges than I would recommend using BigDecimal as this type doesn't have a limit (rather your RAM is the limit).