[Tutor] how to handle big numbers

Peter Otten __peter__ at web.de
Sat Dec 10 16:37:31 CET 2011


lina wrote:

> On Sat, Dec 10, 2011 at 6:09 PM, Peter Otten <__peter__ at web.de> wrote:
>> surya k wrote:
>>
>>> Finding factorial of 8 or 9 isn't big. If I would like to find factorial
>>> of 32327, how can I ?
>>
>> gmpy is a library designed for working with large numbers. Compare:
>>
>>>>> import time
>>>>> def bench(f, *args):
>> ...     start = time.time()
>> ...     try:
>> ...             return f(*args)
>> ...     finally:
>> ...             print time.time() - start
>> ...
>>>>> def fac(n):
>> ...     f = 1
>> ...     for i in xrange(1, n+1):
>> ...             f *= i
>> ...     return f
>> ...
> 
> sorry to interrupt, I tried your example,
> 
> $ cat time_func.py
> #!/usr/bin/python3
> 
> import time
> 
> def bench(f, *args):
>     start = time.time()
>     try:
>         return f(*args)
>     finally:
>         print(time.time() - start)
> 
> def fac(n):
>     f = 1
>     for i in range(1,n+1):
>         f *= i
>     return f
> 
> on idle3
> 
>>>> import time_func
>>>> time_func.bench(time_func.fac,1000)
> 0.0015549659729003906
> 402...[snip many digits]...000
> 
> why the output so long,

bench() calls the function passed as its first argument with the arguments 
that follow, prints the time this function takes and returns the result of 
the function call. In the case of

bench(fac, 1000)

that result is fac(1000), or 1*2*3*4*...*997*998*999*1000 -- a number with
2568 digits. To avoid printing out these huge numbers I assigned them to x

>>>>> x = bench(fac, 1000)
>> 0.00276589393616

Therfore you only see the time in seconds which is printed rather than 
returned by bench().



More information about the Tutor mailing list