Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
About stdlib...

We believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we've built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.

The library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.

When you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.

To join us in bringing numerical computing to the web, get started by checking us out on GitHub, and please consider financially supporting stdlib. We greatly appreciate your continued support!

dvariancech

NPM version Build Status Coverage Status

Calculate the variance of a one-dimensional double-precision floating-point ndarray using a one-pass trial mean algorithm.

The population variance of a finite size population of size N is given by

$$\sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2$$

where the population mean is given by

$$\mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i$$

Often in the analysis of data, the true population variance is not known a priori and must be estimated from a sample drawn from the population distribution. If one attempts to use the formula for the population variance, the result is biased and yields an uncorrected sample variance. To compute a corrected sample variance for a sample of size n,

$$s^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2$$

where the sample mean is given by

$$\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i$$

The use of the term n-1 is commonly referred to as Bessel's correction. Note, however, that applying Bessel's correction can increase the mean squared error between the sample variance and population variance. Depending on the characteristics of the population distribution, other correction factors (e.g., n-1.5, n+1, etc) can yield better estimators.

Installation

npm install @stdlib/stats-base-ndarray-dvariancech

Alternatively,

  • To load the package in a website via a script tag without installation and bundlers, use the ES Module available on the esm branch (see README).
  • If you are using Deno, visit the deno branch (see README for usage intructions).
  • For use in Observable, or in browser/node environments, use the Universal Module Definition (UMD) build available on the umd branch (see README).

The branches.md file summarizes the available branches and displays a diagram illustrating their relationships.

To view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.

Usage

var dvariancech = require( '@stdlib/stats-base-ndarray-dvariancech' );

dvariancech( arrays )

Computes the variance of a one-dimensional double-precision floating-point ndarray using a one-pass trial mean algorithm.

var Float64Vector = require( '@stdlib/ndarray-vector-float64' );
var scalar2ndarray = require( '@stdlib/ndarray-from-scalar' );

var opts = {
    'dtype': 'float64'
};

var x = new Float64Vector( [ 1.0, -2.0, 2.0 ] );
var correction = scalar2ndarray( 1.0, opts );

var v = dvariancech( [ x, correction ] );
// returns ~4.3333

The function has the following parameters:

  • arrays: array-like object containing the following ndarrays:

    • a one-dimensional input ndarray.
    • a zero-dimensional ndarray specifying the degrees of freedom adjustment. Providing a non-zero degrees of freedom adjustment has the effect of adjusting the divisor during the calculation of the variance according to N-c where N is the number of elements in the input ndarray and c corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to 0 is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample variance, setting this parameter to 1 is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction).

Notes

  • If provided an empty one-dimensional ndarray, the function returns NaN.
  • If N - c is less than or equal to 0 (where N corresponds to the number of elements in the input ndarray and c corresponds to the provided degrees of freedom adjustment), the function returns NaN.

Examples

var discreteUniform = require( '@stdlib/random-discrete-uniform' );
var scalar2ndarray = require( '@stdlib/ndarray-from-scalar' );
var ndarray2array = require( '@stdlib/ndarray-to-array' );
var dvariancech = require( '@stdlib/stats-base-ndarray-dvariancech' );

var opts = {
    'dtype': 'float64'
};

var x = discreteUniform( [ 10 ], -50, 50, opts );
console.log( ndarray2array( x ) );

var correction = scalar2ndarray( 1.0, opts );
var v = dvariancech( [ x, correction ] );
console.log( v );

C APIs

Usage

#include "stdlib/stats/base/ndarray/dvariancech.h"

stdlib_stats_dvariancech( arrays )

Computes the variance of a one-dimensional double-precision floating-point ndarray using a one-pass trial mean algorithm.

#include "stdlib/ndarray/ctor.h"
#include "stdlib/ndarray/dtypes.h"
#include "stdlib/ndarray/index_modes.h"
#include "stdlib/ndarray/orders.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include <stdint.h>

// Create an ndarray:
const double data[] = { 1.0, -2.0, 2.0 };
int64_t shape[] = { 3 };
int64_t strides[] = { STDLIB_NDARRAY_FLOAT64_BYTES_PER_ELEMENT };
int8_t submodes[] = { STDLIB_NDARRAY_INDEX_ERROR };

struct ndarray *x = stdlib_ndarray_allocate( STDLIB_NDARRAY_FLOAT64, (uint8_t *)data, 1, shape, strides, 0, STDLIB_NDARRAY_ROW_MAJOR, STDLIB_NDARRAY_INDEX_ERROR, 1, submodes );

