scusumkbn.js (2693B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 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 float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' ); 24 var abs = require( '@stdlib/math/base/special/abs' ); 25 26 27 // MAIN // 28 29 /** 30 * Computes the cumulative sum of single-precision floating-point strided array elements using an improved Kahan–Babuška algorithm. 31 * 32 * ## Method 33 * 34 * - This implementation uses an "improved Kahan–Babuška algorithm", as described by Neumaier (1974). 35 * 36 * ## References 37 * 38 * - Neumaier, Arnold. 1974. "Rounding Error Analysis of Some Methods for Summing Finite Sums." _Zeitschrift Für Angewandte Mathematik Und Mechanik_ 54 (1): 39–51. doi:[10.1002/zamm.19740540106](https://doi.org/10.1002/zamm.19740540106). 39 * 40 * @param {PositiveInteger} N - number of indexed elements 41 * @param {number} sum - initial sum 42 * @param {Float32Array} x - input array 43 * @param {integer} strideX - `x` stride length 44 * @param {Float32Array} y - output array 45 * @param {integer} strideY - `y` stride length 46 * @returns {Float32Array} output array 47 * 48 * @example 49 * var Float32Array = require( '@stdlib/array/float32' ); 50 * 51 * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); 52 * var y = new Float32Array( x.length ); 53 * var N = x.length; 54 * 55 * var v = scusumkbn( N, 0.0, x, 1, y, 1 ); 56 * // returns <Float32Array>[ 1.0, -1.0, 1.0 ] 57 */ 58 function scusumkbn( N, sum, x, strideX, y, strideY ) { 59 var ix; 60 var iy; 61 var s; 62 var v; 63 var t; 64 var c; 65 var i; 66 67 if ( N <= 0 ) { 68 return y; 69 } 70 if ( strideX < 0 ) { 71 ix = (1-N) * strideX; 72 } else { 73 ix = 0; 74 } 75 if ( strideY < 0 ) { 76 iy = (1-N) * strideY; 77 } else { 78 iy = 0; 79 } 80 s = sum; 81 c = 0.0; 82 for ( i = 0; i < N; i++ ) { 83 v = x[ ix ]; 84 t = float64ToFloat32( s + v ); 85 if ( abs( s ) >= abs( v ) ) { 86 c = float64ToFloat32( c + float64ToFloat32( float64ToFloat32( s-t ) + v ) ); // eslint-disable-line max-len 87 } else { 88 c = float64ToFloat32( c + float64ToFloat32( float64ToFloat32( v-t ) + s ) ); // eslint-disable-line max-len 89 } 90 s = t; 91 y[ iy ] = float64ToFloat32( s + c ); 92 ix += strideX; 93 iy += strideY; 94 } 95 return y; 96 } 97 98 99 // EXPORTS // 100 101 module.exports = scusumkbn;