[Tutor] puzzled again by decimal module

Bob Gailer bgailer at alum.rpi.edu
Fri Aug 18 23:41:42 CEST 2006


Dick Moores wrote:
> As an exercise that I thought would help me understand the decimal 
> module, I've been trying write a script (precisionFactorial.py) that 
> uses a modified fact(n) to compute precise factorials 
What do you mean by "precise factorials"? Python's long integer should 
handle this just fine.
> [snip]
>   

> # precisionFactorial.py
>
> import decimal
>
> def d(x):
>      return decimal.Decimal(str(x))
>
> def fact(n):
>      product = 1
>      while d(n) > 1:
>          product *= n
>          d(n) -= 1 
>   
 d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since d(n) 
is a function call, which is not valid as as assignment target. Instead 
you should should:

def fact(n):
     product = 1
     dec_n = d(n)
     while dec_n > 1:
         product *= n
         dec_n -= 1 
     return product


[snip]
But as I mentioned there is no value in using decimal here.

-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list