[Development] Comparing two reals in Qt code

Thomas Senyk thomas.senyk at pelagicore.com
Thu Nov 29 16:50:55 CET 2012


On Thu, November 29, 2012 14:53:21 Sean Harmer wrote:
> 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.

I think it's not about mathematical correctness.
It's about deciding if something like width or height is updated or not.

So for those use-cases it's IMO enough to filter a lot/nearly all unnecessary 
updates out.

> 
> 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
> _______________________________________________
> Development mailing list
> Development at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/development



More information about the Development mailing list