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:
For example, if I want to use an hexagon (6 points/6 sides), I simply need to compute a
:(0.5*sin(2*pi/2*x
) and multiply it by (2*x
). Finally, since Pi = Circumference/Diameter
, then my approximation of Pi = polygon perimeter (since Diameter = 1
).
Essentially:
from math import sin, pi
def computePi(x): #x: number of points desired
p = x*sin(pi/x)
print(p)
computePi(10000)
3.141592601912665
It works, and I think it's as efficient as it gets, no? Thank you for your time!
EDIT: to avoid circularity, I redid it using Archimedes algorithm using only the Pythagorean theroem:
Code:
from math import sqrt
def approxPi(x): #x: number of times you want to recursively apply Archmidedes' algorithm
s = 1 #Unit circle
a = None; b = None;
for i in range(x):
a = sqrt(1 - (s/2)**2)
b = 1 - a
print('The approximate value of Pi using a {:5g}-sided polygon is {:1.8f}'.format(6*2**(i),(s*6*2**(i))/2))
s = sqrt(b**2 + (s/2)**2)
The math library in python has a plethora of trigonometric functions which are enough for performing various trigonometric calculations in just minimal lines of code. These functions can be used after importing the math module or by referencing the math library with the dot operator as follows:
Another fun way that you can get the value of pi in Python is to use the radians () function from the math library. When you pass in 180 as the value for the radian, the function returns the value of pi. While this isn’t the most practical way to get the value of pi, it does work!
Also, as we study in mathematics, pi/2 is 90 degrees and pi/3 is 60 degrees, the math module in python provides a pi constant which represent pi which can be used with the trigonometric function. It returns the cosine of the number (in radians).
Also, as we study in mathematics, pi/2 is 90 degrees and pi/3 is 60 degrees, the math module in python provides a pi constant which represent pi which can be used with the trigonometric function. Time for an Example: In the code example below, we have used the degrees () and radians () methods,
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))
and
print(2 * math.asin(1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With