View Source Bunch.Math (Bunch v1.6.1)

A bunch of math helper functions.

Summary

Functions

Applies div/2 and rem/2 to arguments and returns results as a tuple.

Works like div_rem/2 but allows to accumulate remainder.

Returns the biggest multiple of value that is lower than or equal to threshold.

Returns the smallest multiple of value that is greater than or equal to threshold.

Functions

Link to this function

div_rem(dividend, divisor)

View Source
@spec div_rem(divident :: non_neg_integer(), divisor :: pos_integer()) ::
  {div :: non_neg_integer(), rem :: non_neg_integer()}

Applies div/2 and rem/2 to arguments and returns results as a tuple.

Example

iex> Bunch.Math.div_rem(10, 4)
{div(10, 4), rem(10, 4)}
Link to this function

div_rem(dividend, divisor, accumulated_remainder)

View Source
@spec div_rem(
  divident :: non_neg_integer(),
  divisor :: pos_integer(),
  accumulated_remainder :: non_neg_integer()
) :: {div :: non_neg_integer(), rem :: non_neg_integer()}

Works like div_rem/2 but allows to accumulate remainder.

Useful when an accumulation of division error is not acceptable, for example when you need to produce chunks of data every second but need to make sure there are 9 chunks per 4 seconds on average. You can calculate div_rem(9, 4), keep the remainder, pass it to subsequent calls and every fourth result will be bigger than others.

Example

iex> 1..10 |> Enum.map_reduce(0, fn _, err ->
...>  Bunch.Math.div_rem(9, 4, err)
...>  end)
{[2, 2, 2, 3, 2, 2, 2, 3, 2, 2], 2}
Link to this function

max_multiple_lte(value, threshold)

View Source
@spec max_multiple_lte(value :: pos_integer(), threshold :: non_neg_integer()) ::
  non_neg_integer()

Returns the biggest multiple of value that is lower than or equal to threshold.

Examples

iex> Bunch.Math.max_multiple_lte(4, 10)
8
iex> Bunch.Math.max_multiple_lte(2, 6)
6
Link to this function

min_multiple_gte(value, threshold)

View Source
@spec min_multiple_gte(value :: pos_integer(), threshold :: non_neg_integer()) ::
  non_neg_integer()

Returns the smallest multiple of value that is greater than or equal to threshold.

Examples

iex> Bunch.Math.min_multiple_gte(4, 10)
12
iex> Bunch.Math.min_multiple_gte(2, 6)
6