Python求累加、累乘

如题所述

Python中的求和与求积:基础与应用</


1. 累加</


在Python中,求解1到100的和是基础操作,我们来看看两种方法的实现:



方法一(for循环):</
```python
# 定义累加函数
def sum_range(start, stop):
total = 0
for i in range(start, stop): # range不包括stop
total += i
return total
# 计算1到100的和
result1 = sum_range(1, 101)
result1
```

方法二(while循环):</
```python
# 初始化变量
total, i = 0, start
while i < stop:
total += i
i += 1 # 不包括stop
result2 = total
result2
```

接着,我们尝试计算圆周率π的近似值,利用无穷级数公式:



Python代码:</
```python
def pi_approximation(n_terms=100):
pi = 0
sign = 1
for i in range(1, n_terms+1, 2):
pi += sign * (1 / i)
sign *= -1
pi *= 4
return pi
pi_value = pi_approximation()
pi_value
```

2. 累乘</


累乘求1到10的乘积,同样有for和while两种方法:



方法一(for循环):</
```python
def multiply_range(start, stop, multivalue=1): # 注意初始值不能为0
for i in range(start, stop):
multivalue *= i
return multivalue
result3 = multiply_range(1, 11)
result3
```

方法二(while循环):</
```python
# 初始化乘积
multivalue = 1
i = start
while i < stop:
multivalue *= i
i += 1
result4 = multivalue
result4
```

3. 累加与累乘的综合运用:自然常数e的求解</


为求e的值,我们可以结合累乘和循环,先封装累乘函数,再使用它来实现e的计算:



Python代码:</
```python
import math
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
def e_approximation(n_terms=100):
e = 1
for i in range(1, n_terms+1):
e *= (1 + 1/i)
return e
approximated_e = e_approximation()
approximated_e
```

通过以上示例,我们看到for循环在已知范围时更为高效,而while循环则更为灵活。理解这两种循环的特性,将帮助我们在实际问题中选择最合适的实现方式。

温馨提示:答案为网友推荐,仅供参考