float comparison

Jonathan M Davis jmdavisProg at gmx.com
Sat Aug 25 01:36:35 PDT 2012


On Saturday, August 25, 2012 10:28:44 nocide wrote:
> unittest {
>      bool fuzzyCmp(float a, float b) {
>          return abs(a-b) < 0.000001f;
>      }
>      float len1 = sqrt(8.0f);
>      float len2 = sqrt(8.0f);
>      assert(len1 == len2);              // passes
>      assert(fuzzyCmp(len1,sqrt(8.0f))); // passes
>      assert(len1 == sqrt(8.0f));        // fails!!
> }
> 
> 
> The comparison of the float variable passes, but the comparison to the
> return value of the sqrt-function fails.?!

Comparing floating point numbers with == is almost always the wrong thing to 
do.

http://floating-point-gui.de/

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list