On Thu, 16 Sept 2021 at 19:34, Jonatan <pybots...@gmail.com> wrote: > Currently, math.factorial only supports integers and not floats, whereas > the "mathematical" version supports both integers and floats. > I.e: > ``` > import math > > > def better_factorial(n): > return n * math.gamma(n) > > print(math.factorial(10) == better_factorial(10)) > ``` > > This ends up in `True`, as that's correct. > However, `math.factorial(math.pi)` (for example, or any float) > Ends up in `ValueError: factorial() only accepts integral values`. > unlike `better_factorial(math.pi)` which would end up in 7.188082728976031. > > My proposal is to make another function for floats, or even use the same > math.factorial function and check inside it whether the given input is an > integer or a float object. >
SymPy has a symbolic factorial function that does this: >>> import sympy as sym >>> sym.factorial(10) 3628800 >>> sym.factorial(0.5) 0.886226925452758 If you pass in exact rational input then you can compute the result to any desired precision: >>> sym.factorial(sym.Rational(1, 2)) factorial(1/2) >>> sym.factorial(sym.Rational(1, 2)).evalf(60) 0.886226925452758013649083741670572591398774728061193564106904 Doing the same with integer values requires using evaluate=False to avoid the potentially slow exact integer calculation: >>> sym.factorial(20) 2432902008176640000 >>> sym.factorial(20, evaluate=False) factorial(20) >>> sym.factorial(20, evaluate=False).evalf(10) 2.432902008e+18 >>> sym.factorial(10**30, evaluate=False).evalf(10) 6.223112323e+29565705518096748172348871081098 https://docs.sympy.org/latest/modules/functions/combinatorial.html#factorial The floating point calculations are computed by mpmath under the hood which can also be used directly: https://mpmath.org/doc/current/functions/gamma.html#factorial-fac -- Oscar
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/6PJ3N24Y2CNZYRRTPOJ6CJXUCIAIRHBG/ Code of Conduct: http://python.org/psf/codeofconduct/