Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created August 17, 2018 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashwin/733f1a755675617bb63d70db8c3cc1c2 to your computer and use it in GitHub Desktop.
Save ashwin/733f1a755675617bb63d70db8c3cc1c2 to your computer and use it in GitHub Desktop.
Round half to even implementation for float
#include <array>
#include <cmath>
#include <iostream>
float roundHalfToEven(float f)
{
const float r = round(f); // Result is round-half-away-from-zero
const float d = r - f; // Difference
// Result is not half, RHAFZ result same as RHTE
if ((d != 0.5f) && (d != -0.5f))
{
return r;
}
// Check if RHAFZ result is even, then RHAFZ result same as RHTE
if (fmod(r, 2.0f) == 0.0f)
{
return r;
}
// Switch to even value
return f - d;
}
int main()
{
const std::array<float, 8> fvals {{-5.5, -4.5, -3.5, -0.5, 0.5, 3.5, 4.5, 5.5}};
for (float f : fvals)
{
const float r = roundHalfToEven(f);
std::cout << "roundHalfToEven(" << f << "): " << r << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment