I'm of the opinion that, as rounding is generally only for the purpose of
*displaying* a result, that the rounding operation should be delayed until
the last possible moment. Thus, in general, it's better to do all the adding
and other stuff and then round just prior to printing.

Look at it this way: rounding throws away information, specifically that
embodied in the digits that get rounded off. Computers can generally handle
all that information. It's only when they need to show it to *people* that
they need to dumb it down ;)
   
   Chuck

-----Original Message-----
From: Dan Sugalski [mailto:[EMAIL PROTECTED]
Sent: Monday, October 13, 2003 2:56 PM
To: Bill Stephenson
Cc: mac osx list
Subject: Re: Weird math...


On Mon, 13 Oct 2003, Bill Stephenson wrote:

> I've got a script that takes numbers similar to those below and then
rounds
> them and adds them together using code similar to what is below.
[snip]
> 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
>
> I'm no math wizard, so if someone could please take the time and tell what
> I'm missing here I would very much appreciate it!

Welcome to the wonderful world of inexact representations.

You're getting bitten by some fundamental issues with floating point
representations of numbers. Floating point fractions are base 2, so they
can't properly represent anything that's not base 2. (And, since our
decimal fractions are base 10, that can be a lot of 'em)

There's more explanation in the perl faq, along with some workarounds.

                                Dan

Reply via email to