defmodule Growth.Calc.Percentile do
  @moduledoc """
  Convert the z-score of a given measurement into a cumulative percentile.

  This calculation is described in the [cumulative distribution function][https://en.wikipedia.org/wiki/Error_function#Cumulative_distribution_function].

  ## Examples

    iex> z_scores = [-1.0, 0.0, 1.0]
    iex> Enum.map(z_scores, &apply(Growth.Calc.Percentile, :compute, [&1]))
    [0.15865525393145707, 0.5, 0.8413447460685429]

  """

  @doc """
  Convert the z-score of a given measurement into a percentile representation, ranging from 0 to 1.

  ## Examples

    iex> Growth.Calc.Percentile.compute(2.0)
    0.9772498680518208
    iex> Growth.Calc.Percentile.compute(-2.0)
    0.02275013194817921

  """
  @spec compute(number()) :: number()
  def compute(z_score) do
    0.5 * (:math.erf(z_score / :math.sqrt(2)) + 1)
  end
end
