Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.

The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.

Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.



Test case

Use this to compute the standard deviation of this demonstration set, 



{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}


{\displaystyle \{2,4,4,4,5,5,7,9\}}

, which is 



2


{\displaystyle 2}

.



Related tasks

 Random numbers


Tasks for calculating statistical measures



in one go
moving (sliding window)
moving (cumulative)

Mean
Arithmetic

Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means


Averages/Simple moving average




Geometric

Averages/Pythagorean means




Harmonic

Averages/Pythagorean means




Quadratic

Averages/Root mean square




Circular

Averages/Mean angle
Averages/Mean time of day




Median

Averages/Median




Mode

Averages/Mode




Standard deviation

Statistics/Basic



Cumulative standard deviation




defmodule Standard_deviation do
  def add_sample( pid, n ), do: send( pid, {:add, n} )
 
  def create, do: spawn_link( fn -> loop( [] ) end )
 
  def destroy( pid ), do: send( pid, :stop )
 
  def get( pid ) do
    send( pid, {:get, self()} )
    receive do
      { :get, value, _pid } -> value
    end
  end
 
  def task do
    pid = create()
    for x <- [2,4,4,4,5,5,7,9], do: add_print( pid, x, add_sample(pid, x) )
    destroy( pid )
  end
 
  defp add_print( pid, n, _add ) do
    IO.puts "Standard deviation #{ get(pid) } when adding #{ n }"
  end
 
  defp loop( ns ) do
    receive do
      {:add, n} -> loop( [n | ns] )
      {:get, pid} ->
        send( pid, {:get, loop_calculate( ns ), self()} )
        loop( ns )
      :stop -> :ok
    end
  end
 
  defp loop_calculate( ns ) do
    average = loop_calculate_average( ns )
    :math.sqrt( loop_calculate_average( for x <- ns, do: :math.pow(x - average, 2) ) )
  end
 
  defp loop_calculate_average( ns ), do: Enum.sum( ns ) / length( ns )
end
 
Standard_deviation.task