Module: Math
- Defined in:
- lib/combinatorics/extensions/math.rb
Overview
Class Method Summary collapse
-
.factorial(x = 1) ⇒ Integer
Apply the well-known factorial function to the given Integer.
-
.pi(r) {|i| ... } ⇒ Integer
Pi notation for iterative product computations.
-
.Pi(r) ⇒ Object
CamelCase alias for pi (defined above).
-
.Sigma(r) ⇒ Object
CamelCase alias for sigma (defined above).
-
.sigma(r) {|i| ... } ⇒ Integer
Mathematical summation (invokes a block for k = 1 until ++k = n).
-
.subfactorial(n) ⇒ Integer
Subfactorial function for calculation of derangement cardinalities.
Class Method Details
.factorial(x = 1) ⇒ Integer
The factorial of zero equals one!
Apply the well-known factorial function to the given Integer.
171 172 173 174 175 176 177 |
# File 'lib/combinatorics/extensions/math.rb', line 171 def Math.factorial(x=1) if x >= 1 then pi(1..x) elsif x == 0 then 1 else raise(RangeError,"x must be non-negative") end end |
.pi(r) {|i| ... } ⇒ Integer
Pi notation for iterative product computations.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/combinatorics/extensions/math.rb', line 91 def Math.pi(r) unless r.kind_of?(Range) raise(TypeError,"r must be a Range") end k = 1 if block_given? r.each { |n| k *= yield n } else r.each { |n| k *= n } end k end |
.Pi(r) ⇒ Object
CamelCase alias for pi (defined above)
114 115 116 |
# File 'lib/combinatorics/extensions/math.rb', line 114 def Math.Pi(r) Math.pi(r) end |
.Sigma(r) ⇒ Object
CamelCase alias for sigma (defined above)
60 61 62 |
# File 'lib/combinatorics/extensions/math.rb', line 60 def Math.Sigma(r) Math.sigma(r) end |
.sigma(r) {|i| ... } ⇒ Integer
"chalkboard" notation for summation is the capital Greek letter Sigma.
Mathematical summation (invokes a block for k = 1 until ++k = n).
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/combinatorics/extensions/math.rb', line 37 def Math.sigma(r) unless r.kind_of?(Range) raise(TypeError,"r must be a Range") end k = 0 if block_given? r.each { |n| k += yield n } else r.each { |n| k += n } end k end |
.subfactorial(n) ⇒ Integer
The notation used in academia for subfactorial notation is "!n"
Subfactorial function for calculation of derangement cardinalities.
141 142 143 144 145 146 147 |
# File 'lib/combinatorics/extensions/math.rb', line 141 def Math.subfactorial(n) if n >= 1 then ((Math.factorial(n) + 1) / Math::E).floor elsif n == 0 then 1 else raise(RangeError,"n must be non-negative") end end |