I am trying to understand floating-point numbers more deeply. I know that binary (base 2) floating-point numbers cannot represent some decimal numbers exactly. But I am confused in this strange behavior of double in Java (in Java, double is a binary floating-point number data type).
I write this piece of Java code:
public void myTestMethod() {
double num;
double factor;
double compared;
double result1;
double result2;
String output;
num = 0.3;
factor = 10;
compared = 3;
//num * 10
result1 = num * factor;
//add 10 num, which is mathematically equal to num * 10
result2 = num + num + num + num + num + num + num + num + num + num;
output = "num: " + num + "\n";
output = output + "result1: " + result1 + "\n";
output = output + "result2: " + result2 + "\n";
if (result1 == compared) {
output = output + "result1 == compared\n";
} else {
output = output + "result1 != compared\n";
}
if (result2 == compared) {
output = output + "result2 == compared\n";
} else {
output = output + "result2 != compared\n";
}
System.out.print(output);
}
Running this method produces this output:
num: 0.3
result1: 3.0
result2: 2.9999999999999996
result1 == compared
result2 != compared
From what I know, the value of "factor" is exactly 10, and the value of "compared" is exactly 3, because these integers can be represented exactly by double. But maybe the value of "num" is a little different from 0.3.
Now I want to know:
Is the value of "num" 0.3 (exactly)?
If the value of "num" is 0.3, then, why is "result2 == compared" false?
If the value of "num" is not 0.3, then, why is its String output "0.3"? From what I know, binary floating-point numbers can always be represented exactly in decimal numbers. So, if the value of "num" is not 0.3, its String output should not be "0.3", but should be something like "0.300000000001".
If the value of "num" is not 0.3, then, why is "result1 == compared" true?
If the value of "num" is not 0.3, then, what is it?