// Create an ndarray for specifying the degrees of freedom adjustment:
const double cdata[] = { 1.0 };
int64_t cstrides[] = { 0 };
struct ndarray *corr = stdlib_ndarray_allocate( STDLIB_NDARRAY_FLOAT64, (uint8_t *)cdata, 0, NULL, cstrides, 0, STDLIB_NDARRAY_ROW_MAJOR, STDLIB_NDARRAY_INDEX_ERROR, 1, submodes );

// Compute the result:
const struct ndarray *arrays[] = { x, corr };
double v = stdlib_stats_dvariancech( arrays );
// returns ~4.3333

// Free allocated memory:
stdlib_ndarray_free( x );
stdlib_ndarray_free( corr );

The function accepts the following arguments:

  • arrays: [in] struct ndarray** list containing the following ndarrays:

    • [in] struct ndarray* a one-dimensional input ndarray.
    • [in] struct ndarray* a zero-dimensional ndarray specifying the degrees of freedom adjustment. Providing a non-zero degrees of freedom adjustment has the effect of adjusting the divisor during the calculation of the variance according to N-c where N is the number of elements in the input ndarray and c corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to 0 is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample variance, setting this parameter to 1 is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction).
double stdlib_stats_dvariancech( const struct ndarray *arrays[] );

Examples

#include "stdlib/stats/base/ndarray/dvariancech.h"
#include "stdlib/ndarray/ctor.h"
#include "stdlib/ndarray/dtypes.h"
#include "stdlib/ndarray/index_modes.h"
#include "stdlib/ndarray/orders.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

int main( void ) {
    // Create a data buffer:
    const double data[] = { 1.0, -2.0, 3.0, -4.0, 5.0, -6.0, 7.0, -8.0 };

    // Specify the number of array dimensions:
    const int64_t ndims = 1;

    // Specify the array shape:
    int64_t shape[] = { 4 };

    // Specify the array strides:
    int64_t strides[] = { 2*STDLIB_NDARRAY_FLOAT64_BYTES_PER_ELEMENT };

    // Specify the byte offset:
    const int64_t offset = 0;

    // Specify the array order:
    const enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;

    // Specify the index mode:
    const enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;

    // Specify the subscript index modes:
    int8_t submodes[] = { STDLIB_NDARRAY_INDEX_ERROR };
    const int64_t nsubmodes = 1;

    // Create an ndarray:
    struct ndarray *x = stdlib_ndarray_allocate( STDLIB_NDARRAY_FLOAT64, (uint8_t *)data, ndims, shape, strides, offset, order, imode, nsubmodes, submodes );
    if ( x == NULL ) {
        fprintf( stderr, "Error allocating memory.\n" );
        exit( 1 );
    }

    // Create a data buffer for an ndarray specifying the degrees of freedom adjustment:
    const double cdata[] = { 1.0 };

    // Specify the array strides:
    int64_t cstrides[] = { 0 };

    // Create an ndarray for the degrees of freedom adjustment:
    struct ndarray *corr = stdlib_ndarray_allocate( STDLIB_NDARRAY_FLOAT64, (uint8_t *)cdata, 0, NULL, cstrides, 0, order, imode, nsubmodes, submodes );
    if ( corr == NULL ) {
        fprintf( stderr, "Error allocating memory.\n" );
        exit( 1 );
    }

    // Define a list of ndarrays:
    const struct ndarray *arrays[] = { x, corr };

    // Compute the result:
    double v = stdlib_stats_dvariancech( arrays );

    // Print the result:
    printf( "result: %lf\n", v );

    // Free allocated memory:
    stdlib_ndarray_free( x );
    stdlib_ndarray_free( corr );
}

References

  • 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.
  • Ling, Robert F. 1974. "Comparison of Several Algorithms for Computing Sample Means and Variances." Journal of the American Statistical Association 69 (348). American Statistical Association, Taylor & Francis, Ltd.: 859–66. doi:10.2307/2286154.
  • Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. 1983. "Algorithms for Computing the Sample Variance: Analysis and Recommendations." The American Statistician 37 (3). American Statistical Association, Taylor & Francis, Ltd.: 242–47. doi:10.1080/00031305.1983.10483115.
  • 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.

Notice

This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.

For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.

Community

Chat


License

See LICENSE.

Copyright

Copyright © 2016-2026. The Stdlib Authors.

About

Compute the variance of a one-dimensional double-precision floating-point ndarray using a one-pass trial mean algorithm.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages