Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::format gives different results than round

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?

like image 867
Bing Avatar asked Mar 09 '23 03:03

Bing


1 Answers

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.

like image 169
Andreas H. Avatar answered Mar 16 '23 01:03

Andreas H.