Kahan summation: Difference between revisions
(New draft task and Python solution.) |
(→{{header|Python}}: getcontext.) |
||
Line 33: | Line 33: | ||
Decimal('10005.9') |
Decimal('10005.9') |
||
>>> |
>>> |
||
>>> # More info on the current Decimal context: |
|||
⚫ | |||
>>> getcontext() |
|||
Context(prec=6, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow]) |
|||
>>> |
|||
>>> |
|||
⚫ | |||
>>> getcontext().prec = 20 |
>>> getcontext().prec = 20 |
||
>>> (a + b) + c |
>>> (a + b) + c |
Revision as of 01:47, 11 December 2014
The Kahan summation algorithm is a method of summing a series of numbers represented in a limited precision in a way that minimises the loss of precision in the result.
The task is to follow the previously linked Wikipedia articles algorithm and its worked example by:
- Do all arithmetic in decimal to a precision of six digits.
- Write a function/method/procedure/subroutine/... to perform Kahan summation on an ordered collection of numbers, (such as a list of numbers).
- Create the three numbers
a, b, c
equal to10000.0, 3.14159, 2.71828
respectively. - Show that the simple left-to-right summation, equivalent to
(a + b) + c
gives an answer of 10005.8 - Show that the Kahan function applied to the sequence of values
a, b, c
results in the more precise answer of 10005.9
Show all output on this page.
Python
<lang python>>>> from decimal import * >>> >>> getcontext().prec = 6 >>> >>> def kahansum(input):
summ = c = 0 for num in input: y = num - c t = summ + y c = (t - summ) - y summ = t return summ
>>> a, b, c = [Decimal(n) for n in '10000.0 3.14159 2.71828'.split()] >>> a, b, c (Decimal('10000.0'), Decimal('3.14159'), Decimal('2.71828')) >>> >>> (a + b) + c Decimal('10005.8') >>> kahansum([a, b, c]) Decimal('10005.9') >>> >>> # More info on the current Decimal context: >>> getcontext() Context(prec=6, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow]) >>> >>> >>> ## Lets try the simple summation with more precision for comparison >>> getcontext().prec = 20 >>> (a + b) + c Decimal('10005.85987') >>> </lang>