Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 478
samuelschaefer Avatar asked Feb 02 '15 20:02

samuelschaefer


1 Answers

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

like image 120
R Sahu Avatar answered Sep 30 '22 13:09

R Sahu