Calculates the variance of a given set of data.

You're viewing an older version of this page (#5407). View the current version.

View versions (2)

Interface

#include <codecogs/statistics/moments/variance.h>

using namespace Statistics::Moments;

Consider a discrete random variable $X$. The variance $X$ of is defined as

$$var[X]=E[(X-E[X])^2]$$
(1)

Note that $(X-E[X])^2$ is a new random variable (it's a function of $X$ ). The variance is also denoted as $\sigma^2$. A useful formula that follows inmediately from the definition is that

$$var[X]=E[X^2]-E[X]^2$$
(2)

In words, the variance of $X$ is the second moment of $X$ minus the first moment squared. The variance of a random variable determines a level of variation of the possible values of $X$ around its mean. However, as this measure is squared, the standard deviation is used instead when one wants to talk about how much a random variable varies around its expected value.

If we cannot analyze a whole population but we have to take a sample, we define its variance (denoted as $s^2$) with the formula:

$$s^2=\frac{1}{N-1}\sum_{i=1}^N(x_i-\overline{x})^2$$
(3)

where $\overline{x}$ is the arithmetic mean . The value for $s^2$ is an estimator for $\sigma$.

If the value of the boolean argument <em> total </em> is true, then the variance is computed using the following formula:

$$Var=\frac{1}{N}\sum_{i=1}^N(x_i-\overline{x})^2$$
(4)

References

PlanetMath, http://planetmath.org/encyclopedia/Variance.html

Example 1

#include <codecogs/statistics/moments/variance.h>
#include <iostream>
int main()
 {
   int x[5] = {3 , 1 , 5 , 6 , 9};
   double var = Statistics::Moments::variance<int>(5, x);
   std::cout << "The sample variance is: " << var << std::endl;
   return 0;
 }

Output:

The sample variance is: 9.2

Parameters

n
the size of the population
data
the actual population data given as an array
total
Default value = false

Returns

return value the variance of the given set of data
GPL Licence — free for non commercial use. See Licence details.