What is the difference between:
if( a == b )
and
if( qFuzzyCompare(a, b) )
given that the variables a and b are:
a = 1234.5678
b = 1234.5678
Note: I'm asking because I am having trouble comparing doubles in Qt and I want to understand how qFuzzyCompare
works.
The official documentation for qFuzzyCompare()
did not really explain why one would use this, but in general comparing floating point values is considered a bad practice because two seemingly identical floating point variables may be found to differ due to rounding errors. You may read more about this and other gotchas of floating point variables here.
When looking at source code for qFuzzyCompare()
for double and float respectively as shipped with Qt5.6.0
(Hold CTRL and click the function to see this in QtCreator
), it can be inferred that it tries to reduce the likelihood of inaccuracies to get in the way of an equality test:
Q_DECL_CONSTEXPR static inline bool qFuzzyCompare(double p1, double p2) Q_REQUIRED_RESULT Q_DECL_UNUSED;
Q_DECL_CONSTEXPR static inline bool qFuzzyCompare(double p1, double p2)
{
return (qAbs(p1 - p2) * 1000000000000. <= qMin(qAbs(p1), qAbs(p2)));
}
Q_DECL_CONSTEXPR static inline bool qFuzzyCompare(float p1, float p2) Q_REQUIRED_RESULT Q_DECL_UNUSED;
Q_DECL_CONSTEXPR static inline bool qFuzzyCompare(float p1, float p2)
{
return (qAbs(p1 - p2) * 100000.f <= qMin(qAbs(p1), qAbs(p2)));
}
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