Module: Dicey::Mixins::MissingMath Private

Included in:
DistributionCalculators::Binomial
Defined in:
lib/dicey/mixins/missing_math.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Some math functions missing from Math, though without argument range checks.

Class Method Summary collapse

Class Method Details

.combinations(n, k) ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Calculate number of combinations of n elements taken k at a time.

Unlike plain binomial coefficients, combinations are defined as 0 for k > n.

Parameters:

  • n (Integer)

    natural integer

  • k (Integer)

    natural integer

Returns:

  • (Integer)


17
18
19
20
21
22
# File 'lib/dicey/mixins/missing_math.rb', line 17

def combinations(n, k) # rubocop:disable Naming/MethodParameterName
  return 0 if k > n
  return 1 if k.zero? || k == n

  factorial_quo(n, k) / factorial(n - k)
end

.factorial(n) ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Calculate factorial of a natural number.

Parameters:

  • n (Integer)

    natural integer

Returns:

  • (Integer)


28
29
30
# File 'lib/dicey/mixins/missing_math.rb', line 28

def factorial(n) # rubocop:disable Naming/MethodParameterName
  (n < 23) ? Math.gamma(n + 1).to_i : (1..n).reduce(:*)
end

.factorial_quo(n, k) ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Calculate n! / k! where n >= k.

Parameters:

  • n (Integer)

    natural integer

  • k (Integer)

    natural integer

Returns:

  • (Integer)


37
38
39
40
41
# File 'lib/dicey/mixins/missing_math.rb', line 37

def factorial_quo(n, k) # rubocop:disable Naming/MethodParameterName
  return Math.gamma(n + 1).to_i / Math.gamma(k + 1).to_i if n < 23 && k < 23

  ((k + 1)..n).reduce(:*)
end