Created
August 17, 2018 05:27
-
-
Save ashwin/733f1a755675617bb63d70db8c3cc1c2 to your computer and use it in GitHub Desktop.
Round half to even implementation for float
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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