Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGFloat: round, floor, abs, and 32/64 bit precision

TLDR: How do I call standard floating point code in a way that compiles both 32 and 64 bit CGFloats without warnings?


CGFloat is defined as either double or float, depending on the compiler settings and platform. I'm trying to write code that works well in both situations, without generating a lot of warnings.

When I use functions like floor, abs, ceil, and other simple floating point operations, I get warnings about values being truncated. For example:

warning: implicit conversion shortens 64-bit value into a 32-bit value

I'm not concerned about correctness or loss of precision in of calculations, as I realize that I could just use the double precision versions of all functions all of the time (floor instead of floorf, etc); however, I would have to tolerate these errors.

Is there a way to write code cleanly that supports both 32 bit and 64 bit floats without having to either use a lot of #ifdef __ LP64 __ 's, or write wrapper functions for all of the standard floating point functions?

like image 557
leecbaker Avatar asked Oct 08 '11 05:10

leecbaker


2 Answers

You may use those functions from tgmath.h.

#include <tgmath.h>

...

double d = 1.5;
double e = floor(d);   // will choose the 64-bit version of 'floor'

float f = 1.5f;
float g = floor(f);    // will choose the 32-bit version of 'floorf'.
like image 148
kennytm Avatar answered Sep 18 '22 21:09

kennytm


If you only need a few functions you can use this instead:

#if CGFLOAT_IS_DOUBLE
#define roundCGFloat(x) round(x)
#define floorCGFloat(x) floor(x)
#define ceilCGFloat(x) ceil(x)
#else
#define roundCGFloat(x) roundf(x)
#define floorCGFloat(x) floorf(x)
#define ceilCGFloat(x) ceilf(x)
#endif
like image 44
zeroimpl Avatar answered Sep 20 '22 21:09

zeroimpl