Please supply a rationale for better_average.
Update:I thought the code below would speak for itself, but here is my own rationale for posting it, and for questioning the better_average routine submitted above.
- The only difference between bad_average and better_average is that a division by a constant is moved inside the innermost loop.
- If this were handed to any of us as a homework problem in refactoring, would we not pull the division back out again?
- But numerical methods are for many of us an intimidating twilight zone in which paradoxical results hold true.
- Let us require at least one example in support of every numerical claim.
- I claim that better_average is worse than bad_average, and here follows my supporting example.
use strict;
use warnings;
sub bad_average {
my $acc = 0;
$acc += $_ for @_;
return $acc / @_;
}
sub better_average {
my $acc = 0;
$acc += $_/@_ for @_;
return $acc;
}
my @inputs = (1) x 65537; # 2**16 + 1
my $true_average = 1;
for my $adj (qw[bad better]) {
my $func = "${adj}_average";
no strict 'refs';
my $average = &$func( @inputs );
my $diff = $average - $true_average;
print
"Error using $func is ",
$diff? "a nonzero number near $diff" : 0,
"\n"
}
Your roundoff error may vary, but on my system I get
Error using bad_average is 0
Error using better_average is a nonzero number near 3.33066907387547e-
+015
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.