Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Rounding

0 views
Skip to first unread message

Todd Anderson

unread,
Mar 14, 2002, 2:15:00 PM3/14/02
to
Dear Sirs,
I have a number like 45.12737 and I need to round it up with 2 decimal
placesfor 45.13. Is there a perl command for this?
Any help is appreciated.

Josh Ghiloni

unread,
Mar 14, 2002, 2:21:46 PM3/14/02
to
> Dear Sirs,
> I have a number like 45.12737 and I need to round it up with 2 decimal
> placesfor 45.13. Is there a perl command for this?

2 choices that I can think of off the top of my head:
-- choice 1 (using int) --
my $n = 45.12737;
$n = int($n * 100) / 100;

-- choice 2 (using substitution) --
my $n = 45.12737;
$n =~ s/(-?\d+\.?\d{0,2})\d*/\1/;

I'd choose the former, simply for readability purposes. Both, however,
seem to work equally well.

As for built in solutions, I can't think of one.
------------------------------------------------------------------
Josh Ghiloni - jo...@joshghiloni.net - http://www.joshghiloni.net/

Webmaster, WRUW-FM <http://www.wruw.org/>
Postmaster, The Geek Empire <http://www.thegeekempire.net/>

"My parents just came back from a planet where the dominant lifeform
had no bilateral symmetry, and all I got was this stupid F-Shirt."
------------------------------------------------------------------

Andrew Harton

unread,
Mar 14, 2002, 2:36:34 PM3/14/02
to
"Todd Anderson" <to...@MrNoItAll.com> wrote in message
news:3C90F6A8...@MrNoItAll.com...
sprintf is the command you want. Read about it in the perlfunc section of
the documentation.

To do what you want, try this;

$a = sprintf("%.2f", 45.12737);
print $a;

Andrew

--
$s="acehJklnoPrstu ";$_="4dbce078c32ae92a6e30152a";
split//;for(0..$#_){print substr($s,hex $_[$_],1);}


Uri Guttman

unread,
Mar 14, 2002, 2:52:04 PM3/14/02
to
>>>>> "JG" == Josh Ghiloni <jo...@joshghiloni.net> writes:

>> Dear Sirs,
>> I have a number like 45.12737 and I need to round it up with 2 decimal
>> placesfor 45.13. Is there a perl command for this?

JG> 2 choices that I can think of off the top of my head:
JG> -- choice 1 (using int) --
JG> my $n = 45.12737;
JG> $n = int($n * 100) / 100;

JG> -- choice 2 (using substitution) --
JG> my $n = 45.12737;
JG> $n =~ s/(-?\d+\.?\d{0,2})\d*/\1/;

the use of \1 in the replacement is deprecated. use $1.

do you realize those won't REALLY make the number have only 2 decimal
fraction digits? binary floats can't accurately represent most decimal
fractions. also they don't round, they truncate. to round you have to
add .5 scaled to the desired place and then truncate.

JG> I'd choose the former, simply for readability purposes. Both, however,
JG> seem to work equally well.

equally wrong. they don't round.

JG> As for built in solutions, I can't think of one.

and perl does rounding in sprintf.

uri

--
Uri Guttman ------ u...@stemsystems.com -------- http://www.stemsystems.com
-- Stem is an Open Source Network Development Toolkit and Application Suite -
----- Stem and Perl Development, Systems Architecture, Design and Coding ----
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org

Jürgen Exner

unread,
Mar 14, 2002, 2:16:02 PM3/14/02
to
"Todd Anderson" <to...@MrNoItAll.com> wrote in message
news:3C90F6A8...@MrNoItAll.com...
> I have a number like 45.12737 and I need to round it up with 2 decimal
> placesfor 45.13. Is there a perl command for this?

What happened when you ask Perl?
Please check "perldoc -q round"

jue


Jürgen Exner

unread,
Mar 14, 2002, 2:28:16 PM3/14/02
to
"Josh Ghiloni" <jo...@joshghiloni.net> wrote in message
news:Pine.NEB.4.43.020314...@jdg.STUDENT.cwru.edu...

