Why do lots of (old) programs use floor(0.5 + input) instead of round(input)?

markzzz picture markzzz · Nov 15, 2017 · Viewed 14.6k times · Source

The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}

which outputs:

1
0

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?

Answer

haccks picture haccks · Nov 15, 2017

std::round is introduced in C++11. Before that, only std::floor was available so programmers were using it.