Home > database >  C - ceil/float rounding to int guarantees
C - ceil/float rounding to int guarantees

Time:05-14

I'm wondering if there are any circumstances where code like this will be incorrect due to floating point inaccuracies:

#include <math.h>

// other code ...

float f = /* random but not NAN or INF */;

int i = (int)floorf(f);

// OR

int i = (int)ceilf(f);

Are there any guarantees about these values? If I have a well-formed f (not NAN or INF) will i always be the integer that it rounds to, whichever way that is.

I can image a situation where (with a bad spec/implementation) the value you get is the value just below the true value rather than just above/equal but is actually closer. Then when you truncate it actually rounds down to the next lower value.

It doesn't seem possible to me given that integers can be exact values in ieee754 floating point but I don't know if float is guaranteed to be that standard

CodePudding user response:

The C standard is sloppy in specifying floating-point behavior, so it is technically not completely specified that floorf(f) produces the correct floor of f or that ceilf(f) produces the correct ceiling of f.

Nonetheless, no C implementations I am aware of get this wrong.

If, instead of floorf(some variable), you have floorf(some expression), there are C implementations that may evaluate the expression in diverse ways that will not get the same result as if IEEE-754 arithmetic were used throughout.

If the C implementation defines __STDC_IEC_559__, it should evaluate the expressions using IEEE-754 arithmetic.

Nonetheless, int i = (int)floorf(f); is of course not guaranteed to set i to the floor of f if the floor of f is out of range of int.

  • Related