by sold · 12y ago · 0 comments
def stddev(x):
avg = sum(x)/len(x)
return sqrt(sum((xi-avg)**2 for xi in x) / len(x))
stddev xs = let avg = sum xs / length xs
in sqrt $ sum [(x-avg)**2 | x <- xs] / length xs #include <valarray>
#include <iostream>
double standard_dev(const std::valarray<double> &vals)
{
return sqrt(pow(vals - (vals.sum() / vals.size()), 2).sum() / vals.size());
}
int main()
{
std::cout << standard_dev({2, 4, 4, 4, 5, 5, 7, 8}) << '\n';
}
…and none of those are really much less readable than the math version. All in all, that "example" clearly wasn't made in good faith, and left a bad taste in my mouth.My personal opinion is that rather than trying to make programming more like math, we should make math more like programming - such that we stop assuming the reader has some magical knowledge needed to understand it.