In a message dated Mon, 13 Oct 2003, Bill Stephenson writes:
>     #!/usr/bin/perl -w
>     use strict;
>     my $item_1 = "1.655";
>     my $item_2 = "1.755";
>     my $rnd_1 = (sprintf qq~%.2f~, $item_1);
>     print "$rnd_1, $rnd_2";
>
> The code above prints this result (system 10.1.5, perl 5.6.0):
>
>     1.66, 1.75
>
> But shouldn't it be:
>
>     1.66, 1.76
>
> or:
>
>     1.65, 1.75

A side issue not mentioned (yet) here.  Because of the "..55" at the end
of both of your samples, it turns out to be irrelevant for your cases.
But, in general when doing statistical work, you round a number halfway
between what your rounding to by looking at the prior digit: even digits
down, an odd digits up.

So round(0.1, 1.75) = 1.8, but round(0.1, 1.65) = 1.6.  Note that you do
this only when the number is EXACTLY halfway; round(1.651) would be 1.7,
not 1.6, because you have an extra significant digit to tell you which
side is more appropriate to round towards.  This is the behavior of
round_even in the Math::Round CPAN module.

(This rounding behavior is not always appropriate.  If a ...5 is very
common in your data, and a bias towards numbers ending in even digits is
undesirable, you might round towards odd instead, or round randomly, as
round_odd and round_rand in Math::Round do.)

I most often use the nearest_rand function in Math::Round, as it
randomizes the halfway rounding and allows you to round to whatever place
(or multiple) you like.

Trey

Reply via email to