time-to-botec

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

dvarmpn.c (2283B)


      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/dvarmpn.h"
     20 #include <stdint.h>
     21 
     22 /**
     23 * Computes the variance of a double-precision floating-point strided array provided a known mean and using Neely's correction algorithm.
     24 *
     25 * ## References
     26 *
     27 * -   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).
     28 * -   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).
     29 *
     30 * @param N           number of indexed elements
     31 * @param mean        mean
     32 * @param correction  degrees of freedom adjustment
     33 * @param X           input array
     34 * @param stride      stride length
     35 * @return            output value
     36 */
     37 double stdlib_strided_dvarmpn( const int64_t N, const double mean, const double correction, const double *X, const int64_t stride ) {
     38 	int64_t ix;
     39 	int64_t i;
     40 	double dN;
     41 	double M2;
     42 	double M;
     43 	double n;
     44 	double d;
     45 
     46 	dN = (double)N;
     47 	n = dN - correction;
     48 	if ( N <= 0 || n <= 0.0 ) {
     49 		return 0.0 / 0.0; // NaN
     50 	}
     51 	if ( N == 1 || stride == 0 ) {
     52 		return 0.0;
     53 	}
     54 	if ( stride < 0 ) {
     55 		ix = (1-N) * stride;
     56 	} else {
     57 		ix = 0;
     58 	}
     59 	M2 = 0.0;
     60 	M = 0.0;
     61 	for ( i = 0; i < N; i++ ) {
     62 		d = X[ ix ] - mean;
     63 		M2 += d * d;
     64 		M += d;
     65 		ix += stride;
     66 	}
     67 	return (M2/n) - ((M/dN)*(M/n));
     68 }