Search code examples
ccastingfloorceil

floor() and ceil() functions vs casting to integer in C


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.

  1. 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)?
  2. 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)

Solution

  • The functions ceil() and floor() will return different numbers than what you get by using

    up = (int)(test + 1);
    down  = (int)test;
    

    when you have a negative number.

    If you have:

    float test = -1.3548;
    up = (int)test;        // ceil()
    down = (int)(test-1);  // floor()
    

    Even the last statement is not a good way to compute floor() when test is an integral number.

    Unless you want to deal with positive and negative numbers differently, and the special cases of when test is integral number, you are better off using ceil() and floor().