def ramanujan(n, prec=100):
r"""
Approximates the factorial :math:`n!` given an integer :math:`n` using Ramanujan's formula.
Ramanujan's formula is just as or more accurate than several other factorial approximation
formulas.
Parameters
----------
n
Integer to approximate factorial
prec
Defines level of precision for factorials over 100. Default 100. Optional
Returns
-------
int or Decimal
Factorial of :math:`n` as approximated by Ramanujan's formula.
Notes
-----
Ramanujan's formula is another factorial approximation method known for its accuracy
in comparison to other factorial approximation approaches including Stirling's and
Gosper's approximations. Ramanujan's formula is defined as:
.. math::
n! \approx \sqrt{\pi} \left(\frac{n}{e}\right)^n \sqrt[6]{8n^3 + 4n^2 + n + \frac{1}{30}}
Examples
--------
>>> ramanujan(10)
3628800.3116126074
>>> ramanujan(5)
120.00014706585664
References
----------
Mortici, Cristinel. On Gosper's Formula for the Gamma Function. Valahia University of Targoviste,
Department of Mathematics. Retrieved from http://files.ele-math.com/articles/jmi-05-53.pdf
"""
if n != np.floor(n):
n = np.floor(n)
if n >= 100:
with localcontext() as ctx:
ctx.prec = prec
f = Decimal(
np.sqrt(np.pi) * n ** n * np.exp(-n) * (8. * n ** 3. + 4. * n ** 2. + n + 1. / 30.) ** (1. / 6.))
else:
f = np.sqrt(np.pi) * n ** n * np.exp(-n) * (8. * n ** 3. + 4. * n ** 2. + n + (1. / 30.)) ** (1. / 6.)
return f
评论列表
文章目录