Python编程计算π的值(π的计算的python程序)
求解Python二级题目
Python二级题目,该题要求根据给出的等式求π值。我们可以利用for循环或while循环着手来解决:
1、加载数学模块
import math
2、初始化,即s=0
3、利用for循环语句,从1到100000进行叠加计算
for i in range(1,100001): # i 循环从1递增到100000
4、计算1/n2值,即
s= s+1/(i**2);
5、计算π值,即
Pi=math.sqrt(6*s);
6、显示循环次数,即
print("n:",i)
7、显示π值,即
print("π值:",Pi)
现代计算机是如何计算圆周率的?
可以用编程语言计算。以下是python语言
pi = 0.0
N = 100
for i in range(N):
pi += (1/pow(16,i) * (? 4/(8*i +1) -2/(8*i+4)-1/(8*i+5) -1/(8*i +6) )? ?)
print('圆周率为{:.10f}'.format(pi))
请把以上代码拷进python语言开发环境里运行,结果如下(下图是使用python开发环境Spyder运行上述代码的结果):圆周率为3.1415926536
扩展资料
电子计算机的出现使π值计算有了突飞猛进的发展。1949年,美国制造的世上首部电脑-ENIAC(ElectronicNumerical Integrator And Computer)在阿伯丁试验场启用了。次年,里特韦斯纳、冯纽曼和梅卓普利斯利用这部电脑,计算出π的2037个小数位。
这部电脑只用了70小时就完成了这项工作,扣除插入打孔卡所花的时间,等于平均两分钟算出一位数。五年后,IBM NORC(海军兵器研究计算机)只用了13分钟,就算出π的3089个小数位。
参考资料:百度百科——圆周率
python如何计算π
#coding=utf-8
'''
Created?on?2014-11-04
@author:?Neo
'''
import?sys
import?math
from?decimal?import?*
??
def?bbp(n):
????pi=Decimal(0)
????k=0
????while?k??n:
????????pi+=(Decimal(1)/(16**k))*((Decimal(4)/(8*k+1))-(Decimal(2)/(8*k+4))-(Decimal(1)/(8*k+5))-(Decimal(1)/(8*k+6)))
????????k+=1
????return?pi
??
def?main(argv):
????if?len(argv)?!=2:
????????exit('Usage:?BaileyBorweinPlouffe.py?prec?n')
??????????
????getcontext().prec=(int(sys.argv[1]))
????my_pi=bbp(int(sys.argv[2]))
????accuracy=100*(Decimal(math.pi)-my_pi)/my_pi
??
????print?"Pi?is?approximately?"+str(my_pi)
????print?"Accuracy?with?math.pi:?"+str(accuracy)
??????
if?__name__=="__main__":
????main(sys.argv[1:])
result:
d:\workspace\PyDemopython test.py 10 10
Pi is approximately 3.141592653
Accuracy with math.pi: 1.877369797E-8
d:\workspace\PyDemopython test.py 25 25
Pi is approximately 3.141592653589793238462644
Accuracy with math.pi: -3.898171852150198570978563E-15
d:\workspace\PyDemopython test.py 40 40
Pi is approximately 3.141592653589793238462643383279502884195
Accuracy with math.pi: -3.898171832519375446564294863483061824361E-15
d:\workspace\PyDemo
Python语言编程。根据BBP公式计算π,k=0~100?
pi = 0
N = 100
for k in range(N):
pi += 1/pow(16,k) * (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6))
print("圆周率值是:{}".format(pi))