Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximal integer value for double

Tags:

java

double

That is the maximal integer value could be assigned to Java double and still behave as an integer value? I mean, it sill must satisfy the usual conditions

a + 1 > a;
a - 1 < a;

With the values big enough, even a + 1000 may still be a due rounding errors.

I need to use double as a counter and want to know where is the upper limit of the reliable counting.

like image 916
Audrius Meškauskas Avatar asked Jan 12 '23 19:01

Audrius Meškauskas


1 Answers

The number that you're looking for is 9,007,199,254,740,991 because 9,007,199,254,740,991 + 1 = 9,007,199,254,740,992 but 9,007,199,254,740,992 + 1 = 9,007,199,254,740,992.

I found this experimentally using the following snippet.

double a = 9.007199254E15;
while (a + 1 > a) {
    a += 1;
}
System.out.println(a);

Given the fact that you are using this value as a counter, and that the maximum value for longs is 2^63 - 1 = 9.22E18 (as Peter pointed out), there seems to be no reason not to use longs instead.

like image 178
wheels Avatar answered Jan 22 '23 05:01

wheels