module KXI::Math
Public Class Methods
choose(n, k)
click to toggle source
Computes the binomial coefficient @param [Integer] n First (upper) term of coefficient @param [Integer] k Second (lower) term of coefficient @return [Numeric] Binomial coefficient (n choose k)
# File lib/kxi/math/math.rb, line 30 def self.choose(n, k) return pfact(n, k) / fact(n - k) end
fact(n)
click to toggle source
Computes factorial @param [Integer] n Factorial base @return [Integer] Value of factorial
# File lib/kxi/math/math.rb, line 8 def self.fact(n) n <= 0 ? 1 : n * fact(n - 1) end
permutation(n, k)
click to toggle source
Computes the permutation of two numbers @param [Integer] n First term of permutation @param [Integer] k Second term of permutation @return [Numeric] Permutation (k-permutations of n)
# File lib/kxi/math/math.rb, line 38 def self.permutation(n, k) return 0 if k > n pfact(n, n - k) end
pfact(n, m)
click to toggle source
Computes fraction of factorials (!n / !m) @param [Integer] n Factorial base of numerator @param [Integer] m Factorial base of denominator @return [Numeric] Result of fraction
# File lib/kxi/math/math.rb, line 20 def self.pfact(n, m) return 1 if n == m return (1.to_f / lfact(m, m - n)) if m > n return lfact(n, n - m) end
Private Class Methods
lfact(n, l)
click to toggle source
# File lib/kxi/math/math.rb, line 12 def self.lfact(n, l) return (l == 1 or n <= 0) ? n : n * lfact(n - 1, l - 1) end