I want to round a double to the nearest integer and round to even in halfway cases. Per documentation std::nearbyintf
should do this:
If the current rounding mode is FE_TONEAREST, this function rounds to even in halfway cases (like std::rint, but unlike std::round).
Another function that does this is std::rintf
. The docs of std::rintf
state:
The only difference between std::nearbyint and std::rint is that std::nearbyint never raises FE_INEXACT.
So, I did expect the same results for both functions, but they return different results for double x = 3.4999999
.
The following reprex demonstrates this:
#include <iostream>
#include <iomanip>
#include <cfenv>
#include <cmath>
int main() {
std::fesetround(FE_TONEAREST);
std::cout << std::setprecision(15)
<< " std::nearbyintf(3.5) = " << std::nearbyintf(3.5) << "n"
<< " std::rint(3.5) = " << std::rint(3.5) << std::endl;
std::cout << std::setprecision(15)
<< " std::nearbyintf(2.5) = " << std::nearbyintf(2.5) << "n"
<< " std::rint(2.5) = " << std::rint(2.5) << std::endl;
std::cout << std::setprecision(15)
<< " std::nearbyintf(3.4999999) = " << std::nearbyintf(3.4999999) << "n"
<< " std::rintf(3.4999999) = " << std::rint(3.4999999) << std::endl;
return 0;
}
This example can be run here and produces the following output:
std::nearbyintf(3.5) = 4
std::rint(3.5) = 4
std::nearbyintf(2.5) = 2
std::rint(2.5) = 2
std::nearbyintf(3.4999999) = 4
std::rintf(3.4999999) = 3
Any advice on why they differ would be greatly appreciated.
7