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.

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

In reply to Re^2: Floating Point Errors: How and Why to Avoid Adding and Subtracting Varying Numbers by Narveson
in thread Floating Point Errors by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.