java using float comparison will return wrong results -


class {     public final static float _eps = 1e-7f;     public final static double _eps2 = 1e-7;      public static boolean compare(float a, float b)     {         return < b + _eps;     }     public static boolean compare2(float a, float b)     {         return < b + _eps2;     }      public static void main(string [] main)     {         float = 54.124844f;         float b = 54.124844f;         system.out.println("compare 1: " + a.compare(a,  b) + " comapre 2: " + a.compare2(a, b));     } } 

i thought both of these 2 comparisons return true, but, a.compare return false. reason in mind because of range , precision difference between float , double type. however, seems number , eps used should within legal range. help.

this because 54.124844f + 1e-7f == 54.124844f. float doesn't have enough precision addition yield value different 54.124844f.

using math.nextafter(float, double) shows next larger value after 54.124844f 54.124847f. such, adding smaller increment won't change float.

the other 1 returns true because _eps2 double, b coerced double before addition. double have enough precision represent difference.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -