8

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)
samuelschaefer
  • 614
  • 2
  • 10
  • 26
  • 9
    Not a reliable method. Consider the case where `test` is an integer value, such as `4.0`. In this case, `floor(x) == ceil(x)`, but your code would return `up = 5; down = 4`. – njuffa Feb 02 '15 at 20:29
  • 1
    Are you sure it's quicker? Show us your performance test! – Sulthan Feb 02 '15 at 20:46
  • Depends on what you mean by "reliable". If "reliable" means "it will work", then, yes. But if you mean something more, like "it will always round down/up/nearest/to zero/etc...", then, no... Make sure to try your various methods on both positive and negative numbers, as well as those that might be outside the range of `int` to see what happens so you can select the "correct" method for your particular situation... Oh, and that should probably be `up = (int)(test + 0.5)` - think about it... – twalberg Feb 02 '15 at 20:46
  • If you don't care about older processors, compile with SSE4.1. Then `floor()` and `ceil()` won't be slow anymore. – Mysticial Feb 02 '15 at 21:18

1 Answers1

8

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

R Sahu
  • 204,454
  • 14
  • 159
  • 270