#!/urs/bin/env python3 """ pi_recursive.py Program to recursively calculate pi. @author Richard White @version 2018-03-14 """ import math def recurse(n): """recursively performs a summation that can be used to calculate pi. Maximum recursive depth is 997. """ if n == 1: return 1 else: return 1/(n * n) + recurse(n - 1) def main(): n = int(input("Enter recursion depth: ")) my_pi = math.sqrt(6 * recurse(n)) print("My pi: " + str(my_pi)) print("math.pi: " + str(math.pi)) percent_difference = abs(my_pi - math.pi) / math.pi * 100 print("Percent difference: " + str(percent_difference)) print("The number of iterations to get within 0.1% is 304 (by trial and error)") print("Solving with iteration!") sum = 0 for i in range(n, 0, -1): sum += 1/(i * i) my_new_pi = math.sqrt(6 * sum) print(my_new_pi) percent_difference = abs(my_new_pi - math.pi) / math.pi * 100 print("Percent difference: " + str(percent_difference)) if __name__ == "__main__": main()