Fast Factorial Approximations
Join the DZone community and get the full member experience.
Join For FreeChoose and factorial algorithms
# choose and factorial were stolen from:
# http://bluebones.net/2007/09/combinatorics-in-ruby/
def choose(m)
self.factorial / (m.factorial * (self - m).factorial)
end
def factorial
(2..self).inject(1) { |f, n| f * n }
end
def fastchoose(m)
self.gosper / (m.to_f.gosper * (self - m).gosper)
end
# quick, accurate approximation to factorial
# gleaned from http://mathworld.wolfram.com/StirlingsApproximation.html
def gosper
Math.sqrt( ((2*self) + (1.0/3))*Math::PI ) * ((self/Math::E)**self).round
end
def stirling
Math::E ** (self*Math.log(self) - self)
end
Opinions expressed by DZone contributors are their own.
Comments