dnanmeanwd.c (2385B)
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/dnanmeanwd.h" 20 #include <stdint.h> 21 22 /** 23 * Computes the arithmetic mean of a double-precision floating-point strided array, using Welford's algorithm and ignoring `NaN` values. 24 * 25 * ## Method 26 * 27 * - This implementation uses Welford's algorithm for efficient computation, which can be derived as follows 28 * 29 * ```tex 30 * \begin{align*} 31 * \mu_n &= \frac{1}{n} \sum_{i=0}^{n-1} x_i \\ 32 * &= \frac{1}{n} \biggl(x_{n-1} + \sum_{i=0}^{n-2} x_i \biggr) \\ 33 * &= \frac{1}{n} (x_{n-1} + (n-1)\mu_{n-1}) \\ 34 * &= \mu_{n-1} + \frac{1}{n} (x_{n-1} - \mu_{n-1}) 35 * \end{align*} 36 * ``` 37 * 38 * ## References 39 * 40 * - Welford, B. P. 1962. "Note on a Method for Calculating Corrected Sums of Squares and Products." _Technometrics_ 4 (3). Taylor & Francis: 419–20. doi:[10.1080/00401706.1962.10490022](https://doi.org/10.1080/00401706.1962.10490022). 41 * - van Reeken, A. J. 1968. "Letters to the Editor: Dealing with Neely's Algorithms." _Communications of the ACM_ 11 (3): 149–50. doi:[10.1145/362929.362961](https://doi.org/10.1145/362929.362961). 42 * 43 * @param N number of indexed elements 44 * @param X input array 45 * @param stride stride length 46 * @return output value 47 */ 48 double stdlib_strided_dnanmeanwd( const int64_t N, const double *X, const int64_t stride ) { 49 int64_t ix; 50 int64_t i; 51 int64_t n; 52 double mu; 53 double v; 54 55 if ( N <= 0 ) { 56 return 0.0 / 0.0; // NaN 57 } 58 if ( N == 1 || stride == 0 ) { 59 return X[ 0 ]; 60 } 61 if ( stride < 0 ) { 62 ix = (1-N) * stride; 63 } else { 64 ix = 0; 65 } 66 mu = 0.0; 67 n = 0; 68 for ( i = 0; i < N; i++ ) { 69 v = X[ ix ]; 70 if ( v == v ) { 71 n += 1; 72 mu += ( v-mu ) / (double)n; 73 } 74 ix += stride; 75 } 76 if ( n == 0 ) { 77 return 0.0 / 0.0; // NaN; 78 } 79 return mu; 80 }