Ali Polatel wrote:
The reason for this is that pi() doesn't return anything (hence None). What it does do is print the result (stdout.write). So you can either use it w/o print (just pi(5)) or modify the code so it returns pi all at once instead of printing it as it goes (this will make it seem like it is taking more time since it will have to calculate the whole thing before printing anything, instead of printing the digits one and 4 at a time (I've bolded the changes): def pi(n=1000): # if you set n to -1, nothing will ever be printed because #the loops waits for pi to be calculated before printing anything from decimal import setcontext, getcontext, Decimal, ExtendedContext setcontext(ExtendedContext) # No DvisionByZero Error getcontext().prec = n+1 # always just enough, and this way you can # still perform operations on the results (if you set the precision to # Infinity, it gives you an OverflowError to perform operations) pil = [] printed_decimal = False r = f((1,0,1,1)) while n != 0: if len(r) == 5: pil.append(str(r[4])) if not printed_decimal: pil.append(('.')) printed_decimal = True n -= 1 r = f(r[:4]) return Decimal(''.join(pil)) With Decimal(), you get an accurate string representation of floating point numbers which treats the strings as floating point numbers: >>> pi(20)-3 Decimal("0.1415926535897932384") The only reason the original pi(...) didn't have to deal with this is that it wrote directly to stdout, without formatting the text as string, float, etc. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. |
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
