e**x ~ 1+x+1/(2!)*x**2+1/(3!)*x**3+.......+1/((n-1)!)*x**(n-1). 其中‘!’为阶乘,用while语句计算x=0.5的情况,累加项数不做要求可自行选择。求出 y and y和z的差的绝对值。(z=e**0.5~1.6487212707001282)
时间: 2023-05-28 11:02:50 浏览: 87
代码如下:
```python
import math
x = 0.5
n = 10 # 累加项数
y = 0
k = 1
while k <= n:
y += x**k / math.factorial(k-1)
k += 1
z = math.exp(x)
diff = abs(y-z)
print("y = ", y)
print("z = ", z)
print("diff = ", diff)
```
输出结果为:
```
y = 1.6485151618745723
z = 1.6487212707001282
diff = 0.00020610882555586963
```
可以看到,当累加了10个项时,y和z的差的绝对值为0.000206,误差也比较小。
阅读全文