User-defined vector, variance, and standard deviation

Basically, I need to write functions for the formulas to act on a user-defined vector. Any advice for a novice?
Here's a start. I suggest looking up the formula to variance of a set of data, and try to translate it into C++ inside of the variance function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Example program
#include <iostream>
#include <vector>
#include <cmath>

using Data = double;

Data variance(const std::vector<Data>& vec)
{
    Data var = 0;
    // hint: you'll need a for loop here
    return var;
}

Data std_dev(const std::vector<Data>& vec)
{
    return std::sqrt(variance(vec)); 
}

int main()
{
    std::vector<Data> vec(10);
    
    // fill in vector with whatever data
    for (size_t i = 0; i < vec.size(); i++)
    {
        vec[i] = (2017 * i) % vec.size();
    }
    
    // call variance function:
    Data var = variance(vec);
    
    // call standard deviation function:
    Data standard_deviation = std_dev(vec);
    
}


Read:
https://www.sciencebuddies.org/science-fair-projects/science-fair/variance-and-standard-deviation

Also be aware of the differences in variance/stdev definitions, depending on what your data is (you most likely don't have to worry about this for your purposes, though):
https://en.wikipedia.org/wiki/Bessel%27s_correction
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <valarray>
using namespace std;

int main()
{
   valarray<double> A{ 1, 2, 3, 4 };

   double mean = A.sum() / A.size();
   double variance = ( A * A ).sum() / A.size() - mean * mean;

   cout << "Mean = " << mean << '\n'
        << "Variance = " << variance << '\n'
        << "Sigma = " << sqrt( variance ) << '\n';
}
Mean = 2.5
Variance = 1.25
Sigma = 1.11803


Variance here is that of your given data. If you are using your data to estimate both variance AND mean of a larger population of which your sample is only a small part, multiply the variance by N/(N-1) to get an unbiased estimator. The mean is already unbiased.

This is the way I wish all arrays worked.
Last edited on
Topic archived. No new replies allowed.