Skip to content

Instantly share code, notes, and snippets.

@metametaclass
Last active April 10, 2022 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metametaclass/c0602cb64c1fc839666a02dabbb6f5e7 to your computer and use it in GitHub Desktop.
Save metametaclass/c0602cb64c1fc839666a02dabbb6f5e7 to your computer and use it in GitHub Desktop.
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