## Programming Tips - C/C++: Calculate Mean Deviation

Date: 2021feb16 Language: C/C++ Q. C/C++: Calculate Mean Deviation A. Here is a small example program
#include <vector> #include <math.h> #include <stdio.h> typedef std::vector<float> Numbers; float Total(const Numbers &numbers) { float total = 0; for (Numbers::const_iterator it = numbers.begin(); it != numbers.end(); it++) { total += *it; } return total; } float Size(const Numbers &numbers) { return (float)numbers.size(); } float Mean(const Numbers &numbers) { return Total(numbers) / Size(numbers); } float MeanDeviation(const Numbers &numbers) { const float mean = Mean(numbers); float totalDeviation = 0; for (Numbers::const_iterator it = numbers.begin(); it != numbers.end(); it++) { totalDeviation += fabs(mean - *it); } return totalDeviation / Size(numbers); } int main() { Numbers numbers; numbers.push_back(3); numbers.push_back(6); numbers.push_back(6); numbers.push_back(7); numbers.push_back(8); numbers.push_back(11); numbers.push_back(15); numbers.push_back(16); const float mdev = MeanDeviation(numbers); printf("mdev=%f\n", mdev); }