> > Dear Sirs,
> > I have a number like 45.12737 and I need to round it up with 2 decimal
> > placesfor 45.13. Is there a perl command for this?
>
> 2 choices that I can think of off the top of my head:
> -- choice 1 (using int) --
> my $n = 45.12737;
> $n = int($n * 100) / 100;

This doesn't round, it simply cuts off after the second digit after the
decimal separator.

> -- choice 2 (using substitution) --
> my $n = 45.12737;
> $n =~ s/(-?\d+\.?\d{0,2})\d*/\1/;

Neither does this round.

> I'd choose the former, simply for readability purposes. Both, however,
> seem to work equally well.

Actually, none of them "work" (the OP asked for rounding, not for cutting
off).

> As for built in solutions, I can't think of one.

See "perldoc -f round"

Gregory Toomey

unread,
Mar 14, 2002, 4:47:06 PM3/14/02
to
"Andrew Harton" <andrew...@agilent.com> wrote in message
news:10161346...@cswreg.cos.agilent.com...

> sprintf is the command you want. Read about it in the perlfunc section of
> the documentation.
No, that's truncation, not rounding.

gtoomey


Martien Verbruggen

unread,
Mar 14, 2002, 4:59:44 PM3/14/02
to

No, it's rounding, not truncation.

$ perl -e 'printf "%.2f\n", 1.234'
1.23
$ perl -e 'printf "%.2f\n", 1.235'
1.24

There are of course issues with floating point arithmentic and rounding,
and they have all beed discussed in the past on this newsgroup, and
almost every other programming newsgroup I subscribe to.

Martien
--
|
Martien Verbruggen | The problem with sharks is that they are too
| large to get to the shallow end of the gene
| pool. -- Scott R. Godin

Andreas Kähäri

unread,
Mar 14, 2002, 6:50:08 PM3/14/02
to
Submitted by "Todd Anderson" to comp.lang.perl.misc:

What about some easy arithmetics?

$newval = int($oldval * 100 + 0.5)/100;

--
Andreas Kähäri (on a slow news feed)
----------------------------------------------------------------
NetBSD: En Vax i handen är bättre än tio på skroten.
http://www.netbsd.org/

Andreas Kähäri

unread,
Mar 14, 2002, 7:17:36 PM3/14/02
to
Submitted by "Josh Ghiloni" to comp.lang.perl.misc:

>> Dear Sirs,
>> I have a number like 45.12737 and I need to round it up with 2 decimal
>> placesfor 45.13. Is there a perl command for this?
>
> 2 choices that I can think of off the top of my head:
> -- choice 1 (using int) --
> my $n = 45.12737;
> $n = int($n * 100) / 100;
>
> -- choice 2 (using substitution) --
> my $n = 45.12737;
> $n =~ s/(-?\d+\.?\d{0,2})\d*/\1/;
>
> I'd choose the former, simply for readability purposes. Both, however,
> seem to work equally well.

Except for the rounding part...

Alexander Avtanski

unread,
Mar 14, 2002, 8:29:07 PM3/14/02
to

"Andreas Kähäri" <a...@freeshell.org.REMOVE> wrote in message
news:3c913730$1...@news.nwlink.com...

...

> What about some easy arithmetics?
>
> $newval = int($oldval * 100 + 0.5)/100;

This doesn't work correctly for negative numbers.

Regards,

- Alex

Mark Jason Dominus

unread,
Mar 15, 2002, 10:38:32 AM3/15/02
to
In article <x7lmcu3...@home.sysarch.com>,

Uri Guttman <u...@stemsystems.com> wrote:
>the use of \1 in the replacement is deprecated.

It is not.

Hope this helps.
--
Mark Jason Dominus m...@plover.com
Philadelphia Excursions Mailing List: http://www.plover.com/~mjd/excursions/

Uri Guttman

unread,
Mar 15, 2002, 1:33:00 PM3/15/02
to
>>>>> "MJD" == Mark Jason Dominus <m...@plover.com> writes:

MJD> In article <x7lmcu3...@home.sysarch.com>,


MJD> Uri Guttman <u...@stemsystems.com> wrote:
>> the use of \1 in the replacement is deprecated.

MJD> It is not.

from perlre:

