Logo

Programming-Idioms

History of Idiom 203 > diff from v10 to v11

Edit summary for version 11 by Francob411:
[Elixir] added list comprehension

Version 10

2019-11-02, 17:27:26

Version 11

2019-11-02, 17:37:16

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
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






Code
defmodule SD do
  import Enum, only: [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
    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






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