python求平均值最簡單方法(6種方法用python求π值)
2023-07-27 02:19:34
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 n5: 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): print ("PI=" str(p))
,