dnanvariancewd.c (2264B)
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/dnanvariancewd.h" 20 #include <stdint.h> 21 22 /** 23 * Computes the variance of a double-precision floating-point strided array ignoring `NaN` values and using Welford's algorithm. 24 * 25 * ## References 26 * 27 * - 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). 28 * - 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). 29 * 30 * @param N number of indexed elements 31 * @param correction degrees of freedom adjustment 32 * @param X input array 33 * @param stride stride length 34 * @return output value 35 */ 36 double stdlib_strided_dnanvariancewd( const int64_t N, const double correction, const double *X, const int64_t stride ) { 37 double delta; 38 int64_t ix; 39 int64_t n; 40 int64_t i; 41 double M2; 42 double nc; 43 double mu; 44 double v; 45 46 if ( N <= 0 ) { 47 return 0.0 / 0.0; // NaN 48 } 49 if ( N == 1 || stride == 0 ) { 50 v = X[ 0 ]; 51 if ( v == v && (double)N-correction > 0.0 ) { 52 return 0.0; 53 } 54 return 0.0 / 0.0; // NaN 55 } 56 if ( stride < 0 ) { 57 ix = (1-N) * stride; 58 } else { 59 ix = 0; 60 } 61 M2 = 0.0; 62 mu = 0.0; 63 n = 0; 64 for ( i = 0; i < N; i++ ) { 65 v = X[ ix ]; 66 if ( v == v ) { 67 delta = v - mu; 68 n += 1; 69 mu += delta / (double)n; 70 M2 += delta * ( v - mu ); 71 } 72 ix += stride; 73 } 74 nc = (double)n - correction; 75 if ( nc <= 0.0 ) { 76 return 0.0 / 0.0; // NaN 77 } 78 return M2 / nc; 79 }