summaryrefslogtreecommitdiff
path: root/stddev.cpp
blob: e3ce623b17e6b1026e3bb1df3c47a7b6a91ca497 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cctype>

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;

	bool warned=false;

	double total=0;
	string word;
	while(true){
		cin>>word;
		double v;
		if(!cin)break;
		const char *start=word.c_str();
		char *endp;
		v=strtod(start,&endp);
		if(endp!=start+word.size()||!isfinite(v)){
			if(!warned){
				warned=true;
				cerr<<"Warning: invalid floating-point values detected"<<endl;
			}
			continue;
		}
		data.push_back(v);
		total+=v;
	}
	if(data.size()==0){
		cerr<<"No data"<<endl;
		return 0;
	}

	sort(data.begin(),data.end());

	const double s_count=data.size();
	const double s_mean=total/data.size();
	const double s_median=data[data.size()/2];
	const double s_min=data[0];
	const double s_max=data[data.size()-1];

	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));
	const double s_stderr=s_stddev/sqrt(data.size());

	cout<<"Count:  "<<s_count<<'\n'
	    <<"Mean:   "<<s_mean<<'\n'
	    <<"Stddev: "<<s_stddev<<'\n'
	    <<"Stderr: "<<s_stderr<<'\n'
	    <<"Median: "<<s_median<<'\n'
	    <<"Range:  ["<<s_min<<","<<s_max<<"]"<<endl;
}