Here is the output for the below program.
value is : 2.7755575615628914E-17
Double.compare with zero : 1
isEqual with zero : true
My question is, what should be an epsilon value? Is there any robust way to obtain the value, instead of picking a number out from the sky.
package sandbox;
/**
*
* @author yccheok
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double zero = 1.0/5.0 + 1.0/5.0 - 1.0/10.0 - 1.0/10.0 - 1.0/10.0 - 1.0/10.0;
System.out.println("value is : " + zero);
System.out.println("Double.compare with zero : " + Double.compare(zero, 0.0));
System.out.println("isEqual with zero : " + isEqual(zero, 0.0));
}
public static boolean isEqual(double d0, double d1) {
final double epsilon = 0.0000001;
return d0 == d1 ? true : Math.abs(d0 - d1) < epsilon;
}
}
The answer to your second question is no. The magnitude of finite-machine precision error can be arbitrarily large:
This gives
~5.55E-12, but if you increaseNyou can get just about any level of error you desire.There is a vast amount of past and current research on how to write numerically stable algorithms. It is a hard problem.