Logo

Programming-Idioms

History of Idiom 203 > diff from v14 to v15

Edit summary for version 15 by programming-idioms.org:
[Elixir] Removed newlines

Version 14

2020-04-29, 00:19:31

Version 15

2020-05-10, 21:34:53

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.

Variables
m,s,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
    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






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/