Created
October 16, 2015 11:01
-
-
Save mitchwongho/8423e6cc8b47a4bbfa22 to your computer and use it in GitHub Desktop.
An example of comparing two double values with an epsilon.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Compare two {@code double} values | |
* @param a some <i>double</i> value | |
* @param b some other <i>double</i> value | |
* @return {@code true} if the two values are equal | |
*/ | |
public static boolean equals (final double a, final double b) { | |
if (a==b) return true; | |
return Math.abs(a - b) < EPSILON; //EPSILON = 0.0000001d | |
} | |
/** | |
* Compare {@code a} and {@code b} | |
* @param a some <i>double</i> value | |
* @param b some other <i>double</i> value | |
* @return a negative value if {@code a} is smaller than {@code b}, | |
* a positive value if {@code a} is larger than {@code b}, else {code 0}. | |
*/ | |
public static int compare (final double a, final double b) { | |
return equals(a, b) ? 0 : (a < b) ? -1 : +1; | |
} |
@chaoyangnz
Yes epsilon is a constant. See it as a error margin. If the two values are within EPSILON they are considered the same.
Example:
3.5 and 3.6 with EPSILON 0.05 are NOT considered EQUAL [abs(3.5-3.6) < 0.05]
3.5 and 3.6 with EPSILON 0.15 are considered EQUAL [abs(3.5-3.6) < 0.15]
2 years later you got a reply. Wohooo :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you define EPSILON? Is it a constant?