|
| 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 | +// MAIN // |
| 22 | + |
| 23 | +/** |
| 24 | +* Computes the sum of strided array elements using pairwise summation. |
| 25 | +* |
| 26 | +* ## Method |
| 27 | +* |
| 28 | +* - This implementation uses pairwise summation, which accrues rounding error `O(log2 N)` instead of `O(N)`. The recursion depth is also `O(log2 N)`. |
| 29 | +* |
| 30 | +* ## References |
| 31 | +* |
| 32 | +* - Higham, Nicholas J. 1993. "The Accuracy of Floating Point Summation." _SIAM Journal on Scientific Computing_ 14 (4): 783–99. doi:[10.1137/0914050](https://doi.org/10.1137/0914050). |
| 33 | +* |
| 34 | +* @param {PositiveInteger} N - number of indexed elements |
| 35 | +* @param {Object} x - input array object |
| 36 | +* @param {Collection} x.data - input array data |
| 37 | +* @param {Array<Function>} x.accessors - array element accessors |
| 38 | +* @param {integer} strideX - stride length |
| 39 | +* @param {NonNegativeInteger} offsetX - starting index |
| 40 | +* @returns {number} sum |
| 41 | +* |
| 42 | +* @example |
| 43 | +* var toAccessorArray = require( '@stdlib/array/base/to-accessor-array' ); |
| 44 | +* var arraylike2object = require( '@stdlib/array/base/arraylike2object' ); |
| 45 | +* |
| 46 | +* var x = toAccessorArray( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] ); |
| 47 | +* |
| 48 | +* var v = gsumpw( 4, arraylike2object( x ), 2, 1 ); |
| 49 | +* // returns 5.0 |
| 50 | +*/ |
| 51 | +function gsumpw( N, x, strideX, offsetX ) { |
| 52 | + var xbuf; |
| 53 | + var get; |
| 54 | + var ix; |
| 55 | + var s; |
| 56 | + var i; |
| 57 | + |
| 58 | + // Cache reference to array data: |
| 59 | + xbuf = x.data; |
| 60 | + |
| 61 | + // Cache a reference to the element accessor: |
| 62 | + get = x.accessors[ 0 ]; |
| 63 | + ix = offsetX; |
| 64 | + if ( strideX === 0 ) { |
| 65 | + return N * get( xbuf, ix ); |
| 66 | + } |
| 67 | + s = 0.0; |
| 68 | + |
| 69 | + // TODO --- for ( i = 0; i < N; i++ ) {} |
| 70 | + return s; |
| 71 | +} |
| 72 | + |
| 73 | + |
| 74 | +// EXPORTS // |
| 75 | + |
| 76 | +module.exports = gsumpw; |
0 commit comments