11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vectorの平均値と中央値を求める

Last updated at Posted at 2015-12-19

##平均値の求め方
合計して要素の数で割る

mean.cpp
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;
}

##中央値の求め方
要素の値でソートして中央の要素を返す
要素の数が偶数だったら中央2つの平均を返す

median.cpp
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;
    }
}
11
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?