The bracketing construct "( ... )" creates capture buffers.
To refer to the digit'th buffer use \<digit> within the
match. Outside the match use "$" instead of "\". (The
\<digit> notation works in certain circumstances outside the
match. See the warning below about \1 vs $1 for details.)
Referring back to another part of the match is called a
backreference.


Warning on \1 vs $1

Some people get too used to writing things like:

$pattern =~ s/(\W)/\\\1/g;

This is grandfathered for the RHS of a substitute to avoid
shocking the sed addicts, but it's a dirty habit to get
into. That's because in PerlThink, the righthand side of a
"s///" is a double-quoted string. "\1" in the usual double-
quoted string means a control-A. The customary Unix meaning
of "\1" is kludged in for "s///". However, if you get into
the habit of doing that, you get yourself into trouble if
you then add an "/e" modifier.

s/(\d+)/ \1 + 1 /eg; # causes warning under -w


from perlop


It is at this step that "\1" is begrudgingly
converted to "$1" in the replacement text of "s///"
to correct the incorrigible sed hackers who haven't
picked up the saner idiom yet. A warning is emitted
if the "use warnings" pragma or the -w command-line
flag (that is, the "$^W" variable) was set.


calling its use a dirty habit and the meaning change a kludge is pretty
close to deprecation in my book. generating warnings is also a bad sign.

perl -wne 's/(..)/\1foo/'
\1 better written as $1 at -e line 1.

how much more is needed to be done before that is called deprecated?

Mike Stok

unread,
Mar 15, 2002, 1:48:45 PM3/15/02
to
In article <x7zo19n...@home.sysarch.com>, Uri Guttman wrote:

> Warning on \1 vs $1
>
> Some people get too used to writing things like:
>
> $pattern =~ s/(\W)/\\\1/g;
>
> This is grandfathered for the RHS of a substitute to avoid

^^^^^^^^^^^^^


> shocking the sed addicts, but it's a dirty habit to get
> into. That's because in PerlThink, the righthand side of a
> "s///" is a double-quoted string. "\1" in the usual double-
> quoted string means a control-A. The customary Unix meaning
> of "\1" is kludged in for "s///". However, if you get into
> the habit of doing that, you get yourself into trouble if
> you then add an "/e" modifier.

[...]

>
> calling its use a dirty habit and the meaning change a kludge is pretty
> close to deprecation in my book. generating warnings is also a bad sign.

[...]

> how much more is needed to be done before that is called deprecated?

For the docs to say deprecated rather than grandfathered! Grandfathering
has a fairly common meaning outside of familial relations, and as I see
it this means that \1 in the RHS is here to stay regardless of whether
it would have been done that way with the benefit of hindsight.

Mike

--
mi...@stok.co.uk | The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA
mi...@starnix.com | Fingerprint 0570 71CD 6790 7C28 3D60
http://www.starnix.com/ | 75D2 9EC4 C1C0 0599 13DA

Keith Keller

unread,
Mar 15, 2002, 1:51:37 PM3/15/02
to
In article <x7zo19n...@home.sysarch.com>,
Uri Guttman <u...@stemsystems.com> writes:

> perl -wne 's/(..)/\1foo/'
> \1 better written as $1 at -e line 1.

The long warning (from my Camel) is like so:

<quote>
Outside of patterns, backreferences live on as variables. The use of
backslashes is grandfathered on the righthand side of a substitution, but
stylistically it's better to use the variable form because other Perl
programmers will expect it, and it works better if there are more than
nine backreferences.
</quote>

> how much more is needed to be done before that is called deprecated?

