title: Exercise 7.3 Think Python book
body: <blockquote>
    <p>The mathematician Srinivasa Ramanujan found an inﬁnite series that can
    be used to generate a numerical approximation of 1/π:</p>
    
    <p><a href="https://i.stack.imgur.com/XWzam.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XWzam.png" alt="enter image description here"></a></p>
    
    <p>Write a function called estimate_pi that uses this formula to compute
    and return an estimate of π. It should use a while loop to compute
    terms of the summation until the last term is smaller than 1e-15
    (which is Python notation for 10**−15). You can check the result by
    comparing it to math.pi.</p>
  </blockquote>
  
  <p>Although both my solution and the correct answer(which I found in internet) are similar logically, but I don't understand why my factorial function does't work properly for this question. (It traps on an infinite loop when I use it in the calculation of pi.) When I check my factorial function separately it works correctly but only for this question it seems I must follow different structure.</p>
  
  <p>My code:</p>
  
  <pre><code>import math
  
  def fact(n):
  
      if n == 0:
          return 1
      else:
          return (n * fact(n - 1))        
  
  
  
  k = 0
  result = 0
  
  while True:
  
      result = result + ( ( fact(4*k)*(1103 + 26390*k))    /    ((fact(k)**4) 
  * (396 ** (4*k))) )
  
      if abs(result) &lt; 1e-15:
          break
  
      k = k + 1
  
  print ("result = ", (2 * math.sqrt(2) / 9801) * result)
  print("pi = ",math.pi)
  </code></pre>
  
  <p>correct one:</p>
  
  <pre><code>import math
  
  def fact(n):
  
      if n == 0:
          return 1
      else:
          recurse = fact(n-1)
          result = n * recurse
          return result
  
  
  
  
  k = 0
  result = 0
  
  while True:
  
      result = result + ( ( fact(4*k)*(1103 + 26390*k))    /    ((fact(k)**4) 
  * (396 ** (4*k))) )
  
      if abs(result) &lt; 1e-15:
          break
  
      k = k + 1
  
  print ("result = ", (2 * math.sqrt(2) / 9801) * result)
  print("pi = ",math.pi)
  </code></pre>