#计算e的值(精度为10**-6)
sum,tmp = 1,1
for i in range(1,20):
tmp*=i
sum += 1/tmp
print("e的近似值(精度为10**-6)为%.6f"%sum)
输出结果是2.718282
def factorial(n):
t = 2.0
for i in range(3, n+1):
t *= i
return t
def e(n):
return sum([1.0/factorial(i) for i in range(1, n+1)])
1、阶乘随着n的增大计算难度也增大,所以不能无限进行下去
2、代码如下(计算前10位)
import math
def e(accuracy):
return sum(1.0/math.factorial(i) for i in range(accuracy))
if __name__ == "__main__":
print(e(10))