From b9df0a758202173a31b892f57c1a1dcc196508b2 Mon Sep 17 00:00:00 2001 From: John Benediktsson Date: Sun, 13 Oct 2013 08:27:58 -0700 Subject: [PATCH] math.extras: adding the Kahan summation. --- extra/math/extras/extras-docs.factor | 4 ++++ extra/math/extras/extras.factor | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/extra/math/extras/extras-docs.factor b/extra/math/extras/extras-docs.factor index cd477f8354..51abeaab1f 100644 --- a/extra/math/extras/extras-docs.factor +++ b/extra/math/extras/extras-docs.factor @@ -86,3 +86,7 @@ HELP: round-to-decimal { $example "USING: math.extras prettyprint ;" "1.23456 2 round-to-decimal ." "1.23" } { $example "USING: math.extras prettyprint ;" "12345.6789 -3 round-to-decimal ." "12000.0" } } ; + +HELP: kahan-sum +{ $values { "seq" sequence } { "n" float } } +{ $description "Calculates the summation of the sequence using the Kahan summation algorithm." } ; diff --git a/extra/math/extras/extras.factor b/extra/math/extras/extras.factor index 0dc792a307..56825f2801 100644 --- a/extra/math/extras/extras.factor +++ b/extra/math/extras/extras.factor @@ -289,3 +289,8 @@ M: real round-away-from-zero [ swapd @ [ 1 + ] [ max 0 ] if ] keep swap ] reduce nip max ] if ; inline + +: kahan-sum ( seq -- n ) + [ 0.0 0.0 ] dip [ + rot - 2dup + [ -rot [ - ] bi@ ] keep + ] each nip ;