Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
var m = data.Average();
var s = CalculateStdDev(data);
float CalculateStdDev(IEnumerable<float> values)
{
double ret = 0;
if (values.Count() > 0)
{
double avg = values.Average();
double sum = values.Sum(d => Math.Pow(d - avg, 2));
ret = Math.Sqrt((sum) / values.Count()-1);
}
return (float)ret;
}
defmodule SD do
import Enum, only: [map: 2, sum: 1]
import :math, only: [sqrt: 1, pow: 2]
def standard_deviation(data) do
m = mean(data)
data |> variance(m) |> mean |> sqrt
end
def mean(data) do
sum(data) / length(data)
end
def variance(data, mean) do
for n <- data, do: pow(n - mean, 2)
end
end
# usage
data = [1,2,3,4]
m = SD.mean(data) # => 2.5
sd = SD.standard_deviation(data) # => 1.118033988749895
Usage example at the bottom
real, allocatable :: data(:)
real :: m, s
...
m = sum( data ) / size( data )
s = sqrt( sum( data**2 ) / size( data ) - m**2 )
data may be a multidimensional array (e.g. data(:,:)).
mean dat = sum dat / (fromIntegral $ length dat)
stddev dat = sqrt . mean $ map ((**2) . (m -)) dat
where
m = mean dat
data is a keyword in Haskell, so I'm using dat instead.
This solution is not very memory efficient on long, lazily-computed lists. If you're dealing with one of those, you might want to write a recursive version instead.
This solution is not very memory efficient on long, lazily-computed lists. If you're dealing with one of those, you might want to write a recursive version instead.
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
import static java.util.stream.DoubleStream.of;
int n = data.length;
double m = of(data).sum() / n,
s = of(data).map(x -> pow(x - m, 2)).sum();
s = sqrt(s / n);
m = data.sum / data.length.to_f
sd = Math.sqrt data.sum { |n| (m-n)**2 } / data.length.to_f
.to_f forces floating point
let sum: f64 = data.iter().sum();
let m = sum / (data.len() as f64);
let sum_of_squares: f64 = data.iter().map(|item| (item - m) * (item - m)).sum();
let s = (sum_of_squares / (list.len() as f64)).sqrt();