编写一个Python程序来查找等比数列(G.P. Series)之和,并附带实际示例。
等比数列是指一系列元素,其中下一项是通过将公比乘以前一项获得的。或者说,等比数列是一系列数字,其中任何连续数字(项)的公比始终相同。
等比数列之和背后的数学公式。
Sn = a(rn) / (1- r)
Tn = ar(n-1)
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 程序中,我们不使用任何数学公式。
# 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)
等比数列之和输出
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 程序中,我们使用函数分离了逻辑。
# 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)
等比数列之和输出
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