2017-11-11 152 views
-2

我有一个功能强大的程序来查找许多整数的标准偏差。但是,我想找到一种方法来获得没有平均值的标准偏差。没有意思的标准偏差C++

我理解的公式为: 标准偏差= SQRT [(B - A^2/N)/ N]

其中

A是数据值的总和;

B是平方数据值的总和;

N是数据值的数量。

但我怎么会写在代码? 这是我对偏差的功能,但它使用的意思是:

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); 

}  
+0

'得到标准差不mean'我可以问为什么? – DimChtz

+0

家庭作业也许? – twoleggedhorse

+1

你有总和和数量。划分.....来吧。 –

回答

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; 
}