time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

dnannsumkbn.c (2184B)


      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 #include "stdlib/blas/ext/base/dnannsumkbn.h"
     20 #include "stdlib/math/base/assert/is_nan.h"
     21 #include <stdint.h>
     22 #include <math.h>
     23 
     24 /**
     25 * Computes the sum of double-precision floating-point strided array elements, ignoring `NaN` values and using an improved Kahan–Babuška algorithm.
     26 *
     27 * ## Method
     28 *
     29 * -   This implementation uses an "improved Kahan–Babuška algorithm", as described by Neumaier (1974).
     30 *
     31 * ## References
     32 *
     33 * -   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).
     34 *
     35 * @param N       number of indexed elements
     36 * @param X       input array
     37 * @param stride  stride length
     38 * @param n       pointer for storing the number of non-NaN elements
     39 * @return        output value
     40 */
     41 double stdlib_strided_dnannsumkbn( const int64_t N, const double *X, const int64_t stride, int64_t *n ) {
     42 	double sum;
     43 	int64_t ix;
     44 	int64_t i;
     45 	double v;
     46 	double t;
     47 	double c;
     48 
     49 	sum = 0.0;
     50 	*n = 0;
     51 	if ( N <= 0 ) {
     52 		return sum;
     53 	}
     54 	if ( N == 1 || stride == 0 ) {
     55 		if ( stdlib_base_is_nan( X[ 0 ] ) ) {
     56 			return sum;
     57 		}
     58 		*n += 1;
     59 		return X[ 0 ];
     60 	}
     61 	if ( stride < 0 ) {
     62 		ix = (1-N) * stride;
     63 	} else {
     64 		ix = 0;
     65 	}
     66 	c = 0.0;
     67 	for ( i = 0; i < N; i++ ) {
     68 		v = X[ ix ];
     69 		if ( !stdlib_base_is_nan( v ) ) {
     70 			t = sum + v;
     71 			if ( fabs( sum ) >= fabs( v ) ) {
     72 				c += (sum-t) + v;
     73 			} else {
     74 				c += (v-t) + sum;
     75 			}
     76 			sum = t;
     77 			*n += 1;
     78 		}
     79 		ix += stride;
     80 	}
     81 	return sum + c;
     82 }