Java floating-point value round-off errors

Question

What is the output of the following code?



public class Main {
  public static void main(String[] args) {
    System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); 
    System.out.println(1.0 - 0.9); 
  }
}


0.5000000000000001
0.09999999999999998

Note

A round-off error is called a rounding error.

There is a difference between the calculated floating-point approximation and its exact mathematical value.

Since the number of digits that can be stored in a variable is limited, round-off errors are inevitable.

Calculations involving floating-point numbers are approximated since these numbers are not stored with complete accuracy.

For example,

System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); 

displays 0.5000000000000001, not 0.5, and

System.out.println(1.0 - 0.9); 

displays 0.09999999999999998, not 0.1.

Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.




PreviousNext

Related