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.

use abs

+4 -4
+4 -4
content/errors/comparison.html
··· 15 15 very small. The error margin that the difference is compared to is often called *epsilon*. 16 16 The most simple form: 17 17 18 - if( a-b < 0.00001) // wrong - don't do this 18 + if( Math.abs(a-b) < 0.00001) // wrong - don't do this 19 19 20 20 This is a bad way to do it because a fixed epsilon chosen because it "looks small" could actually be way too 21 21 large when the numbers being compared are very small as well. The comparison would return "true" for numbers that are quite different. And when the numbers are very large, the epsilon 22 22 could end up being smaller than the smallest rounding error, so that the comparison always returns "false". 23 23 Therefore, it is necessary to see whether the *relative error* is smaller than epsilon: 24 24 25 - if( (a-b)/b < 0.00001 ) // still not right! 25 + if( Math.abs((a-b)/b) < 0.00001 ) // still not right! 26 26 27 27 There is one important special case where this will fail: When both a and be are zero. 0.0/0.0 is "not a number", which returns false for all comparisons. So we have to take care of that first: 28 28 29 - if( a==b || (a-b)/b < 0.00001 ) // more correct, but bad design 29 + if( a==b || Math.abs((a-b)/b) < 0.00001 ) // more correct, but bad design 30 30 31 31 Since it's not immediately clear what this code does, it should be done in a function or method: 32 32 33 33 function nearlyEqual(a,b) 34 34 { 35 - return a==b || (a-b)/b < 0.00001; 35 + return a==b || Math.abs((a-b)/b) < 0.00001; 36 36 } 37 37 38 38 if(nearlyEqual(a,b))