4 ms·
The standard deviation example conflates two questions: 1: Why can't we use standard mathematical notation instead of strings of ASCII? 2: Why do we need lots
by PaulAJ 13y ago
The standard deviation example conflates two questions:
1: Why can't we use standard mathematical notation instead of strings of ASCII?
2: Why do we need lots of control flow and libraries when implementing a mathematical equation as an algorithm.
The first is simple: as others have pointed out here, math notation is too irregular and informal to make a programming language out of it.
The second is more important. In pretty much any programming language I can write:
d = sqrt (b^2 - 4*a*c)
x1 = (-b + d)/(2*a)
x2 = (-b - d)/(2*a)
which is a term-by-term translation of the quadratic equation. But when I want to write this in C++ I need a loop to evaluate the sigma term.
But in Haskell I can write this:
stDev :: [Double] -> Double
stDev xs = sqrt((1/(n-1)) * sum (map (\x -> (x-m)^2)) xs)
where
n = fromIntegral $ length xs
m = sum xs / n
This is a term-by-term translation of the formula, in the same way that the quadratic example was. Just as I use "sqrt" instead of the square root sign I use "sum" instead of sigma and "map" with a lambda expression to capture the internal expression.
Experienced programmers will note that this is an inefficient implementation because it iterates over the list three times, which illustrates the other problem with using mathematics; the most efficient algorithm is often not the most elegant one to write down.