Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float comparison (equality) in CoreGraphics

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).

like image 663
kpower Avatar asked Nov 02 '11 04:11

kpower


People also ask

Is 1.5 float or double?

And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.

What is a float Swift?

Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.


1 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.

like image 177
justin Avatar answered Oct 15 '22 01:10

justin