Lo que todo programador debería saber sobre aritmética de punto flotante
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

allow for user-supplied epsilon

+15 -6
+14 -4
content/errors/NearlyEqualsTest.java
··· 4 4 import org.junit.Test; 5 5 6 6 /** 7 - * Demonstrates a good method for comparing floating-point values 8 - * using an epsilon. Run via JUnit 4 7 + * Test suite to demonstrate a good method for comparing 8 + * floating-point values using an epsilon. Run via JUnit 4. 9 + * 10 + * Note: this function attempts a "one size fits all" solution. There 11 + * may be some edge cases for which it still produces unexpected results, 12 + * and some of the tests it was developed to pass probably specify behaviour 13 + * that is not appropriate for some applications. Before using it, make 14 + * sure it's appropriate for your application! 9 15 * 10 16 * From http://floating-point-gui.de 11 17 * ··· 13 19 */ 14 20 public class NearlyEqualsTest 15 21 { 16 - public static boolean nearlyEqual(float a, float b) 22 + public static boolean nearlyEqual(float a, float b, float epsilon) 17 23 { 18 - final float epsilon = 0.000001f; 19 24 final float absA = Math.abs(a); 20 25 final float absB = Math.abs(b); 21 26 final float diff = Math.abs(a-b); ··· 26 31 } else { // use relative error 27 32 return diff / (absA+absB) < epsilon; 28 33 } 34 + } 35 + 36 + public static boolean nearlyEqual(float a, float b) 37 + { 38 + return nearlyEqual(a, b, 0.000001f); 29 39 } 30 40 31 41 /** Regular large numbers - generally not problematic */
+1 -2
content/errors/comparison.html
··· 38 38 39 39 Also, 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: 40 40 41 - public static boolean nearlyEqual(float a, float b) 41 + public static boolean nearlyEqual(float a, float b, float epsilon) 42 42 { 43 - float epsilon = 0.000001f; 44 43 float absA = Math.abs(a); 45 44 float absB = Math.abs(b); 46 45 float diff = Math.abs(a-b);