I have been struggling to understand the concept of roundoff errors in Java with floating-point. While I understand that double is not supposed to be used for financial calculations, I don't understand why the 'd' variable does not come out to 0.0. How can I get this to print out the first println?
package zetcom;
public class floatingComparison {
public static void main(String[] args) {
double r = Math.sqrt(2);
double d = r * r - 2;
if (d == 0)
{
System.out.println("sqrt(2) squared minus 2 is 0");
}
else
{
System.out.println("sqrt(2) squared minus 2 is " + d);
}
}
}
Any explanation would be appreciated.