#include <iostream>
using namespace std;
//使用基本方法 DX2= E( (X-EX)2 )
double deviation(int* a, int n){
if (a==NULL || n<1) return -1.0;
int sumX= 0;
double EX=0;
for ( int i= 0; i < n; i++ ){
sumX+= a[i];
}
EX = sumX* 1.0/n;
double sum2= 0.0;
for ( int i= 0; i < n; i++ ){
sum2+= (a[i]-EX)*(a[i]-EX);
}
return sum2/n;
}
//一次遍历,求其方差,公式:DX2= E(X2)-(EX)2
double deviation2(int* a, int n){
if (a==NULL || n<1) return -1.0;
double sumX= 0.0;
double sumX2= 0.0;
for ( int i= 0; i < n; i++ ){
sumX+= a[i];
sumX2+= a[i]*a[i];
}
return sumX2/n- (sumX/n)*(sumX/n);
}
int main()
{
int a[10]= {5,8,12,19,21,87,5,56,7,9};
cout<<deviation(a, 10);
cout<<endl;
cout<<deviation2(a, 10);
system("pause");
return 0;
}