小榄网站建设推广/搜索引擎优化的定义
1 说明:
=====
1.1 学习python求π值的方法探讨。
1.2 资料来自网络,大多注明,仅供学习。

求π
2 π:
===
2.1 π就是圆周率。
2.2 阿基米德(公元前287–212 年) ,古希腊大数学家,开创了人类历史上通过理论计算圆周率π近似值的先河。
2.3 祖冲之,南北朝时代著名数学家,进一步得出精确到小数点后7位的π值。

3 python求π值:
===========
3.1 直接调用法:
import mathval = math.piprint(val)
3.2 马青公式简洁法:π=16arctan1/5-4arctan1/239
import mathπ=4*(4*math.atan(1/5)-math.atan(1/239))print(π)#3.1415926535897936
3.3 math法代码:
import mathdef main(): a=1.0 b=1.0/math.sqrt(2) t=1.0/4.0 p=1.0 for i in range(1000): at=(a+b)/2 bt=math.sqrt(a*b) tt=t-p*(a-at)**2 pt=2*p a=at;b=bt;t=tt;p=pt my_pi=(a+b)**2/(4*t) print("Pi is approximately: "+str(my_pi))if __name__== "__main__": main()
3.4 公式法代码:
'''#代码来源:#https://blog.csdn.net/weixin_39525744/article/details/80778163通过公式计算圆周率 当k正无穷 π=[1/16^k*(4/(8*k+1)-2/(8*k+4)- 1/(8*k+5)-1/(8*k+6))] '''pi = 0N = 100for 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))#圆周率的值是: 3.141592653589793
3.5 马青公式复杂代码:
#第1步:说明# -*- coding: utf-8 -*- #代码来源:#https://blog.csdn.net/lnotime/article/details/82319973?utm_medium=distribute.pc_relevant.none-task-blog-title-5&spm=1001.2101.3001.4242#计算准确圆周率的马青公式:π=16arctan1/5-4arctan1/239#这个公式由英国天文学教授约翰·马青于1706年发现。#马青公式#第 2步:函数定义:n一般为100def pi(n): p = 10 ** (n + 10) # 准备初始整数,先多乘 k 个 0,以增加精度,最后再去掉,这里我取 k=10 a = p * 16 // 5 # 第一项的前半部分 b = p * 4 // -239 # 第一项的后半部分 f = a + b # 第一项的值 p = f # π j = 3 while abs(f): # 当|f|=0后计算π的值就不会再改变了 a //= -25 # 第n项的前半部分 b //= -57121 # 第n项的后半部分 f = (a + b) // j p += f j += 2 return p // 10**10 # 去掉 k 位,k=10#第3步:取值x=pi(100)#打印print(x)
3.6 丘德诺夫斯基法:
#第1步:说明:任意位数π# -*- coding: UTF-8 -*-# 丘德诺夫斯基法計算高精度圓周率程序# Calculating PI with Chudnovsky-Series# Author: Idealguy,2018, Shanghai#参考文章:https://blog.csdn.net/idealguy/article/details/82929032#第2步:定义函数def Sqrt10005(): n1=0 c=10002499687 #100.02499687 mc=8; m=mc f1=10**mc f2=f1*f1 a=10005*f2-c*c while mcn: m=n-mc else: m=mc f1=10**m f2=f1*f1 n1+=1 return c #第3步:循环print ("Chudnovsky法計算高精度圓周率程序")while 1: n=int(input('計算位數[1..50000],0:退出:')) if n<=10: break n+=2 base=10**n A=13591409*base; B=A c3=13591409 i=1 while abs(A)>5: c1=((108-72*i)*i-46)*i+5 c2=10939058860032000*i**3 c4=c3; c3+=545140134 i+=1 A=A*c1*c3//(c2*c4) B+=A p=426880*base*Sqrt10005()//B//100 s=input('是否显示结果(Y/N):') if (s=='Y')|(s=="y"): print ("PI="+str(p))