sum accuracy

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Apr 15 07:31:12 EDT 2016


Tony van der Hoff writes:
> On 15/04/16 11:10, Ben Bacarisse 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.  The uninitiated might expect
>>
>>    exact_sum([0.3, 0.7])
>>
>> to be 1.
>>
>
> So I'm uninitiated:
> NameError: name 'exact_sum' is not defined
>
> I appreciate the word of warning, but, in my case, it's not helpful.

There's a reason Ben included some context.

His point is that Fraction(0.3) is not equal to Fraction(3, 10). That in
turn is because the floating point number differs a little from the
mathematical ideal, and the representation of that floating point number
as a Fraction in Python preserves that difference.

Try Fraction(0.3), Fraction("0.3"), Fraction(3, 10), Fraction(3)/10 and
see for yourself.

Also, Fraction(0.3).limit_denominator() gives Fraction(3, 10). See the
documentation.



More information about the Python-list mailing list