pi = 0
sign = 1
for i in range(1, 201, 2):
pi += sign * (1 / i)
sign *= -1
pi *= 4
print("π的值为:", pi)
解释:
首先定义变量pi和sign,分别表示π的值轿局和正负号。然后使明核用for循环计算公式的前100项,每次加上一个数(或减去一个数),并更新正负号。最后将计算结果乘以4,即可得到π的激帆掘值。最后使用print语句输出π的值。
需要注意的是,由于计算机浮点数精度的限制,这个方法计算出来的π值可能不够精确。如果需要更高精度的计算,可以使用一些特殊的数值库或算法。
#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\PyDemo>python test.py 10 10
Pi is approximately 3.141592653
Accuracy with math.pi: 1.877369797E-8
d:\workspace\PyDemo>python test.py 25 25
Pi is approximately 3.141592653589793238462644
Accuracy with math.pi: -3.898171852150198570978563E-15
d:\workspace\PyDemo>python test.py 40 40
Pi is approximately 3.141592653589793238462643383279502884195
Accuracy with math.pi: -3.898171832519375446564294863483061824361E-15
d:\workspace\PyDemo>
Python二级题目,该题要求根据给出的等式求π值。我们可以利用for循环或while循环着手来解决:
1、加载数学模块
import math
2、初始化,即s=0
3、利用for循环语句,从1到100000进行叠加计算
for i in range(1,100001): # i 循环迹槐从1递增到100000
4、计算1/n²值,即
s= s+1/(i**2)
5、计姿尺友算π值,即
Pi=math.sqrt(6*s)
6、显示循环次数,即
print("n:",i)
7、困销显示π值,即
print("π值:",Pi)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)