Johnathan Johnathan - 8 months ago 39
Python Question

Python: estimate Pi with trig functions as efficiently as possible

I have an assignment where I need to approximate Pi in a computationally efficient manner. Here is my strategy: I use a unit circle, the angle bisector of an isoceles triangle, and the definition of sin. I drew a diagram:

enter image description here

For example, if I want to use an hexagon (6 points/6 sides), I simply need to compute

) and multiply it by (
). Finally, since
Pi = Circumference/Diameter
, then my approximation of Pi = polygon perimeter (since
Diameter = 1


from math import sin, pi
def computePi(x): #x: number of points desired
p = x*sin(pi/x)


It works, and I think it's as efficient as it gets, no? Thank you for your time!

EDIT: to avoid circularity, I'll compute sin(30) using a Maclaurin series. Then it should work.

Answer Source

Even better is

print(4 * math.atan(1))

This does not use pi in any obvious way in the calculation (though as @Jean-FrançoisFabre comments, pi is probably used in the function definition), and in addition to the trig function it has just one simple multiplication. Of course, there is also

print(2 * math.acos(0))


print(2 * math.asin(1))