sum accuracy

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Apr 15 09:49:19 EDT 2016


On 15 April 2016 at 11:10, Ben Bacarisse <ben.usenet at bsb.me.uk> wrote:
> Oscar Benjamin <oscar.j.benjamin at gmail.com> writes:
>
>> On 15 April 2016 at 10:24, Robin Becker <robin at reportlab.com> wrote:
> <snip>
>>> yes indeed summation is hard :(
>>
>> Not with Fraction it isn't:
>>
>> from fractions import Fraction
>>
>> def exact_sum(nums):
>>     return sum(map(Fraction, nums))
>>
>> This will give you the exact result with precisely zero rounding
>> error. You can convert it to float at the end.
>
> Just a word of warning for people new to numerical work: there's no
> rounding error, but unless you start with Fraction objects you still
> have input or conversion errors.

There are no conversion errors in the Fraction constructor. This will
exactly sum any combination of int/float/Fraction/Decimal without
errors. (It will raise ValueError on nan/inf but I consider that a
good thing).

> The uninitiated might expect
>
>   exact_sum([0.3, 0.7])
>
> to be 1.

That's true but I wanted to correct the impression (from above) that
*converting* to Fraction is a source of rounding error. It is your
responsibility to give exact_sum the exact numbers that you want to
add.

You can even use strings if you want to write numbers in decimal:

    exact_sum(['0.3', '0.7'])

--
Oscar



More information about the Python-list mailing list