I would like to understand why
double nbr = 102262.5;
boost::format("%.0f") % nbr;
gives 102262
while round(102262.5)
gives 102263.0
If we take another example value 34087.5
boost::format("%.0f") % nbr
gives 34088
and round(34087.5)
gives the same 34088
Does it mean round implements a more sophisticated algorithm to ensure the nearest while format or printf does not?
There is a thing called "round half to even" or "round half to odd" (link).
This is a rule to reduce the bias of rounding errors and
boost::format
seems to implement such a strategy.
Essentially this is to round the tie-breaking cases (such as 1.5 or 2.5) up and down equally often in a deterministic way (depending on the number itself). If one would always round up or round down these cases all, a statistical bias could be introduced by rounding.
The latter is the more "classical" way of rounding which seems to be implemented by round
.
Note that the strategy implemented by boost::format
(round half to even) corresponds to the default rounding mode in the IEEE 754 standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With