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
?
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 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.
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.
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.
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:
+0.0 is defined to compare equal to -0.0.
NaN is defined to compare not-equal to NaN.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With