I am trying to understand double
a bit better. In the following code snippet min
and max
are double
:
double min = 3.472727272727276;
double max = 3.4727272727272767;
System.out.println(max - min);
System.out.println((max - min)/2);
double mid = min + ((max - min)/2);
if(min == mid) {
System.out.println("equal");
}
System.out.println(mid);
The first 2 print statements print:
4.440892098500626E-16
2.220446049250313E-16
Which basically is:
0.0000000000000004440892098500626
and 0.0000000000000002220446049250313
Then the conditional check is true
i.e. prints equal
and the last print is: 3.472727272727276
So from my understanding the (max - min)/2
gave a value that could be represented by a double.
What is not clear to me is what is happening during the addition.
- Is the addition creating a number that could not be represented by a double and leaves the original
min
as is by dropping of digits or is the number effectively considered as 0 before the addition actually happens or how exactly is this done? - Is the
min == mid
a valid check to detect such issues with doubles? I.e. with integer we can detect overflow/underflow by checking if the result is less that we started with. Is the equality check after doing an addition a sane/reasonable check to detect the equivalent problem withdouble
i.e. that the number added was not really enhanced due to rounding error (or what exactly is the actual term for this)?