I am writing some C code to repeatedly round floats up and down to integer values.
The standard C math library includes the functions floor()
and ceil()
.
I noticed that a much quicker implementation of the functions is to cast directly to integers:
int up, down;
float test = 1.3548;
up = (int)(test + 1); //ceil()
down = (int)test; //floor()
I did a quick check and this seems to work fine.
- Is this a reliable method to round up and down if I need the result to be an integer, as an array index (i.e. will it always return the correct results)?
- Is there a strong reason for the significant increase in speed? (on my system it runs about 3 times faster than the math.h implementation)