Skip to content

Instantly share code, notes, and snippets.

@valbeat
Last active October 29, 2016 04:06
Show Gist options
  • Save valbeat/97198753b82900832015 to your computer and use it in GitHub Desktop.
Save valbeat/97198753b82900832015 to your computer and use it in GitHub Desktop.
Vectorの平均値と中央値を求める ref: http://qiita.com/valbeat/items/aaf4721c55e372de3c20
float mean(vector<float> v) {
int size = v.size();
float sum = 0;
for (int i = 0; i < size; i++){
sum += v[i];
}
return sum / size;
}
float median(vector<float> v) {
float size = v.size();
vector<float> _v(v.size());
copy(v.begin(), v.end(), back_inserter(_v));
float tmp;
for (int i = 0; i < size - 1; i++){
for (int j = i + 1; j < size; j++) {
if (_v[i] > _v[j]){
tmp = _v[i];
_v[i] = _v[j];
_v[j] = tmp;
}
}
}
if (size % 2 == 1) {
return _v[(size - 1) / 2];
} else {
return (_v[(size / 2) - 1] + _v[size / 2]) / 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment