sum accuracy

Matt Wheeler m at funkyhat.org
Fri Apr 15 13:04:14 EDT 2016


So we could build on this

On 15 April 2016 at 11:10, Ben Bacarisse <ben.usenet at bsb.me.uk> wrote:
>> 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.  The uninitiated might expect
>
>   exact_sum([0.3, 0.7])
>
> to be 1.

and make

def not_exact_but_probably_the_sum_you_wanted(nums):
    return sum(map(lambda x:Fraction(x).limit_denominator(), nums))


-- 
Matt Wheeler
http://funkyh.at



More information about the Python-list mailing list