python decimal library dmath.py v0.3 released

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Mon Mar 3 17:15:39 EST 2014


On Monday, March 3, 2014 9:03:19 PM UTC+1, Mark H. Harris wrote:
> On Monday, March 3, 2014 11:23:13 AM UTC-6, Wolfgang Maier wrote:
> > def fact(x):
> >     """ fact(x)    factorial    {x} int x > 0        
> >
> >     return +Decimal(math.factorial(x)
> > to make it return a Decimal rounded to context precision?
> 
> hi Wolfgang,  I'm not sure.  We're doing some things with very large factorials where (existentially) we want to know how many zeros are coming up and the end of the very large number (thousands of digits) and 2) what are the last significant figures (say twenty of them) that are just before the zero chain.

That's ok, but I do not understand
- why you shouldn't be able to use math.factorial for this purpose and
- why a factorial function accepting and returning ints should be part of your dmath package.

math.factorial is accurate and faster than your pure-Python function, especially for large numbers. Compare:
>>> a = math.factorial(100000)
and your
>>> b = fact(100000)

> What I don't want is for the Decimal module to overflow (didn't know it would do that), and we don't want the number rounded in scientific notation at some number of places. We want to actually see the digits; all of them.

Well, that may be your use-case, but then math.factorial is for you.
On the other hand, you may be interested in getting context-rounded factorials and rounding to context precision is what you'd expect from a Decimal function, so, logically, that's how it should be implemented in your package if you think it needs to have a fact function (which I'm not sure of).

> Python will do multiplications til the proverbial cows come home; well, as long as you don't try it recursively --- killing the recursive depth.

While that's true you pay a heavy price for abusing this feature in terms of performance because with VERY large integers there will be just too much memory shuffling activity. (I haven't looked into how math.factorial handles this internally, but it's certainly performing much better for large numbers than Python integer multiplication.

Best,
Wolfgang



More information about the Python-list mailing list