R = RealField(2000) #Using the RealField, I can choose the number of decimal points for my answers def Chudnovsky(n): """ A function to simulate the Chudnovsky algorithm for pi approximation, consisting mainly of a sum from 0 to the iteration argument n. For clarity, I have seperated parts of the quotient into variables x and y. Argument n is an integer. Output will be a float """ k = var('k') x = ((-1)**k * factorial(6*k) * (13591409 + 545140134 * k)) y = (factorial(3*k) * (factorial(k))**3 * (640320 ** (3 * k + 3/2))) a = R(sum(x / y, k, 0, n)) return R(1 / (12 * a))
listington = [] #An empty list to be appended with values of correct decimal places for a bar chart rohanna = [['Iterations','Decimal Places']] #rohanna is defined as a list of lists to be written to a csv file. #The first list in rohanna contains the titles of the columns for i in range(7): """ The following for loop iterates the function and finds the absolute difference between the approximation and pi. The number is then converted into a string, then converted into a list of its elements. """ a = R(abs(Chudnovsky(i) - pi)) numlist = [x for x in str(a)] b = numlist[604:606] #Since the number is in standard form, the last two elements of the list gives us the number of decimal places intlist = [int(x) for x in b] c = intlist[0] * 10 + intlist[1] - 1 #The coding is rather shoddy I'm afraid listington.append(c) rohanna.append([i, c]) for i in range(7, 31): """ At a certain point, the number that follows e in standard form reaches three digits, and thus the only method I found that worked was creating a new for loop. """ a = R(abs(Chudnovsky(i) - pi)) numlist = [x for x in str(a)] b = numlist[604:607] intlist = [int(x) for x in b] c = intlist[0] * 100 + intlist[1] * 10 + intlist[2] - 1 listington.append(c) rohanna.append([i, c])
#By using the list that only has the accuracy, I can draw a bar graph to show the continuity. f = bar_chart(listington, ymin = 0, color = ('purple')) f.save('BarChart.png')
#With the second list, I can use it to write a csv file of the data. import csv file = open('decimalpoints.csv', 'w') a = csv.writer(file) a.writerows(rohanna) file.close()