dsnanmeanpn.c (2585B)
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/stats/base/dsnanmeanpn.h" 20 #include <stdint.h> 21 22 /** 23 * Computes the arithmetic mean of a single-precision floating-point strided array, ignoring `NaN` values, using a two-pass error correction algorithm with extended accumulation, and returning an extended precision result. 24 * 25 * ## Method 26 * 27 * - This implementation uses a two-pass approach, as suggested by Neely (1966). 28 * 29 * ## References 30 * 31 * - Neely, Peter M. 1966. "Comparison of Several Algorithms for Computation of Means, Standard Deviations and Correlation Coefficients." _Communications of the ACM_ 9 (7). Association for Computing Machinery: 496–99. doi:[10.1145/365719.365958](https://doi.org/10.1145/365719.365958). 32 * - Schubert, Erich, and Michael Gertz. 2018. "Numerically Stable Parallel Computation of (Co-)Variance." In _Proceedings of the 30th International Conference on Scientific and Statistical Database Management_. New York, NY, USA: Association for Computing Machinery. doi:[10.1145/3221269.3223036](https://doi.org/10.1145/3221269.3223036). 33 * 34 * @param N number of indexed elements 35 * @param X input array 36 * @param stride stride length 37 * @return output value 38 */ 39 double stdlib_strided_dsnanmeanpn( const int64_t N, const float *X, const int64_t stride ) { 40 int64_t ix; 41 int64_t i; 42 int64_t n; 43 int64_t o; 44 double dn; 45 double s; 46 double t; 47 double v; 48 49 if ( N <= 0 ) { 50 return 0.0 / 0.0; // NaN 51 } 52 if ( N == 1 || stride == 0 ) { 53 return X[ 0 ]; 54 } 55 if ( stride < 0 ) { 56 ix = (1-N) * stride; 57 } else { 58 ix = 0; 59 } 60 o = ix; 61 62 // Compute an estimate for the mean... 63 s = 0.0; 64 n = 0; 65 for ( i = 0; i < N; i++ ) { 66 v = (double)X[ ix ]; 67 if ( v == v ) { 68 s += v; 69 n += 1; 70 } 71 ix += stride; 72 } 73 if ( n == 0 ) { 74 return 0.0 / 0.0; // NaN 75 } 76 dn = (double)n; 77 s /= dn; 78 79 // Compute an error term... 80 t = 0.0; 81 ix = o; 82 for ( i = 0; i < N; i++ ) { 83 v = (double)X[ ix ]; 84 if ( v == v ) { 85 t += v - s; 86 } 87 ix += stride; 88 } 89 return s + (t/dn); 90 }