寫一個 Python 程序,用實例求等比數列(G.P .級數)的和。
Python 通用編程系列
等比數列是一個元素序列,其中下一個項目通過乘以上一個項目的公約數而獲得。或者 G.P. Series 是一系列數字,其中任何連續數字(項目)的公共比率總是相同的。
G.P 系列之和
Sn = a(rn)/(1-r)
Tn = ar(n-1)背後的數學公式
Python 程序求等比數列和的例子
這個 Python 程序允許用戶輸入第一個值、一系列項目的總數和公共定額。接下來,它找到等比數列的和。
# Python Program to find Sum of Geometric Progression Series
import math
a = int(input("Please Enter First Number of an G.P Series: : "))
n = int(input("Please Enter the Total Numbers in this G.P Series: : "))
r = int(input("Please Enter the Common Ratio : "))
total = (a * (1 - math.pow(r, n ))) / (1- r)
tn = a * (math.pow(r, n - 1))
print("\nThe Sum of Geometric Progression Series = " , total)
print("The tn Term of Geometric Progression Series = " , tn)
不用數學公式求等比數列和的程序
在這個 Python 程序中,我們沒有使用任何數學公式。
# Python Program to find Sum of Geometric Progression Series
a = int(input("Please Enter First Number of an G.P Series: : "))
n = int(input("Please Enter the Total Numbers in this G.P Series: : "))
r = int(input("Please Enter the Common Ratio : "))
total = 0
value = a
print("\nG.P Series :", end = " ")
for i in range(n):
print("%d " %value, end = " ")
total = total + value
value = value * r
print("\nThe Sum of Geometric Progression Series = " , total)
等比數列輸出的 Python 和
Please Enter First Number of an G.P Series: : 1
Please Enter the Total Numbers in this G.P Series: : 5
Please Enter the Common Ratio : 4
G.P Series : 1 4 16 64 256
The Sum of Geometric Progression Series = 341
用函數計算等比數列和的 Python 程序
這個 Python 等比數列程序與第一個示例相同。然而,在這個 Python 程序中,我們使用函數來分離邏輯。
# Python Program to find Sum of Geometric Progression Series
import math
def sumofGP(a, n, r):
total = (a * (1 - math.pow(r, n ))) / (1- r)
return total
a = int(input("Please Enter First Number of an G.P Series: : "))
n = int(input("Please Enter the Total Numbers in this G.P Series: : "))
r = int(input("Please Enter the Common Ratio : "))
total = sumofGP(a, n, r)
print("\nThe Sum of Geometric Progression Series = " , total)
寶潔系列輸出的 Python 和
Please Enter First Number of an G.P Series: : 2
Please Enter the Total Numbers in this G.P Series: : 6
Please Enter the Common Ratio : 3
The Sum of Geometric Progression Series = 728.0
原創文章,作者:EQKFF,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/316895.html