Logo

Programming-Idioms

History of Idiom 203 > diff from v9 to v10

Edit summary for version 10 by Francob411:
[Elixir] usage

Version 9

2019-11-02, 17:24:53

Version 10

2019-11-02, 17:27:26

Idiom #203 Calculate mean and standarddeviation

Calculate the mean m and the standard deviation s of the list of floating point values data.

Idiom #203 Calculate mean and standarddeviation

Calculate the mean m and the standard deviation s of the list of floating point values data.

Extra Keywords
avg average variance
Extra Keywords
avg average variance
Code
data = [1,2,3,4]

m = SD.mean(data)
# => 2.5

sd = SD.standard_deviation(data)
# => 1.118033988749895

defmodule SD do
  import Enum, only: [map: 2, sum: 1]
  import :math, only: [sqrt: 1, pow: 2]

  def standard_deviation(data) do
    data
    |> mean
    |> variance(data)
    |> mean
    |> sqrt
  end

  def mean(data) do
    sum(data) / length(data)
  end

  def variance(mean, data) do
    map(data, &pow(&1 - mean, 2))
  end
end








Code
defmodule SD do
  import Enum, only: [map: 2, sum: 1]
  import :math, only: [sqrt: 1, pow: 2]

  def standard_deviation(data) do
    data
    |> mean
    |> variance(data)
    |> mean
    |> sqrt
  end

  def mean(data) do
    sum(data) / length(data)
  end

  def variance(mean, data) do
    map(data, &pow(&1 - mean, 2))
  end
end

# usage
data = [1,2,3,4]
m = SD.mean(data) # => 2.5
sd = SD.standard_deviation(data) # => 1.118033988749895






Comments bubble

Comments bubble
Usage example at the bottom
Doc URL
https://hex.pm/
Doc URL
https://hex.pm/