Python 中的几何级数

嘿伙计!在本教程中,我们将了解几何级数是什么以及如何在 Python 编程语言中实现它。


几何级数简介(GP)

几何级数是一系列元素,其中下一项是通过将前一项乘以公比获得的。

GP系列是一个数列,其中任何连续整数(项)的公比始终相同。

GP 系列的总和基于数学公式。

Sn = a(r n ) / (1- r)
Tn = ar (n-1)


Python 中的几何进步

让我们来了解一下 Python 中的几何级数是如何工作的。我们将看两个不同的示例,以便更好地理解。

1. 打印几何级数的前n项

实现 n GP 项涉及许多步骤。步骤如下:

步骤 1 – 输入 a(第一项)、r(公比)和 n(项数)
步骤 2 – 进行从 1 到 n+1 的循环,并在每次迭代中计算第 n 项继续打印条款。

1
2
3
4
5
6
7
8
9
# 1. Take input of 'a','r' and 'n'
a = int(input("Enter the value of a: "))
r = int(input("Enter the value of r: "))
n = int(input("Enter the value of n: "))
 
# 2. Loop for n terms
for i in range(1,n+1):
    t_n = a * r**(i-1)
    print(t_n)
Enter the value of a: 1
Enter the value of r: 2
Enter the value of n: 10
1
2
4
8
16
32
64
128
256
512

2. 求几何级数前n项的和

要获得前 n 个 GP 项的总和,需要执行多个步骤。步骤如下:

步骤 1 – 输入 a(第一项)、r(公比)和 n(项数)
步骤 2 – 使用上述公式计算前“n”项的总和。

1
2
3
4
5
6
7
8
9
10
11
# 1. Take input of 'a','r' and 'n'
a = int(input("Enter the value of a: "))
r = int(input("Enter the value of r: "))
n = int(input("Enter the value of n: "))
 
if(r>1):
  S_n = (a*(r**n))/(r-1)
else:
  S_n = (a*(r**n))/(1-r)
 
print("Sum of n terms: ",S_n)
Enter the value of a: 1
Enter the value of r: 2
Enter the value of n: 5
Sum of n terms:  32.0

结论

恭喜!您刚刚学习了如何在 Python 中实现几何级数。希望你喜欢它!😇

喜欢该教程吗?无论如何,我建议您查看下面提到的教程:

  1. Python 中的记忆化——简介
  2. Python 中的 Anagrams 简介
  3. Python Wonderwords 模块 – 简介

感谢您抽出宝贵时间!希望你学到新东西!😄