Logo

Programming-Idioms

History of Idiom 203 > diff from v11 to v12

Edit summary for version 12 by Francob411:
[Elixir] readability

Version 11

2019-11-02, 17:37:16

Version 12

2019-11-02, 17:43:45

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






Code
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






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