-2

I have a functioning program to find the standard deviation of many integers. However, I am to find a way to get the standard deviation without the mean.

I understand the formula is: std dev = sqrt [(B - A^2/N)/N]

where

A is the sum of the data values;

B is the sum of the squared data values;

N is the number of data values.

but how would I write that in code? This is my function for the deviation but it uses the mean:

float calculateSD(int arr[])
{
float sum = 0.0, mean, standardDeviation = 0.0;

int i;

for(i = 0; i < SIZE; ++i)
{
    sum += arr[i];
}

mean = sum/SIZE;

for(i = 0; i < SIZE; ++i)
  //convert standardDeviation to float
    standardDeviation += static_cast<float>(pow(arr[i] - mean, 2));
//return standard deviation
return sqrt(standardDeviation / SIZE);

}    
Mark P
  • 17
  • 2

1 Answers1

0
#include <iostream>
#include <vector>
#include <numeric>
#include <math.h>

double stddev(std::vector<int> const& data)
{
    auto stats = std::make_pair(0.0,0.0);
    stats = std::accumulate(data.begin(), data.end(), stats,
                            [](std::pair<double,double> stats, double x) {
                                stats.first += x;
                                stats.second += x * x;
                                return stats;
                            });
    return sqrt((stats.second - pow(stats.first, 2.0) / data.size()) / data.size());
}

int main(int argc, const char *argv[])
{
    std::cout << stddev({1,1,1,1}) << std::endl;
    std::cout << stddev({1,2,1,2}) << std::endl;
    std::cout << stddev({1,10,1,10}) << std::endl;
}
RandomBits
  • 4,194
  • 1
  • 17
  • 30