Geometry - Float comparison equality in CoreGraphics

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Apple CoreGraphics.framework, CGGeometry.h:

CG_INLINE bool __CGSizeEqualToSize(CGSize size1, CGSize size2)
{
    return size1.width == size2.width && size1.height == size2.height;
}
#define CGSizeEqualToSize __CGSizeEqualToSize

Why do they (Apple) compare floats with ==? I can t believe this is a mistake. So can you explain me? (I ve expected something like fabs(size1.width - size2.width) < 0.001).

Answers

Floating point comparisons are native width on all OSX and iOS architectures.

For float, that comes to:

  i386, x86_64:   
    • 32 bit XMM register (or memory for second operand)
    • using an instructions in the family of ucomiss
  ARM:   
    • 32 bit register
    • using instructions in the same family as vcmp

Some of the floating point comparison issues have been removed by restricting storage to 32/64 for these types. Other platforms may use the native 80 bit FPU often (example). On OS X, SSE instructions are favored, and they use natural widths. So, that reduces many of the floating point comparison issues.

But there is still room for error, or times when you will favor approximation. One hidden detail about CGGeometry types values is that they may be rounded to a nearby integer (you may want to do this yourself in some cases).

Given the range of CGFloat (float or double-x86_64) and typical values, it s reasonable to assume the rounded values generally be represented accurately enough, such that the results will be suitably comparable in the majority of cases. Therefore, it s "pretty safe", "pretty accurate", and "pretty fast" within those confines.

There are still times when you may prefer approximated comparisons in geometry calculations, but apple s implementation is what I d consider the closest to a reference implementation for the general purpose solution in this context.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/7975765/float-comparison-equality-in-coregraphics

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils