# [Tutor] puzzled again by decimal module

Dick Moores rdm at rcblue.com
Sat Aug 19 01:10:21 CEST 2006

```At 02:41 PM 8/18/2006, Bob Gailer wrote:
>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.

Well, actually, my old fact(100) produces
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Not exactly correct.

>>[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.
>
>def fact(n):
>     product = 1
>     dec_n = d(n)
>     while dec_n > 1:
>         product *= n
>         dec_n -= 1     return product

Ah, a notation problem. Thanks!

But here's the revised precisionFactorial.py:

========================
# 1precisionFactorial.py

import decimal

def d(x):
return decimal.Decimal(str(x))

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

n = 100
decimal.getcontext().prec = 200
print fact(n)
================================================

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Still not exactly correct! I'm bewildered.

Dick

```