Ceil function: how can we implement it ourselves?

TimeToCodeTheRoad picture TimeToCodeTheRoad · Dec 4, 2011 · Viewed 28.5k times · Source

I know that C++ provides us with a ceil function. For practice, I was wondering how can we implement the ceil function in C++. The signature of the method is public static int ceil(float num)

Please provide some insight.

I thought of a simple way: Convert num to a string, find the index of the decimal point, check if the decimal part is greater than 0. If yes, return num+1 else return num. But I want to avoid using the string conversion

Answer

fredoverflow picture fredoverflow · Dec 4, 2011

You can take apart the ingredients of an IEEE754 floating point number and implement the logic yourself:

#include <cstring>

float my_ceil(float f)
{
    unsigned input;
    memcpy(&input, &f, 4);
    int exponent = ((input >> 23) & 255) - 127;
    if (exponent < 0) return (f > 0);
    // small numbers get rounded to 0 or 1, depending on their sign

    int fractional_bits = 23 - exponent;
    if (fractional_bits <= 0) return f;
    // numbers without fractional bits are mapped to themselves

    unsigned integral_mask = 0xffffffff << fractional_bits;
    unsigned output = input & integral_mask;
    // round the number down by masking out the fractional bits

    memcpy(&f, &output, 4);
    if (f > 0 && output != input) ++f;
    // positive numbers need to be rounded up, not down

    return f;
}

(Insert the usual "not portable" disclaimer here.)