Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be the epsilon value when performing double value equal comparison

Tags:

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;     } } 
like image 651
Cheok Yan Cheng Avatar asked Sep 16 '10 15:09

Cheok Yan Cheng


People also ask

What is a good value for epsilon?

The EPSILON property has a value of approximately 2.2204460492503130808472633361816E-16 , or 2-52.

What is the value of double Epsilon?

The value of this constant is 4.94065645841247e-324. Two apparently equivalent floating-point numbers might not compare equal because of differences in their least significant digits.

Can you use == to compare doubles?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

How do you compare double numbers?

To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.


1 Answers

I like (pseudo code, I don't do java)

bool fuzzyEquals(double a, double b) {     return abs(a - b) < eps * max(abs(a), abs(b)); } 

with epsilon being a few times the machine epsilon. Take 10^-12 if you don't know what to use.

This is quite problem dependant however. If the computations giving a and b are prone to roundoff error, or involve many operations, or are themselves within some (known) accuracy, you want to take a bigger epsilon.

Ths point is to use relative precision, not absolute.

like image 53
Alexandre C. Avatar answered Oct 08 '22 18:10

Alexandre C.