Calculate mean and standard deviation from a vector in C++

In this tutorial, we will see how to calculate the mean and standard deviation from a vector in C++. We know that the mean has a formula which is the sum of elements divided by a total number of elements which is also called as total size of vector. Let’s see how to implement mean and standard deviation with the help of vectors in C++ through examples.

Calculate mean from vector in C++

#include<iostream>
#include<vector>
using namespace std;

int main(){
    vector<double>vec1 = {10.1,10.2,10.3,10.4,10.5,10.6,10.7,10.8,10.9,10.10};

    double sum = 0;
    int count_size = 0;
    
    for(auto& x:vec1){
        sum += x;
        count_size += 1;
    }

    double mean = (sum/count_size);
    cout<<"Mean is: "<<mean<<endl;
    return 0;
}

Output –

Mean is: 10.46

In this example, we simply create a vector of double elements and perform a simple mean operation with the help of a vector.

Calculate the standard deviation from a vector in C++   –

Before we move forward we should know what exactly the standard deviation is?  So, Standard deviation measures the spread variation from the mean value. In simple terms if data points are close to the mean then they have less standard deviation but if data points close not close to the mean then they have a high standard deviation.

Formula –  

Standard deviation – √ (∑(m – e)² / (n – 1))

m – mean of all elements

e – each element

n – total number of elements

 

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;

int main(){
    vector<double>vec1 = {0.1,0.4,0.6,0.8,1.1,1.2,1.3,1.5,1.7,1.9,1.9,2.0,2.2,2.6,3.2};
    vector<double>temp;

    double sum = 0;
    int count_size = 0;

    for(auto& x:vec1){
        sum += x;
        count_size += 1;
    }

    double mean = (sum/count_size);
    cout<<"Mean is: "<<mean<<endl;

    //This is for calculate the standard deviation
    for(auto x:vec1){
        double num1 = abs(mean - x);
        double num2 = pow(num1,2);
        temp.push_back(num2);
    }

    //This loop is used to calculate the sum 
    double temp_sum = 0;
    for(auto& x:temp){
        temp_sum += x;
    }

    //Calculate variance
    double variance_value = temp_sum/(count_size - 1); 
    cout<<"Variance is: "<<variance_value<<endl;

    //Now we will calculate standard deviation

    double sd_value = sqrt(variance_value);
    cout<<"Standard deviation is: "<<sd_value<<endl;

    return 0;
}

Output – 

Mean is: 1.5
Variance is: 0.711429
Standard deviation is: 0.843462

In this example, firstly we have calculated the mean then we calculate the variance for which we need to perform some operations so we have included cmath header file as well. After the calculation of variance, we calculated the standard deviation from a vector in C++. Hope this tutorial will be helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *