0

please go easy on me, I've been learning Python about a week! I thought I'd try calculating Pi using the Rumanujan formula. I am confident I was able to code that correctly. My answer is truncating and I'd like it to be represented with 200 dp. In C I'd use malloc to do this perhaps but I understand that Python doesn't work that way. The learning point I'd like to take away from this is: Is the truncation caused by the limit of representing a float, and if so is it possible to fix?

Thanks.

import math
from decimal import *

getcontext().prec = 200
def iterate(n):
    sum = 0
    Decimal(sum)
    sum = (math.factorial(4*n))
    sum = (sum/math.pow(math.factorial(n), 4))
    sum = sum*((26390*n +1103)/math.pow(396, (4*n)))
    return sum
ans=0
Decimal(ans)    
print "Choose the number of iterations:\n"
itnum = int(raw_input())

for n in range (0, itnum+1):
    this_iteration = 0
    Decimal(this_iteration)
    this_iteration = iterate(n)
    ans = ans + this_iteration

ans =  ans*(math.pow(8, 0.5)/9801)
ans = 1/ans
print "%.200f" % ans

1 Answers1

0

Your snippet

sum = 0
Decimal(sum)

leaves sum set to the int 0, and computes and throws away a Decimal equivalent. Use, instead, an assignment statement:

sum = Decimal(0)

Next, you'll need to ensure every intermediate result is also converted appropriately to Decimal (and floats by default are not).

Personally, I'd recommend using gmpy2 instead, but then, I'm biased:-).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395