How does qFuzzyCompare work in Qt

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

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.

回答1:

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))); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!