[Development] Comparing two reals in Qt code

Sean Harmer sean.harmer at kdab.com
Thu Nov 29 15:53:21 CET 2012


On Thursday 29 November 2012 15:01:05 Dominik Holland wrote:
> Hi all,
> 
> last month i had some performance problems on a QML animation running on
> low end hardware (imx233).
> I debugged that problem and it was caused because of rounding errors
> during the comparison of two reals.
> 
> I fixed that problem by replacing the comparison by a qFuzzyCompare() in
> the Qt4 declarative source code.
> Afterwards i checked whether qt5 has the same problem... and it has
> exactly the same problem.
> 
> Now i pushed my patch to gerrit
> (https://codereview.qt-project.org/#change,40655) and looked again at
> the code
> for any other occurrences.
> 
> What i found is, that this happens in many places and it would be a
> really huge effort to change the code to compare the qreals in the right
> way.
> 
> Is this already a known problem and do you think that it is worth to try
> to fix the code ?

Also please be aware that qFuzzyCompare() is nto the right way to compare two 
arbitrary floating point values. If one of them is zero or close to zero the 
condition it tests for becomes impossible to satisfy.

Something along the lines of

fuzzyCompare(float p1, float p2)
{
    if (qFuzzyIsNull(p1))
        return qFuzzyIsNull(p2);
    else if (qFuzzyIsNull(p2))
        return false;
    else
        return qFuzzyCompare(p1, p2);
}

is slightly better but still not fantastic. Comparing two floats that we do 
not know a priori is actually very difficult

http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-
numbers-2012-edition/

I would love to see a better qFuzzyCompare() implementation in Qt but the 
existing one is used in so many places it would be a nightmare to introduce 
without unwanted side effects.

Cheers,

Sean

--
Dr Sean Harmer | sean.harmer at kdab.com | Senior Software Engineer
Klarälvdalens Datakonsult AB, a KDAB Group company
Tel. Sweden (HQ) +46-563-540090, USA +1-866-777-KDAB(5322)
KDAB - Qt Experts - Platform-independent software solutions



More information about the Development mailing list