2017-11-11 4 views
-2

Ich habe ein funktionierendes Programm, um die Standardabweichung vieler Ganzzahlen zu finden. Ich soll jedoch einen Weg finden, die Standardabweichung ohne den Mittelwert zu erhalten.Standardabweichung ohne Mittelwert C++

Ich verstehe die Formel: std dev = sqrt [(B - A^2/N)/N]

wo

A die Summe der Datenwerte ist;

B ist die Summe der quadrierten Datenwerte;

N ist die Anzahl der Datenwerte.

aber wie würde ich das im Code schreiben? Dies ist meine Funktion für die Abweichung aber es nutzt den Mittelwert:

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

'erhalten die Standardabweichung ohne mean' Darf ich fragen, warum? – DimChtz

+0

Hausaufgaben vielleicht? – twoleggedhorse

+1

Sie haben die Summe und die Anzahl. Teilen ..... Komm schon. –

Antwort

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