[Tutor] Problem with default arguments for function

Dick Moores rdm at rcblue.com
Mon Nov 12 00:46:45 CET 2007


I just discovered mpmath 
(<http://code.google.com/p/mpmath/wiki/Documentation>) and am trying 
to write a useful function that uses it to compute factorials. Here's 
what I have:

def fact(n, precision=15, full=False):
     """
     compute n!
     """
     from mpmath import mpf
     if not isinstance(n, int):
         return None
     elif n < 0:
         return None
     n = mpf(n)
     if full:
         precision = n * 10   # ensures that for n < 1 billion, 
product will not be in scientific notation (i.e., no '+')
     mpf.dps = precision
     product = mpf(1)
     while n > mpf(1):
         product *= n
         n -= 1
     if '+' in str(product):
         return product
     else:
         return int(str(product)[:-2])      #  product is a float, 
ending in '.0', so this needs to be removed and string converted to int.

The code is also at <http://python.pastebin.com/m33d52d54>.

And a couple of example uses that illustrate my problem:

# 1 (precision default overridden and set to 20; full left at default of False)
 >>> print fact(50, 20)
3.0414093201713378044e+64

# 2 (both precision and full left at their defaults)
 >>> print fact(50)
3.04140932017134e+64

# 3 (full set to True, forcing precision to be specified--but 
irrelevant what it is set to)
 >>> print fact(50, 3, True)
30414093201713378043612608166064768844377641568960512000000000000

# 4 (see # 3)
 >>> print fact(50, 30, True)
30414093201713378043612608166064768844377641568960512000000000000

And if the function is rewritten as def fact(n, full=False, precision=15)
there would be the analogous problem involving full.

Is there a way to solve this problem of the unnecessary setting of 
the 2nd argument?

Thanks,

Dick Moores



More information about the Tutor mailing list