Back on track with my C++ saga:
The standard deviation of a list of numbers is a measure of how much the numbers deviate from the average. If the standard deviation is small, the numbers are clustered close to the average. If the standard deviation is large, the numbers are scattered far from the average. The standard deviation, \$ S \$, of a list of \$ N \$ numbers \$ x \$ is defined as follows
$$ S = \sqrt{\dfrac{\sum\limits_{i=1}^{N} \left( x_i - \bar{x} \right)^{2}}{N}} $$
Where \$\bar{x} \$ is the average of the \$ N \$ numbers \$ x1, x2, .... \$ Define a function that takes a partially filled array of numbers as its arguments and returns the standard deviation of the numbers in the partially filled array. Since a partially filled array requires two arguments, the function will actually have two formal parameters: an array parameter and a formal parameter of type
int
that gives the number of array positions used. The numbers in the array will be of typedouble
Embed your function in a suitable test program.
stddev.cpp
:
/**
* @file stddev.cpp
* @brief
* @author syb0rg
* @date 11/6/14
*/
#include <iostream>
#include <fstream>
#include <cmath>
constexpr int NUM_ELEM = 28;
double mean(double arr[])
{
double sum = 0;
for (int i = 0; i < NUM_ELEM; ++i)
{
sum += arr[i];
}
return (sum / NUM_ELEM);
}
double stdDev(double arr[])
{
double avg = mean(arr);
double sum = 0;
for (int i = 0; i < NUM_ELEM; ++i)
{
arr[i] = arr[i] - avg;
sum += std::pow(arr[i], 2);
}
return std::sqrt(sum / NUM_ELEM);
}
int main()
{
std::ifstream file("test.txt", std::ios_base::in);
double input[NUM_ELEM] = {0.0};
for(int i = 0; (file >> input[i]) && file.good(); ++i);
std::cout << stdDev(input) << std::endl;
file.close();
}