Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - maximum loss of precision in one double addition/subtraction

Is it possible to establish, even roughly, what the maximum precision loss would be when dealing with two double values in java (adding/subtracting)? Probably the worst case scenario is when two numbers cannot be represented exactly, and then an operation is performed on them, which results in a value that also cannot be represented exactly.

like image 389
Bober02 Avatar asked Nov 20 '12 10:11

Bober02


Video Answer


1 Answers

The worst case is that all precision can be lost. This can for example happen if the result is larger than the largest representable finite number. Then it will be stored as POSITIVE_INFINITY (or NEGATIVE_INFINITY).

Regarding your update, it can happen with addition.

double a = Double.MAX_VALUE;
System.out.println(a);
double b = a + a;
System.out.println(b);

Result:

1.7976931348623157E308
Infinity

See it online: ideone

In general the size of the representation error is relative to the size of your numbers.

like image 198
Mark Byers Avatar answered Sep 26 '22 01:09

Mark Byers