Last active
October 29, 2016 04:06
-
-
Save valbeat/97198753b82900832015 to your computer and use it in GitHub Desktop.
Vectorの平均値と中央値を求める ref: http://qiita.com/valbeat/items/aaf4721c55e372de3c20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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