[Qt-interest] strange qFuzzyCompare implementation
Thiago Macieira
thiago.macieira at trolltech.com
Sun Apr 12 18:42:33 CEST 2009
Peter Radagast wrote:
>Hello!
>I think all of us got used to high quality of the Qt design and
> implementation. And I was very disappointed, when I saw the
> qFuzzyCompare implementation:
That's because you didn't understand the purpose behind those functions.
>static inline bool qFuzzyCompare(double p1, double p2)
>{
> return (qAbs(p1 - p2) <= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));
>}
>
>static inline bool qFuzzyCompare(float p1, float p2)
>{
> return (qAbs(p1 - p2) <= 0.00001f * qMin(qAbs(p1), qAbs(p2)));
>}
>
>Do you consider these hard-coded numbers etc effective, precise and
> portable?
Yes. They work fine for the intent that these functions are meant to have.
> I supposed to see smth like:
>static inline bool qFuzzyCompare(double p1, double p2)
>{
> return (qAbs(p1 - p2) <= std::numeric_limits::epsilon<double>());
>}
That would have the opposite effect of what is wanted. And it would not
work.
For one thing, no two numbers can have a difference that is smaller than
epsilon / order of magnitude. They can either be equal (exactly), differ by
one epsilon/order of magnitude or more. Remember that epsilon is the
smallest number that, added to 1, makes it different from 1. But if you had
1e-9 instead of 1, you the difference would be epsilon * 1e-9. Even if you
took the order of magnitude into consideration in your function, it would
compare only if the two numbers are exactly equal or differ by the smallest
unit that they could differ by.
Like I said, that's not the intent of the function. The intent of the
function is to verify if the two numbers are sufficiently close that they
should be considered equal for the code in question. The problem is that
the many floating point operations accumulate rounding errors: the more
operations you make, the greater that error is. It's definitely greater
than one epsilon.
So your code would definitely not work.
We could have chosen to make the code compare to a multiple of epsilons
(like 1000 epsilon), but instead we chose to make our lives easier and
just write a very small number.
--
Thiago Macieira - thiago.macieira (AT) nokia.com
Senior Product Manager - Nokia, Qt Software
Sandakerveien 116, NO-0402 Oslo, Norway
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090412/f7b5be0c/attachment.bin
More information about the Qt-interest-old
mailing list