Larry and Friends may not want to call it deprecated so as not to
frighten avid sed users. Perhaps they'll do it in 5.8 or in 6?
(But anything that's been grandfathered means deprecated to me.)

--keith

--
kke...@speakeasy.net
public key: http://wombat.san-francisco.ca.us/kkeller/public_key
alt.os.linux.slackware FAQ: http://wombat.san-francisco.ca.us/perl/fom

Uri Guttman

unread,
Mar 15, 2002, 1:52:48 PM3/15/02
to
>>>>> "MS" == Mike Stok <mi...@stok.co.uk> writes:

>> how much more is needed to be done before that is called deprecated?

MS> For the docs to say deprecated rather than grandfathered!
MS> Grandfathering has a fairly common meaning outside of familial
MS> relations, and as I see it this means that \1 in the RHS is here
MS> to stay regardless of whether it would have been done that way
MS> with the benefit of hindsight.

i would say that issuing a warning now is on the path to deprecation and
should be called that. it WAS grandfathered but sed is not so much in
the vocabulary of most perl users any more (e.g. winblows). i can't
recall the last time i used sed and i used to use it a fair amount. and
i wouldn't say it is here to stay if it has a compile time warning.

Joe Schaefer

unread,
Mar 15, 2002, 3:14:03 PM3/15/02
to
Uri Guttman <u...@stemsystems.com> writes:

> >>>>> "MS" == Mike Stok <mi...@stok.co.uk> writes:
>
> >> how much more is needed to be done before that is called deprecated?
>
> MS> For the docs to say deprecated rather than grandfathered!
> MS> Grandfathering has a fairly common meaning outside of familial
> MS> relations, and as I see it this means that \1 in the RHS is here
> MS> to stay regardless of whether it would have been done that way
> MS> with the benefit of hindsight.
>
> i would say that issuing a warning now is on the path to deprecation and
> should be called that. it WAS grandfathered but sed is not so much in
> the vocabulary of most perl users any more (e.g. winblows). i can't
> recall the last time i used sed and i used to use it a fair amount. and
> i wouldn't say it is here to stay if it has a compile time warning.

From the Jargon File:

deprecated

Said of a program or feature that is considered obsolescent and in the
process of being phased out, usually in favour of a specified
replacement. Deprecated features can, unfortunately, linger on for
many years. This term appears with distressing frequency in standards
documents when the committees writing the documents realise that large
amounts of extant (and presumably happily working) code depend
on the feature(s) that have passed out of favour.


Based on the discussion so far I agree with mjd's view. Using
backwhacks in the replacement text has not been phased out by p5p,
it's not being "replaced" by some other feature, and AFAIK
there are no plans to provide the "normal" semantics for "\1"
(i.e. "\001") in the replacement string- this is what I would
take "deprecated" to mean in this context.

A word like "discouraged" would IMO make a better description.

--
Joe Schaefer "Whoever undertakes to set himself up as a judge of Truth and
Knowledge is shipwrecked by the laughter of the gods."
--Albert Einstein

Mark Jason Dominus

unread,
Mar 15, 2002, 5:24:01 PM3/15/02
to
In article <prft6a...@wombat.san-francisco.ca.us>,

Keith Keller <kke...@speakeasy.net> wrote:
>Larry and Friends may not want to call it deprecated so as not to
>frighten avid sed users.

Oh yeah, we might scare off the hordes of avid sed users. I wonder
where those folks are hiding these days?

> Perhaps they'll do it in 5.8 or in 6?

It sure isn't going to be 'deprecated' in 5.8.

I doubt very much it'll be deprecated in Perl 6 either---it might be
*gone*, but it won't be deprecated.

>(But anything that's been grandfathered means deprecated to me.)

Perhaps a trip to the dictionary would help you with that problem.

Mark Jason Dominus

unread,
Mar 15, 2002, 5:42:38 PM3/15/02
to
In article <x7zo19n...@home.sysarch.com>,

Uri Guttman <u...@stemsystems.com> wrote:
>how much more is needed to be done before that is called deprecated?

There needs to be agreement that support for the feature may be
withdrawn in a future version of Perl 5, and a warning in the manual
to that effect.

For example, use of pseudohashes will be deprecated in Perl 5.8, and
the plan is to withdraw support for them in 5.10. Use of
unbackslashed literal "@" in double-quoted strings was deprecated in
5.000, and eventually removed.

John W. Krahn

unread,
Mar 16, 2002, 7:14:54 AM3/16/02
to
Mark Jason Dominus wrote:
>
> In article <prft6a...@wombat.san-francisco.ca.us>,
> Keith Keller <kke...@speakeasy.net> wrote:
> >Larry and Friends may not want to call it deprecated so as not to
> >frighten avid sed users.
>
> Oh yeah, we might scare off the hordes of avid sed users. I wonder
> where those folks are hiding these days?

comp.unix.shell apparently. :-)


John
--
use Perl;
program
fulfillment

Ron Savage

unread,
Mar 16, 2002, 6:28:33 PM3/16/02
to
Todd

See below.

--
Cheers
Ron Savage
r...@savage.net.au
http://savage.net.au/index.html


"Andrew Harton" <andrew...@agilent.com> wrote in message news:10161346...@cswreg.cos.agilent.com...

> "Todd Anderson" <to...@MrNoItAll.com> wrote in message
> news:3C90F6A8...@MrNoItAll.com...
> > Dear Sirs,
> > I have a number like 45.12737 and I need to round it up with 2 decimal
> > placesfor 45.13. Is there a perl command for this?
> > Any help is appreciated.
> >
> sprintf is the command you want. Read about it in the perlfunc section of
> the documentation.
>
> To do what you want, try this;
>
> $a = sprintf("%.2f", 45.12737);
> print $a;

Study sprintf carefully before thinking you understand it...

-----><8-----
#!/perl/lib/perl

use strict;
use warnings;

# ---------------------------------------------------------------

print sprintf("Perl V %vd. \n", $^V);

for my $i (0.555, 1.555, 0.565, 1.565, 0.575, 1.575)
{
print "$i => ", sprintf("%.2f. \n", $i);
}
-----><8-----


Falk Friedrich

unread,
Mar 17, 2002, 3:40:00 AM3/17/02
to
Alexander Avtanski (avta...@ispwest.com) wrote:

>"Andreas Kähäri" <a...@freeshell.org.REMOVE> wrote in message
>news:3c913730$1...@news.nwlink.com...
>

>> $newval = int($oldval * 100 + 0.5)/100;
>
>This doesn't work correctly for negative numbers.

$newval = ($oldval<=>0)*int(abs($oldval) * 100 + 0.5)/100;

-Falk

Bart Lateur

unread,
Mar 17, 2002, 7:03:04 AM3/17/02
to
Falk Friedrich wrote:

$newval = int($oldval * 100 + ($oldval<=>0)/2 )/100;

--
Bart.

Chris Eustace

unread,
Mar 17, 2002, 6:41:15 PM3/17/02
to
"Ron Savage" <r...@savage.net.au> wrote in message
news:UAQk8.3424$523.2...@ozemail.com.au...

> Todd
>
> See below.
>
> --
> Cheers
> Ron Savage
> r...@savage.net.au
> http://savage.net.au/index.html
> "Andrew Harton" <andrew...@agilent.com> wrote in message
news:10161346...@cswreg.cos.agilent.com...
> > "Todd Anderson" <to...@MrNoItAll.com> wrote in message
> > news:3C90F6A8...@MrNoItAll.com...
> Study sprintf carefully before thinking you understand it...
>
> -----><8-----
> #!/perl/lib/perl
>
> use strict;
> use warnings;
>
> # ---------------------------------------------------------------
>
> print sprintf("Perl V %vd. \n", $^V);
>
> for my $i (0.555, 1.555, 0.565, 1.565, 0.575, 1.575)
> {
> print "$i => ", sprintf("%.2f. \n", $i);
> }

The problem you are demonstrating has nothing to do with sprintf!
sprintf DOES round the floating point values passed to it (at least
non-negative ones).
The fact that the list of floats you passed to it cannot be exactly
represented in floating point format is the cause of the "strange" results.
It will not matter what rounding method you try and use to round the values
you have supplied!

--
Chris Eustace.


Mark Jason Dominus

unread,
Mar 17, 2002, 9:21:08 PM3/17/02
to
In article <3c95...@duster.adelaide.on.net>,

Chris Eustace <ceus...@austrics.com.au> wrote:
>> for my $i (0.555, 1.555, 0.565, 1.565, 0.575, 1.575)
>> {
>> print "$i => ", sprintf("%.2f. \n", $i);
>> }
>
>The problem you are demonstrating has nothing to do with sprintf!
>sprintf DOES round the floating point values passed to it (at least
>non-negative ones).
>
>The fact that the list of floats you passed to it cannot be exactly
>represented in floating point format is the cause of the "strange" results.
>It will not matter what rounding method you try and use to round the values
>you have supplied!

That's not the whole story, either. Look at this:

perl -le 'for $i (0.375, 0.625) { printf "%.2f\n", $i }'

On many systems (including mine), the output is

0.38
0.62

and it is *not* because of roundoff error or inexactness in the
floating-point representation; 0.375 and 0.625 are represented
exactly, with no error.

Chris Eustace

unread,
Mar 17, 2002, 9:58:38 PM3/17/02
to
"Mark Jason Dominus" <m...@plover.com> wrote in message
news:a73iuk$odt$1...@plover.com...

> In article <3c95...@duster.adelaide.on.net>,
> Chris Eustace <ceus...@austrics.com.au> wrote:
> That's not the whole story, either. Look at this:
>
> perl -le 'for $i (0.375, 0.625) { printf "%.2f\n", $i }'
>
> On many systems (including mine), the output is
>
> 0.38
> 0.62
>
> and it is *not* because of roundoff error or inexactness in the
> floating-point representation; 0.375 and 0.625 are represented
> exactly, with no error.

Well ... now I _am_ flabbergasted!!
However, on my Win32 box it does still give the "correct" response of 0.38
and 0.63.
--
Chris Eustace.

Mark Jason Dominus

unread,
Mar 17, 2002, 11:05:49 PM3/17/02
to
In article <3c95...@duster.adelaide.on.net>,
Chris Eustace <ceus...@austrics.com.au> wrote:
>> 0.38
>> 0.62
>>
>> and it is *not* because of roundoff error or inexactness in the
>> floating-point representation; 0.375 and 0.625 are represented
>> exactly, with no error.
>
>Well ... now I _am_ flabbergasted!!
>However, on my Win32 box it does still give the "correct" response of 0.38
>and 0.63.

If you always round up when the last figure is a five, you introduce
bias in the rounding, because you are rouning up more often than you
are rounding down. One strategy for combating this is to round fives
sometimes up, and sometimes down. One rule for doing this is to
always round a five toward the nearest even figure, so that 0.625 and
0.615 both round to 0.62, and 0.635 and 0.645 both round ot 0.64.

That is what is going on here.

Chris Eustace

unread,
Mar 17, 2002, 11:22:08 PM3/17/02
to
"Mark Jason Dominus" <m...@plover.com> wrote in message
news:a73p2t$pp1$1...@plover.com...
> In article <3c95...@duster.adelaide.on.net>,

> If you always round up when the last figure is a five, you introduce
> bias in the rounding, because you are rouning up more often than you
> are rounding down. One strategy for combating this is to round fives
> sometimes up, and sometimes down. One rule for doing this is to
> always round a five toward the nearest even figure, so that 0.625 and
> 0.615 both round to 0.62, and 0.635 and 0.645 both round ot 0.64.
>
> That is what is going on here.

I thought I'd been around the traps for quite a while .. but I have never
heard of that scheme of "rounding".
I did jump on to a Solaris machine and saw the behaviour you indicated.
Personally, I don't see why the bias needs to be avoided ... rounding is
rounding as far as I'm concerned but the implementation is quite evidently
in the C libraries from which Perl is built.
Even if it was an attempt to soothe some weirdo accounting constraints
(like - having the cents add up correctly) the code would still need to do
special checking to ensure correct summation for all cases!?

In any case, thanks for that!

Live and learn!!
--
Chris Eustace


David Squire

unread,
Mar 18, 2002, 12:01:47 AM3/18/02
to
Mark Jason Dominus wrote:

> If you always round up when the last figure is a five, you introduce
> bias in the rounding, because you are rouning up more often than you
> are rounding down.

I've never heard of this. Why is zero treated as a special case? I've always
thought that (0,1,2,3,4) go down, and (5,6,7,8,9) go up. Five of each, so no bias.
I am very happy to be enlightened on this one....

Cheers,

D.

Mark Jason Dominus

unread,
Mar 18, 2002, 2:35:52 AM3/18/02
to
In article <3C9574BB...@csse.monash.edu.au>,

David Squire <David....@csse.monash.edu.au> wrote:
>I've never heard of this. Why is zero treated as a special case?

It *is* a special case. Numbers with zeroes aren't rounded at all.

Or look at it this way: You expect each of the ten digits to appear
about as often as the others. So if you use the '5 alwayd rounds up'
technique, then you're doing this:

Digit Rounds to: Net change:
0 0 0
1 0 -1
2 0 -2
3 0 -3
4 0 -4
5 10 +5
6 10 +4
7 10 +3
8 10 +2
9 10 +1

Total: 45 50 +5

If you use the '5 always rounds up' technique, then you tend to
increase the samples by more than you decrease them.

For example, let's compute the average of 1000 random numbers.

$N = 1000;

for (1..$N) {
$n = int(rand 1000);
$n_rounded = 10*(int($n/10 + .5)); # round to nearest 10
$total += $n;
$total_rounded += $n_rounded;
}

$average = $total/$N;
$average_rounded = $total_rounded/$N;

print "The average of the numbers was $average.\n";
print "But the average of the rounded numbers was $average_rounded.\n";

It shouldn't matter that we round off the numbers before averaging
them. But it does. Typical output:

The average of the numbers was 521.477.
But the average of the rounded numbers was 521.95.

The rounding process tends to increase each number by about 0.5, on
average. So by rounding off the numbers before averaging, we've
biased the average, and it appears 0.5 larger than it actually is.

If we use the round-towards-even method, then we get results more like this:

The average of the numbers was 499.184.
But the average of the rounded numbers was 499.22.

Sometimes the rounded average is a little higher, sometimes a little
lower, rarely by as much as 0.5, and will tend to decrease as the
sample size increases. Here the error is only 0.036.

David Squire

unread,
Mar 18, 2002, 3:15:16 AM3/18/02
to
Mark Jason Dominus wrote:

> In article <3C9574BB...@csse.monash.edu.au>,
> David Squire <David....@csse.monash.edu.au> wrote:
> >I've never heard of this. Why is zero treated as a special case?
>
> It *is* a special case. Numbers with zeroes aren't rounded at all.
>

[snip excellent explanation]

Thanks very much!

Cheers,

D.

Mark Jason Dominus

unread,
Mar 18, 2002, 3:47:02 AM3/18/02
to
In article <3C95A214...@csse.monash.edu.au>,
David Squire <David....@csse.monash.edu.au> wrote:
>Thanks very much!
>

Any time.

Bart Lateur

unread,
Mar 18, 2002, 5:00:50 AM3/18/02
to
Mark Jason Dominus wrote:

>That's not the whole story, either. Look at this:
>
> perl -le 'for $i (0.375, 0.625) { printf "%.2f\n", $i }'
>
>On many systems (including mine), the output is
>
> 0.38
> 0.62
>
>and it is *not* because of roundoff error or inexactness in the
>floating-point representation; 0.375 and 0.625 are represented
>exactly, with no error.

Is it because of that awkward "round to nearest even" rule? You'll have
to multiply by 100 upfront and divide by 100 afterwards.

--
Bart.

Michael Carman

unread,
Mar 18, 2002, 9:07:04 AM3/18/02
to
Chris Eustace wrote:
> "Mark Jason Dominus" <m...@plover.com> wrote in message
> news:a73p2t$pp1$1...@plover.com...
>
>>In article <3c95...@duster.adelaide.on.net>,
>>If you always round up when the last figure is a five, you introduce
>>bias in the rounding, because you are rouning up more often than you
>>are rounding down. One strategy for combating this is to round fives
>>sometimes up, and sometimes down. One rule for doing this is to
>>always round a five toward the nearest even figure, so that 0.625 and
>>0.615 both round to 0.62, and 0.635 and 0.645 both round ot 0.64.
>
> I thought I'd been around the traps for quite a while .. but I have never
> heard of that scheme of "rounding".
> [...]

> Personally, I don't see why the bias needs to be avoided...
> [...]

> Even if it was an attempt to soothe some weirdo accounting constraints
> (like - having the cents add up correctly) the code would still need to do
> special checking to ensure correct summation for all cases!?

It's not the accountants, it's the scientists. They're picky about
significant digits too. To them, there's an important difference between
0.5 and 0.500 (the latter is 100 times more accurate). Rounding bias can
really screw up your calculations.

-mjc

Chris Eustace

unread,
Mar 18, 2002, 6:11:38 PM3/18/02
to
"Michael Carman" <mjca...@home.com> wrote in message
news:3C95F488...@home.com...

> Chris Eustace wrote:
> > "Mark Jason Dominus" <m...@plover.com> wrote in message
> > news:a73p2t$pp1$1...@plover.com...
> >
> >>In article <3c95...@duster.adelaide.on.net>,
> >>If you always round up when the last figure is a five, you introduce
> >>bias in the rounding, because you are rouning up more often than you
> >>are rounding down. One strategy for combating this is to round fives
> >>sometimes up, and sometimes down. One rule for doing this is to
> >>always round a five toward the nearest even figure, so that 0.625 and
> >>0.615 both round to 0.62, and 0.635 and 0.645 both round ot 0.64.
> >
> > Even if it was an attempt to soothe some weirdo accounting constraints
> > (like - having the cents add up correctly) the code would still need to
do
> > special checking to ensure correct summation for all cases!?
>
> It's not the accountants, it's the scientists. They're picky about
> significant digits too. To them, there's an important difference between
> 0.5 and 0.500 (the latter is 100 times more accurate). Rounding bias can
> really screw up your calculations.

Without wanting to extend this thread too far, I'm afraid I don't see how
rounding bias (with or without) affects significant figures greatly. It can
only affect the last digit to which you are rounding, and on computers it is
only going to happen for floating point numbers which can be exactly
represented by the IEEE(whatever) format. All other floating point numbers
already have their own "bias".

Let's say that 0.4995 can be exactly represented by computer (it can't in
reality) then rounding to the third decimal place will give 0.500 whether
the bias rounding method is used or not!

