Programming-Idioms

Implementation
Ruby

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating resource.

Please try to avoid dependencies to third-party libraries and frameworks.

Implementation edit is for fixing errors and enhancing with metadata.

Instead of changing the code of the snippet, consider creating another Ruby implementation.

Other implementations
math
var
  m, s: double;
  data: array of double;
...
  MeanAndStdDev(data, m, s);
...
real, allocatable :: data(:)
real :: m, s
...
m = sum( data ) / size( data )
s = sqrt( sum( data**2 ) / size( data ) - m**2 )
use Statistics::Lite qw(mean stddev);
my $m = mean @data;
my $s = stddev @data;
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
import statistics
m = statistics.mean(data)
sd = statistics.stdev(data)
mean dat = sum dat / (fromIntegral $ length dat)

stddev dat = sqrt . mean $ map ((**2) . (m -)) dat
  where
    m = mean dat