fork download
  1. import math
  2. # 公式一:e ≈ (1 + 1/n)^n
  3. def calculate_e_formula1(n):
  4. return (1 + 1 / n) ** n
  5. # 公式二:e ≈ Σ(从k=0到n)1/k!
  6. def calculate_e_formula2(n):
  7. e = 0
  8. factorial = 1 # 用于计算阶乘,初始为0! = 1
  9. for k in range(n + 1):
  10. if k == 0:
  11. factorial = 1
  12. else:
  13. factorial *= k
  14. e += 1 / factorial
  15. return e
  16. # 测试,取n = 1000
  17. n = 1000
  18. e_formula1 = calculate_e_formula1(n)
  19. e_formula2 = calculate_e_formula2(n)
  20. print("公式一计算结果:", e_formula1)
  21. print("公式二计算结果:", e_formula2)
  22. print("Python 内置 math.e 值:", math.e)
Success #stdin #stdout 0.02s 7396KB
stdin
Standard input is empty
stdout
('\xe5\x85\xac\xe5\xbc\x8f\xe4\xb8\x80\xe8\xae\xa1\xe7\xae\x97\xe7\xbb\x93\xe6\x9e\x9c\xef\xbc\x9a', 1)
('\xe5\x85\xac\xe5\xbc\x8f\xe4\xba\x8c\xe8\xae\xa1\xe7\xae\x97\xe7\xbb\x93\xe6\x9e\x9c\xef\xbc\x9a', 2L)
('Python \xe5\x86\x85\xe7\xbd\xae math.e \xe5\x80\xbc\xef\xbc\x9a', 2.718281828459045)