double Num::getMean(double dArray[], int iSize) {
double sum = dArray[0];
for (int i = 1; i < iSize; ++i) {
sum += dArray[i];
}
return sum/iSize;
}
double Num::getstanddev(double dArray[], int iSize)
{
cout.setf(ios::fixed); //¿what is this doing here?
cout.setf(ios::showpoint);
cout.precision(5);
double sum_deviation = 0;
int i; //limit the scope of your variables
for ( i = 0; i < iSize; i++ ) //¿why did you create the getMean() function then?
{
sum += dArray[i]; //¿what's sum? ¿where's declared? ¿what's current value?
}
calcAvg = sum / iSize;
for ( i = 0; i < iSize; i++ )
{
sum += pow( dArray[i] - calcAvg, 2 ); //sum does not start in 0 (well, probably)
}
sum_deviation = sqrt( sum / ( iSize - 1 ) );
return sum_deviation;
//missing brace
In getstanddev, sum should be a local variable and it should be initialized to 0. You are probably getting the wrong value because sum is not zero when you call getstanddev()
¿what is this doing here?
-I deleted that part. I wanted only shows the 5 numbers after "."
//limit the scope of your variables.
-I did and set = to 0.
¿why did you create the getMean() function then?
I deleted the mean inside of the getstanddev.
//¿what's sum? ¿where's declared? ¿what's current value?
-I just used the sum of the function mean.
-Now I tried to set sum = to 0. but it is the same.
I don't know if there are important things running from your source and I can't see the order of execution of what you are doing to see if the formula is even correct. So, let's just start with the formula in a few easy steps to calculate standard deviation.
1) Calculate the mean of the list of numbers that you are working with.
2) Then for each number subtract the mean and square the result
3) Take the mean of this new set of numbers
4) Take the square root of the new mean
#include <iostream>
#include <cmath>
#include <vector>
int main()
{
// a sample list of numbers
std::vector<double> numbers = { 1,2,3,4,5 };
// Get the mean of the numbers in the vector
auto sum = 0;
for (auto i : numbers)
sum += i;
auto mean = sum / numbers.size();
// Create a list of the squares of the numers - the mean
std::vector<double> squares;
for (auto i : numbers)
squares.push_back(std::pow((i - mean), 2.0));
// Now take the mean of these numbers
sum = 0;
for (auto i : squares)
sum += i;
mean = sum / squares.size();
// take the square root of the mean of the squares and we have the standard deviation
auto std_dev = std::sqrt(mean);
std::cout << "The standard deviation of 1,2,3,4,5 is: " << std_dev << std::endl;
return 0;
}
It's not the best code, it uses all the built in functions and easy to follow--thus the choice. The variable std_dev will contain 1.4142135623730951 which is correct and you can create whatever precision you'd like.
My first post and I'm unsure of etiquette so I hope this is fitting with the spirit of forum.