···44import org.junit.Test;
5566/**
77- * Demonstrates a good method for comparing floating-point values
88- * using an epsilon. Run via JUnit 4
77+ * Test suite to demonstrate a good method for comparing
88+ * floating-point values using an epsilon. Run via JUnit 4.
99+ *
1010+ * Note: this function attempts a "one size fits all" solution. There
1111+ * may be some edge cases for which it still produces unexpected results,
1212+ * and some of the tests it was developed to pass probably specify behaviour
1313+ * that is not appropriate for some applications. Before using it, make
1414+ * sure it's appropriate for your application!
915 *
1016 * From http://floating-point-gui.de
1117 *
···1319 */
1420public class NearlyEqualsTest
1521{
1616- public static boolean nearlyEqual(float a, float b)
2222+ public static boolean nearlyEqual(float a, float b, float epsilon)
1723 {
1818- final float epsilon = 0.000001f;
1924 final float absA = Math.abs(a);
2025 final float absB = Math.abs(b);
2126 final float diff = Math.abs(a-b);
···2631 } else { // use relative error
2732 return diff / (absA+absB) < epsilon;
2833 }
3434+ }
3535+3636+ public static boolean nearlyEqual(float a, float b)
3737+ {
3838+ return nearlyEqual(a, b, 0.000001f);
2939 }
30403141 /** Regular large numbers - generally not problematic */
+1-2
content/errors/comparison.html
···38383939Also, the result is not commutative (`nearlyEquals(a,b)` is not always the same as `nearlyEquals(b,a)`). To fix these problems, the code has to get a lot more complex, so we really need to put it into a function of its own:
40404141- public static boolean nearlyEqual(float a, float b)
4141+ public static boolean nearlyEqual(float a, float b, float epsilon)
4242 {
4343- float epsilon = 0.000001f;
4443 float absA = Math.abs(a);
4544 float absB = Math.abs(b);
4645 float diff = Math.abs(a-b);