summaryrefslogtreecommitdiff
path: root/stddev.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'stddev.cpp')
-rw-r--r--stddev.cpp47
1 files changed, 47 insertions, 0 deletions
diff --git a/stddev.cpp b/stddev.cpp
new file mode 100644
index 0000000..c804bf3
--- /dev/null
+++ b/stddev.cpp
@@ -0,0 +1,47 @@
+#include <iostream>
+#include <vector>
+#include <cmath>
+
+using namespace std;
+
+const char *argv0;
+
+void usage(){
+ cerr<<"Usage: "<<argv0<<endl
+ <<"Prints some statistical information about the data on stdin."<<endl
+ <<"Data is assumed to be a list of floating-point values."<<endl;
+}
+
+int main(int,char **argv){
+ argv0=argv[0];
+
+ vector<double> data;
+
+ double total=0;
+ while(true){
+ double v;
+ cin>>v;
+ if(!cin)break;
+ data.push_back(v);
+ total+=v;
+ }
+ if(data.size()==0){
+ cerr<<"No data"<<endl;
+ return 0;
+ }
+
+ sort(data.begin(),data.end());
+
+ const double s_mean=total/data.size();
+ const double s_mode=data[data.size()/2];
+
+ total=0;
+ for(double v : data){
+ total+=(v-s_mean)*(v-s_mean);
+ }
+ const double s_stddev=data.size()==1?nan(""):sqrt(total/(data.size()-1));
+
+ cout<<"Mean: "<<s_mean<<endl
+ <<"Stddev: "<<s_stddev<<endl
+ <<"Mode: "<<s_mode<<endl;
+}