Python:尽可能高效地使用三角函数估计 Pi

标签 python python-3.x trigonometry

我有一个任务,我需要以一种计算效率高的方式来近似 Pi。这是我的策略:我使用单位圆、等腰三角形的角平分线和 sin 的定义。我画了一个图:

enter image description here

例如,如果我想使用六边形(6 点/6 边),我只需要计算 a:(0.5*sin(2*pi/2*x ) 并将其乘以 (2*x)。最后,由于 Pi = Circumference/Diameter,那么我对 Pi 的近似 = 多边形周长(因为 >直径 = 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

它有效,而且我认为它已经非常高效了,不是吗?感谢您的宝贵时间!

编辑:为了避免循环,我使用仅使用毕达哥拉斯定理的阿基米德算法重做了它:

enter image description here

代码:

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)

最佳答案

更好的是

print(4 * math.atan(1))

这在计算中没有以任何明显的方式使用 pi(尽管正如@Jean-FrançoisFabre 评论的那样,函数定义中可能使用了 pi),并且除了 trig 函数外,它只有一个简单的乘法。当然还有

print(2 * math.acos(0))

print(2 * math.asin(1))

关于Python:尽可能高效地使用三角函数估计 Pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40834088/

相关文章:

python - 多个 python 脚本将消息发送到单个中央脚本

python - 导入错误 : No module named 'requests'

python - Qt Designer 直接从设计器自动调整 tableWidget

ios - 计算大于360度的旋转角度而不是倾斜角度

Java tan 函数未按预期工作

python - “ super ”对象不调用 __getattr__

python - 如何简化 sympy 中的 sqrt 表达式

python - Alien 类没有 rect 属性

python-3.x - 类型错误 : 'headers' is an invalid keyword argument for print()

matlab - 用扭曲的时基拟合正弦波