Advertisement
jabela

Pi recursive

Mar 20th, 2024
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. """
  2. The Leibniz formula for π is as follows:
  3. π = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - ...)
  4.  
  5. More info at:
  6. https://www.cuemath.com/calculus/leibniz-rule/
  7.  
  8. Watch out Python will throw an error at a key point.
  9. """
  10.  
  11. def calculate_pi(n, i=1, sum=0, sign=1):
  12.     if n == 0:
  13.         return 4 * sum
  14.     else:
  15.         term = sign * (1 / i)
  16.         print(term)
  17.         return calculate_pi(n - 1, i + 2, sum + term, -sign)
  18.  
  19. # Test the function
  20. approx_pi = calculate_pi(800)  # Increase the number of iterations for a more accurate result
  21. print(approx_pi)
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement