Joh*_*han 5 python trigonometry python-3.x
我有一个任务,我需要以计算有效的方式近似Pi.这是我的策略:我使用单位圆,等角三角形的角平分线,以及罪的定义.我画了一张图:
例如,如果我想使用六边形(6点/ 6边),我只需要计算a:( 0.5*sin(2*pi/2*x)并乘以(2*x).最后,因为Pi = Circumference/Diameter,然后我的近似Pi =多边形周长(因为Diameter = 1).
实质上:
from math import sin, pi
def computePi(x): #x: number of points desired
p = x*sin(pi/x)
print(p)
computePi(10000)
3.141592601912665
Run Code Online (Sandbox Code Playgroud)
它有效,我觉得它有效率,不是吗?感谢您的时间!
编辑:为了避免圆形,我使用阿基米德算法仅使用毕达哥拉斯理论重新编写:
码:
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)
Run Code Online (Sandbox Code Playgroud)
更好的是
print(4 * math.atan(1))
Run Code Online (Sandbox Code Playgroud)
这在计算中没有以任何明显的方式使用pi(虽然@ Jean-FrançoisFabre注释,pi可能在函数定义中使用),并且除了trig函数之外它只有一个简单的乘法.当然,也有
print(2 * math.acos(0))
Run Code Online (Sandbox Code Playgroud)
和
print(2 * math.asin(1))
Run Code Online (Sandbox Code Playgroud)