嘿伙计!在本教程中,我们将了解什么是算术级数以及如何在 Python 编程语言中实现它。
算术级数简介 (AP)
算术级数是一个术语级数,其中下一项是通过将前一项添加公差而生成的。
AP系列是任意两个连续数字之差始终相同的数字序列。这种区别被称为共同差异。
算术级数的数学计算方法如下:
AP 系列之和:Sn = n/2(2a + (n – 1) d)
AP 系列的 Tn 项:Tn = a + (n – 1) d
Python中算术级数的代码实现
让我们开始使用 Python 来实现算术级数。我们将举两个相同的例子来帮助您更好地理解这个概念。
1. 打印算术级数的前 n 项
实现 n AP 项涉及多个步骤。步骤如下:
步骤 1 – 获取 a(第一项)、d(步长)和 n(项数)的输入
步骤 2 – 进行从 1 到 n+1 的循环,并在每次迭代中计算第 n 项并保持打印条款。
1
2
3
4
5
6
7
8
9
|
# 1. Take input of 'a','d' and 'n' a = int ( input ( "Enter the value of a: " )) d = int ( input ( "Enter the value of d: " )) n = int ( input ( "Enter the value of n: " )) # 2. Loop for n terms for i in range ( 1 ,n + 1 ): t_n = a + (i - 1 ) * d print (t_n) |
2. 求算术级数中前n项的和
要获得前 n 个 AP 项的总和,需要执行多个步骤。步骤如下:
步骤 1 – 输入 a(第一项)、d(步长)和 n(项数)
步骤 2 – 使用上述公式计算前“n”项的总和。
1
2
3
4
5
6
7
|
# 1. Take input of 'a','d' and 'n' a = int ( input ( "Enter the value of a: " )) d = int ( input ( "Enter the value of d: " )) n = int ( input ( "Enter the value of n: " )) S_n = (n / 2 ) * ( 2 * a + (n - 1 ) * d) print ( "Sum of first n terms: " , S_n) |
Enter the value of a: 1 Enter the value of d: 2 Enter the value of n: 5 Sum of first n terms: 25.0 |
结论
恭喜!您刚刚学习了如何在 Python 中实现算术级数。希望你喜欢它!😇
喜欢该教程吗?无论如何,我建议您查看下面提到的教程:
感谢您抽出宝贵时间!希望你学到新东西!😄