Double precision of “= =” operator in Java

This method returns' true ' Why?

public static boolean f() {
   double val = Double.MAX_VALUE/10;
   double save = val;
   for (int i = 1; i < 1000; i++) {
       val -= i;
   }
   return (val == save);
}

Solution

You subtract a fairly small value (less than 1000) from a huge value The small value is much smaller than the nearest representable value of the theoretical result, and it is still the large value of the original value

Basically, this is the result of the way floating - point numbers work

Imagine that we have some decimal floating-point types (just for simplicity) that store only five significant digits in the mantissa and range from 0 to 1000

Your example is like writing 10999 – 1000... Think about the result when rounded to 5 significant numbers Yes, the exact result is 99999 9000 (999 digits), but if it can only represent the value of 5 significant digits, the closest result is 10999

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>