(python)求e的近似值(第二版)

自然常数e可以用级数1+1/1!+1/2!+⋯+1/n!来近似计算。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬

本题要求用该公式计算e的近似值,若最后一项(1/n!)小于给定的阀值时,终止计算(该项不计入)。

解决代码如下:

import math


threshold = float(input())                 
e = 1                                      
i = 1                                      
while True:                                
	if 1 / math.factorial(i) < threshold:  
		break                              
	else:                                  
		e = e + 1 / math.factorial(i)      
		i = i + 1                          
print("{:.8f}".format(e))      

你可能感兴趣的:(python习题,python)