[Qt-interest] strange qFuzzyCompare implementation
Konrad Rosenbaum
konrad at silmor.de
Mon Apr 13 08:46:17 CEST 2009
On Monday 13 April 2009, Stephan Rose wrote:
> There actually is another way to do a float compare like this that does
> *not* rely on that type of hardcoded value.
>
> #define MaxError 5
But it relies on another type of hardcoded value.
> bool compareFloat(float p1, float p2)
> {
> int a, b;
> memcpy(&a, &p1, sizeof(float));
> memcpy(&b, &p2, sizeof(float));
>
> a = a < 0 ? 0x80000000 - a : a;
> b = b < 0 ? 0x80000000 - b : b;
>
> return qabs(a - b) <= MaxError;
> }
Your algorithm compares the absolutes of two numbers instead of the two
numbers and I'm not entirely sure whether its behaviour for negative
numbers is what you intended (floats encode the absolute plus sign, whereas
ints encode negatives as inverted bits).
I think your conversion of negatives should be
a &= 0x7fffffff;
Of course the rules for when to convert at all are difficult to find if you
want consistent results for large numbers and very small numbers close to
zero (esp. a very small negative and a very small positive number that
should compare to "sufficiently equal", while eg. -200 and +200 should
compare to "not equal").
> If there is no error, a-b = 0.
> The greater the error is the larger a-b will be. You simply set MaxError
> to what you want the greatest deviation in your code to be.
I wouldn't exactly call that "simply set MaxError", since it requires some
expertise to calculate a good starting point for your kind of calculation.
Konrad
--
Note: I'm changing my PGP/GPG key soon! New KeyID: 723A6200
Fingerprint: B37C FA75 8C4C 6537 7954 CBC0 CB15 C991 723A 6200
Keyserver: wwwkeys.eu.pgp.net
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090413/b781774a/attachment.bin
More information about the Qt-interest-old
mailing list