Gaussian/Banker's Rounding
Join the DZone community and get the full member experience.
Join For FreeGaussian rounding (aka Banker's rounding) rounds numbers in such a way as there is no upwards bias when rounding x.5. This minimises cumulative error in summing, averaging, &c. rounded numbers.
/**
* 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;
}
Thanks to Dennis W Jay for pointing out a bug in the code.
Opinions expressed by DZone contributors are their own.
Comments