In: Computer Science
on python 3.6:
Write a program that will quickly estimate pi to a precision of 1e-4 using Archimedes approach of averaging polygon perimeters. Your program should employ a loop where the number of sides of the polygon are increased each iteration until the absolute value of the difference between the current estimate and the previous estimate is less than 1e-4. l. The program should output the estimate of pi and the number of iterations needed to reach the desired level of precision.
the code for the finding pi using the Archimedes approach is:
numside_ins=float(input(enter the number of sides of the inscribed polygon))
numside_cis=float(input(enter the number of sides of the circumscribed polygon))
diameter= 1
length_ins= 2*(diameter/2)*sin(pi/numside_ins)
peri_ins= numside_ins*length_ins
length_cir= 2*(diameter/2)*tan(pi/numside_cir)
peri_cir = numside_cir * length_cir
ave_peri=((peri_cir + peri_ins) / 2)
found_pi= ave_peri/diameter
print(found_pi)
from math import sin,pi,tan
numside_ins=2
numside_cir=2
diameter= 1
length_ins= 2*(diameter/2)*sin(pi/numside_ins)
peri_ins= numside_ins*length_ins
length_cir= 2*(diameter/2)*tan(pi/numside_cir)
peri_cir = numside_cir * length_cir
ave_peri=((peri_cir + peri_ins) / 2)
currentEstimate = ave_peri/diameter
iterations=1
while True:
numside_ins+=1
numside_cir+=1
diameter= 1
length_ins= 2*(diameter/2)*sin(pi/numside_ins)
peri_ins= numside_ins*length_ins
length_cir= 2*(diameter/2)*tan(pi/numside_cir)
peri_cir = numside_cir * length_cir
ave_peri=((peri_cir + peri_ins) / 2)
previousEstimate = currentEstimate
currentEstimate = ave_peri/diameter
iterations+=1
if abs(currentEstimate-previousEstimate)<1e-4:
break
print('Estimate of pi:',currentEstimate)
print('Number of iterations:',iterations)