main.js (2339B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var abs = require( '@stdlib/math/base/special/abs' ); 24 25 26 // MAIN // 27 28 /** 29 * Returns an accumulator function which incrementally computes a sum. 30 * 31 * ## Method 32 * 33 * - This implementation uses a second-order "iterative Kahan–Babuška algorithm", as proposed by Klein (2005). 34 * 35 * ## References 36 * 37 * - Klein, Andreas. 2005. "A Generalized Kahan-Babuška-Summation-Algorithm." _Computing_ 76 (3): 279–93. doi:[10.1007/s00607-005-0139-x](https://doi.org/10.1007/s00607-005-0139-x). 38 * 39 * @returns {Function} accumulator function 40 * 41 * @example 42 * var accumulator = incrsum(); 43 * 44 * var sum = accumulator(); 45 * // returns null 46 * 47 * sum = accumulator( 2.0 ); 48 * // returns 2.0 49 * 50 * sum = accumulator( -5.0 ); 51 * // returns -3.0 52 * 53 * sum = accumulator(); 54 * // returns -3.0 55 */ 56 function incrsum() { 57 var sum; 58 var ccs; 59 var FLG; 60 var cs; 61 var cc; 62 var t; 63 var c; 64 65 sum = 0.0; 66 ccs = 0.0; // second order correction term for lost low order bits 67 cs = 0.0; // first order correction term for lost low order bits 68 return accumulator; 69 70 /** 71 * If provided a value, the accumulator function returns an updated sum. If not provided a value, the accumulator function returns the current sum. 72 * 73 * @private 74 * @param {number} [x] - new value 75 * @returns {(number|null)} sum or null 76 */ 77 function accumulator( x ) { 78 if ( arguments.length === 0 ) { 79 return ( FLG ) ? sum+cs+ccs : null; 80 } 81 FLG = true; 82 t = sum + x; 83 if ( abs( sum ) >= abs( x ) ) { 84 c = (sum-t) + x; 85 } else { 86 c = (x-t) + sum; 87 } 88 sum = t; 89 t = cs + c; 90 if ( abs( cs ) >= abs( c ) ) { 91 cc = (cs-t) + c; 92 } else { 93 cc = (c-t) + cs; 94 } 95 cs = t; 96 ccs += cc; 97 return sum + cs + ccs; 98 } 99 } 100 101 102 // EXPORTS // 103 104 module.exports = incrsum;