Weird result returned from adding floats depending on order I add them

Grant Edwards grante at visi.com
Tue Feb 20 11:44:55 EST 2007


On 2007-02-20, John Machin <sjmachin at lexicon.net> wrote:
> On Feb 21, 2:05 am, Grant Edwards <gra... at visi.com> wrote:
>> On 2007-02-20, joanne matthews (RRes-Roth) <joanne.matth... at bbsrc.ac.uk> wrote:
>>
>> > I'm getting different results when I add up a list of floats depending
>> > on the order that I list the floats.
>
>>
>> Don't use floating point if you expect exact results.
>
> It's not the floating point that's the problem, it's the radix, in
> this case 2, not being able to express n/10 exactly. As the tutorial
> points out, radix-10 has problems representing n/3 (and n/7 and ...)
> exactly.

No matter what radix you choose, you're going to be able to
exactly represent 0% of the rational numbers within the range
of the representation.  Since you have no control over the FP
representation (and hence radix), and little control over input
values, the only sane thing to do is to write your code under
the assumption that FP can't represent any values exactly.

> Another take: Don't expect exact results.

Which is what I said.  :)

> If the input is exact to 1 or two decimal places, don't expect
> the sum to be exact to 15 or more decimal places.

In this case the input values have about 14 significant digits.
So does the output.  Unfortunately, the algorithm as written
requires an infinite number of significant digits.

-- 
Grant Edwards                   grante             Yow!  WHOA!! Ken and
                                  at               Barbie are having TOO
                               visi.com            MUCH FUN!! It must be the
                                                   NEGATIVE IONS!!



More information about the Python-list mailing list