Python:尽可能有效地使用三角函数估计 Pi [英] Python: estimate Pi with trig functions as efficiently as possible

查看:52
本文介绍了Python:尽可能有效地使用三角函数估计 Pi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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).

本质上:

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!

为了避免循环,我使用阿基米德算法只使用了勾股定理:

to avoid circularity, I redid it using Archimedes algorithm using only the Pythagorean theroem:

代码:

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 可能在函数定义中使用),并且除了三角函数之外,它只有一个简单的乘法.当然,还有

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))

这篇关于Python:尽可能有效地使用三角函数估计 Pi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