Created
January 6, 2015 20:26
-
-
Save brandanmajeske/e2fcb37af1e314629ce5 to your computer and use it in GitHub Desktop.
Gaussian/Banker's Rounding
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
/** | |
* Gaussian rounding (aka Banker's rounding) is a method of statistically | |
* unbiased rounding. It ensures against bias when rounding at x.5 by | |
* rounding x.5 towards the nearest even number. Regular rounding has a | |
* built-in upwards bias. | |
*/ | |
function gaussianRound(x) { | |
var absolute = Math.abs(x); | |
var sign = x == 0 ? 0 : (x < 0 ? -1 : 1); | |
var floored = Math.floor(absolute); | |
if (absolute - floored != 0.5) { | |
return Math.round(absolute) * sign; | |
} | |
if (floored % 2 == 1) { | |
// Closest even is up. | |
return Math.ceil(absolute) * sign; | |
} | |
// Closest even is down. | |
return floored * sign; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment