台北來的土包子
 
Python-Leibniz  use For-Loop

Python-Leibniz use For-Loop

π 的萊布尼茨公式是一個有趣的數學式:
sum  = 1 – 1/3 + 1/5 – 1/7 + 1/9 -…….+ 1/∞
計算的次數愈多時,把 sum  乘以 4 ,其值會趨近於 π
詳細的說明可以參考 π的萊布尼茨公式

 

利用 Python 寫一個簡單的程式即可驗証這個數學式:

# Leibniz
# https://www.george.tw/2020/03/02/python-leibniz-use-for-loop/
import math


count=int(input("Enter a number:"))   # Let user input a number, this is our calculation count
sumLeibniz=1  
denominator=3                    
negate=-1

for i in range(0,count):
    sumLeibniz += (negate * ( 1 / denominator))
    denominator += 2
    negate *= -1

total= 4 * sumLeibniz
print("We calculated that {:d} times Leibniz was {:.8f}".format(count,total))
print("The true PI is {:.8f}".format(math.pi))
print("The diffecent is {:.8f}".format(total - math.pi))

此範例會使用的 pi 這個常數,所以在第一行加上了 import math
count 是我們要計算的次數
denominator 為公式中的分母
negate 控制正負號,由正負號來控制加減
sumLeibniz 為萊布尼茨公式的總和
最後把總和乘上 4,在和 π 做比較

print(“We calculated that {:d} times Leibniz was {:.8f}”.format(count,total)) 這一 行中的 {:d} 和 {:.8f} 為 python 新版的字串格式,
請參考 Python String Formatting, 字串格式化

原始碼: GitHub

發表迴響