Browse Source

Improve factorial module and some arc details

pull/2/head
Arthur POULET 4 years ago
parent
commit
4bb139b4f3
No known key found for this signature in database GPG Key ID: FC154EA63FF5D8BC
  1. 9
      src/lib/math/coef_binomial.cr
  2. 12
      src/lib/math/factorial.cr
  3. 4
      src/lib/math/mean.cr
  4. 2
      src/lib/math/std_dev.cr

9
src/lib/math/coef_binomial.cr

@ -4,14 +4,9 @@ require "big_int"
require "./factorial"
module Math
extend self
include Math::Factorial
{% for num_type in [Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, BigInt] %}
# :nodoc:
include Math::Factorial({{num_type}})
{% end %}
# computes the binomial coefficient of (n, k)
# Computes the binomial coefficient of (n, k)
def coef_binomial(n : Int, k : Int)
return 0 if n < 0 || k < 0 || n < k
# puts "n=#{n},k=#{k},n-k=#{n - k}, factorial(#{n})=#{factorial(n)}, (factorial(#{n}) * factorial(#{n - k}))=#{(factorial(k) * factorial(n - k))}"

12
src/lib/math/factorial.cr

@ -1,12 +1,10 @@
module Math
# A factorial(N) = 1x2x3x...xN
module Factorial(U)
extend self
def factorial(n : U)
module Factorial
# A factorial(N) = 1x2x3x...xN
def factorial(n : Number)
raise Math::DomainError.new "The argument must be a natural (out of domain -- factorial)" if n < 0
return U.new(1) if n == 0
return (1..n).to_a.reduce(U.new(1)) { |a, b| a * b }
return (typeof(n)).new(1) if n == 0
return (1..n).to_a.reduce((typeof(n)).new(1)) { |a, b| a * b }
end
end
end

4
src/lib/math/mean.cr

@ -11,3 +11,7 @@ module Math::Mean
Math.sqrt map { |e| e ** 2 }.mean
end
end
module Enumerable(T)
include Math::Mean
end

2
src/lib/math/std_dev.cr

@ -1,8 +1,6 @@
require "./mean"
module Math::StandardDeviation
include Math::Mean
# Squared deviation from the mean
def variance
mean = mean()

Loading…
Cancel
Save