Browse files

Added the code

  • Loading branch information...
1 parent 8ff5164 commit b993bdbc8cb5dddd2a1f10336e3bef0f88c93921 @viktors committed May 31, 2011
Showing with 67 additions and 0 deletions.
  1. 0 README
  2. +20 −0 README.md
  3. +17 −0 index.js
  4. +19 −0 package.json
  5. +11 −0 test/test.sum.js
View
0 README
No changes.
View
20 README.md
@@ -0,0 +1,20 @@
+Kahan summation algorithm for Node.js
+=====================================
+
+Since JavaScript's only numerical data type is Number, internally represented
+as floating-point number, calculating a sum of numbers can introduce significant
+numerical error. This library aims to reduce the error by employing
+[Kahan's summation algorithm](http://en.wikipedia.org/wiki/Kahan_summation_algorithm).
+
+Example
+-------
+
+```js
+// Naive summation
+[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7].reduce(function(a, b) { return a + b })
+// -> 15.299999999999999
+
+// Kahan summation
+require('kahan').sum([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7])
+// -> 15.3
+```
View
17 index.js
@@ -0,0 +1,17 @@
+// Implements http://en.wikipedia.org/wiki/Kahan_summation_algorithm
+
+function kahanSum(inputArray) {
+ var sum = 0.0
+ , c = 0.0 // A running compensation for lost low-order bits.
+ for(var i = 0; i < inputArray.length; i++) {
+ y = inputArray[i] - c // So far, so good: c is zero.
+ t = sum + y // Alas, sum is big, y small, so low-order digits of y are lost.
+ c = (t - sum) - y // (t - sum) recovers the high-order part of y; subtracting y recovers -(low part of y)
+ sum = t // Algebraically, c should always be zero. Beware eagerly optimising compilers!
+ } // Next time around, the lost low part will be added to y in a fresh attempt.
+ return sum
+}
+
+module.exports = {
+ sum: kahanSum
+}
View
19 package.json
@@ -0,0 +1,19 @@
+{
+ "name": "kahan",
+ "version": "0.0.1",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/viktors/node-kahan.git"
+ },
+ "author": "Viktors Rotanovs <viktors.rotanovs@gmail.com> (http://rotanovs.com)",
+ "dependencies": {
+ "expresso": ">=0.7.7"
+ },
+ "main": "index",
+ "engines": {
+ "node": ">= 0.4.0 < 0.5.0"
+ },
+ "files": [
+ ""
+ ]
+}
View
11 test/test.sum.js
@@ -0,0 +1,11 @@
+// Run $ expresso
+
+var assert = require('assert'),
+ kahan = require('../index.js')
+
+var testArray = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7]
+
+module.exports =
+ { 'test naive summation': function() { assert.equal(15.299999999999999, testArray.reduce(function(a, b) { return a + b })) }
+ , 'test Kahan summation': function() { assert.equal(15.3, kahan.sum(testArray)) }
+ }

0 comments on commit b993bdb

Please sign in to comment.