Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is binary equality comparison of floats correct?

I'm working on different memory block manipulation functions and during benchmarks I noticed, that my implementation of the IsEqualRange(double* begin1, double* end1, double* begin2, double* end2) is much faster then the std::equals(...) on MSVC and GCC as well. Further investigation showed, that doubles and floats are not block compared by memcmp, but in a for loop one by one.

In what situation does binary comparison of floats lead to incorrect result? When is it ok to binary compare (equality) array of floats/doubles? Are there other fundamental types where I shouldn't use memcmp?

like image 257
Zoltan Tirinda Avatar asked Jan 03 '19 10:01

Zoltan Tirinda


People also ask

How reliable are floating point comparisons?

The floating point comparison is not similar to the integer comparison. To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Why do we never use == to compare floating point numbers?

Why does this problem occur? In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers.

Is it possible to compare floats for equality in Python?

How To Compare Floats in Python. If abs(a - b) is smaller than some percentage of the larger of a or b , then a is considered sufficiently close to b to be "equal" to b . This percentage is called the relative tolerance. You can specify the relative tolerance with the rel_tol keyword argument of math.

Can you compare floats and integers?

Assigning an integer to float and comparison in C/C++ The integer is a data type used to define a number that contains all positive, negative or zero non-fractional values. These cannot have decimals. Float is a data type used to define a number that has a fractional value. These can have decimals also.


2 Answers

The first thing I would do if I were you is to check your optimisation settings.

It's fine to use memcmp for an array of floating points but note that you could get different results to element-by-element ==. In particular, for IEEE754 floating point:

  1. +0.0 is defined to compare equal to -0.0.

  2. NaN is defined to compare not-equal to NaN.

like image 58
Bathsheba Avatar answered Sep 30 '22 04:09

Bathsheba


The main issue is nan values, as these are never equal to themselves. There is also two representations of 0 (+0 and -0) that are equal but not binary equal.

So strictly speaking, you cannot use memcmp for them, as the answer would be mathematically incorrect.

If you know that you don't have nan or 0 values, then you can use memcmp.

like image 23
Matthieu Brucher Avatar answered Sep 30 '22 03:09

Matthieu Brucher