For 0.4985 (again assuming exact representation), the biased method will
give 0.498 where instead you might expect 0.499. So there is only variation
in the last place, and "scientists" should realise that a figure displayed
with significant figures is accurate only within 0.5 * (last place units).

For our example above:
0.498 plus or minus 0.0005
0.499 plus or minus 0.0005

So both forms "cover" the true value of 0.4985.

--
Chris Eustace.


Michael Carman

unread,
Mar 19, 2002, 11:49:18 AM3/19/02
to
Chris Eustace wrote:
>
> "Michael Carman" <mjca...@home.com> wrote in message
> news:3C95F488...@home.com...
>>
>>It's not the accountants, it's the scientists. They're picky about
>>significant digits too. To them, there's an important difference between
>>0.5 and 0.500 (the latter is 100 times more accurate). Rounding bias can
>>really screw up your calculations.
>
> Without wanting to extend this thread too far,

Agreed.

> I'm afraid I don't see how rounding bias (with or without) affects
> significant figures greatly.

Ah... I didn't say that. I didn't mean to imply it, either. I was
responding to the comment

I don't see why the bias needs to be avoided

by saying that for some people, the bias is important and can really
screw you up. The bit about significant digits was only an example of
another thing that people very concerned about accuracy care about that
most of us never consider.

> "scientists" should realise that a figure displayed with significant
> figures is accurate only within 0.5 * (last place units).

Actually, it's within +/- 1 of the least significant digit. e.g. a
measurement of 0.498 is considered to be accurate within +/- 0.001, not
0.0005. But this is all very OT.

-mjc

Alexander Avtanski

unread,
Mar 20, 2002, 3:36:40 PM3/20/02
to
Cool, :-)

Bart Lateur <bart....@pandora.be> wrote in message news:<nb199uk3hdot60bf6...@4ax.com>...

gamo <gamo@telecable.es>

unread,
Mar 21, 2002, 12:28:16 PM3/21/02
to
On Thu, 14 Mar 2002, Todd Anderson wrote:

> Dear Sirs,
> I have a number like 45.12737 and I need to round it up with 2 decimal
> placesfor 45.13. Is there a perl command for this?
> Any help is appreciated.
>

$a = 45.12737
$a += 0.000001
printf("%.2f",$a);
$b = sprintf("%.2f",$a);
print " $b";
Best regards,

--
#ga...@telecable.es; http://www.telecable.es/personales/gamo/
The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore all
progress depends on the unreasonable man. -- George Bernard Shaw

0 new messages