Last active
November 16, 2023 11:44
-
-
Save juanfal/d57d94a7e5777ed43fd16d838593f0cf to your computer and use it in GitHub Desktop.
stats mean min max stdev
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
// t9e12.stats.cpp | |
// juanfc 2023-11-14 | |
// | |
#include <iostream> | |
#include <cmath> | |
#include <array> | |
using namespace std; | |
// consts | |
const int N=5; | |
// types | |
typedef array<float,N> TVec; | |
// prototypes | |
void writeArr(TVec a); | |
void stats(TVec a, | |
float& mean, float& min, | |
float& max, float& stdev); | |
int main() | |
{ | |
float mean, min, max, stdev; | |
TVec a = {{1, 2, 3, 4, 5}}; | |
writeArr(a); cout << endl; | |
stats(a, mean, min, max, stdev); | |
cout << "mean: " << mean << endl; // 3 | |
cout << "min: " << min << endl; // 1 | |
cout << "max: " << max << endl; // 5 | |
cout << "std dev: " << stdev << endl; // 1.58114 | |
return 0; | |
} | |
void stats(TVec a, | |
float& mean, float& min, | |
float& max, float& stdev) | |
{ | |
mean = 0; | |
float sa2 = 0, sa = 0; | |
min = max = a[0]; | |
for (int i = 0; i < N; ++i) { | |
mean += a[i]; | |
sa += a[i]; | |
sa2 += a[i]*a[i]; | |
if (a[i] < min) min = a[i]; | |
else if (a[i] > max) max = a[i]; | |
} | |
mean /= N; | |
stdev = sqrt((sa2-sa*sa/N)/(N-1)); | |
} | |
void writeArr(TVec a) | |
{ | |
for (int i = 0; i < N; ++i) | |
cout << a[i] << " "; | |
} | |
void swap(int& a, int& b) | |
{ | |
int t = a; | |
a = b; b = t; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment