铭正文案网-每一句好文案都值得收藏

铭正文案网-每一句好文案都值得收藏

等比数列求和速算法?

59

等比数列的求和公式如下:

当公比 \( q

eq 1 \) 时 :

\[ S_n = \frac{a_1 (1 - q^n)}{1 - q} \]

其中,\( S_n \) 是前 \( n \) 项和,\( a_1 \) 是首项,\( q \) 是公比,\( n \) 是项数。

当公比 \( q = 1 \) 时

\[ S_n = n \cdot a_1 \]

即前 \( n \) 项和等于项数乘以首项。

示例计算

假设有一个等比数列,首项 \( a_1 = 2 \),公比 \( q = 3 \),项数 \( n = 10 \):

\[ S_{10} = \frac{2 (1 - 3^{10})}{1 - 3} = \frac{2 (1 - 59049)}{-2} = \frac{-118096}{-2} = 59048 \]

代码示例

```python

def geometric_series_sum(a, q, n):

return a * (1 - qn) / (1 - q)

a = 2

q = 3

n = 10

sum_n = geometric_series_sum(a, q, n)

print("The sum of the first {} terms of the geometric series is: {}".format(n, sum_n))

```

输出结果为:

```

The sum of the first 10 terms of the geometric series is: 59048

```

这个代码定义了一个名为 `geometric_series_sum` 的函数,该函数接受三个参数:等比数列的首项 `a`、公比 `q` 和项数 `n`。然后使用求和公式计算并返回数列和。