Skip to content

Instantly share code, notes, and snippets.

@mitchwongho
Created October 16, 2015 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchwongho/8423e6cc8b47a4bbfa22 to your computer and use it in GitHub Desktop.
Save mitchwongho/8423e6cc8b47a4bbfa22 to your computer and use it in GitHub Desktop.
An example of comparing two double values with an epsilon.
/**
* 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
Copy link

How do you define EPSILON? Is it a constant?

@LsHallo
Copy link

LsHallo commented Mar 5, 2019

@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