What should be the epsilon value when performing double value equal comparison
java
Solution
The answer to your second question is no. The magnitude of finite-machine precision error can be arbitrarily large:
public static void main(String[] args) {
double z = 0.0;
double x = 0.23;
double y = 1.0 / x;
int N = 50000;
for (int i = 0; i < N; i++) {
z += x * y - 1.0;
}
System.out.println("z should be zero, is " + z);
}
This gives `~5.55E-12`, but if you increase `N` you 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.
Problem
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; } } ```