Skip to content

Instantly share code, notes, and snippets.

@brandanmajeske
Created January 6, 2015 20:26
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 brandanmajeske/e2fcb37af1e314629ce5 to your computer and use it in GitHub Desktop.
Save brandanmajeske/e2fcb37af1e314629ce5 to your computer and use it in GitHub Desktop.
Gaussian/Banker's Rounding
/**
* 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