Last active
April 10, 2022 09:22
-
-
Save metametaclass/c0602cb64c1fc839666a02dabbb6f5e7 to your computer and use it in GitHub Desktop.
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
template <class Iterator> | |
typename std::iterator_traits<Iterator>::value_type stddev(Iterator first, Iterator last) | |
{ | |
using U = typename std::iterator_traits<Iterator>::value_type; | |
U M, Mnew; | |
U S, Snew; | |
int count = 0; | |
for (auto it = first; it != last; ++it) { | |
auto v = * it; | |
if (it == first) { | |
M = Mnew = v; | |
S = U{}; | |
} else { | |
Mnew = M + (v - M) / count; | |
Snew = S + (v - M) * (v - Mnew); | |
M = Mnew; | |
S = Snew; | |
} | |
count++; | |
} | |
if (count > 1) { | |
double variance = Snew / (count - 1); | |
return std::sqrt(variance); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment