Python 中数学常数 e 的近似值

问题描述 投票:0回答:2

我尝试使用 100,000 次迭代来近似常数 e,并显示结果,其中 i 是 10,000 的倍数,范围从 10,000 到 100,000。

我的代码是这样的:

import math

e = 0
i = 0

while i < 100001:
    e += 1 / (math.factorial(i))
    i += 1
    if i % 10000 == 0:
        print("The approximation using", i, "iterations is: ", e)

这有两个问题:

1.)代码需要永远运行,但我认为这可能是预期的。

2.) 无论我使用多少次迭代,我都会得到相同的近似值。这是我输出的开始部分:

The approximation using 10000 iterations is 2.7182818284590455
The approximation using 20000 iterations is 2.7182818284590455
The approximation using 30000 iterations is 2.7182818284590455

..等等。我该如何解决这个问题?

就上下文而言,这是一个仅包含循环的入门级编程问题。

编辑:注意到我的 i 和 e 部分在 while 循环中向后。固定的。但仍然遇到号码不变的问题。

python approximation
2个回答
1
投票

浮点数以 64 位编码,这意味着您无法继续迭代并获取 e 的新数字。

一种替代方法是使用任意精度算术 (GMP)

安装 gmpy2 :

pip3 install gmpy2

重构你的代码:


import math
from gmpy2 import mpfr

e = mpfr(0)
i = 0

while i < 100001:
    i += 1
    e += mpfr(1) / (math.factorial(i))
    if i % 10000 == 0:
        print("The approximation using", i, "iterations is: ", e)


0
投票

首先,当

e
时,你真的应该开始积累
i==0
的值 - 上面的代码片段从
i==1
开始,并且跳过一个完整的单位 - 这就是为什么你得到
1.718...
而不是
2.718...
- 并且 第二件事是,尽管 Python 整数能够具有任意大小(因此,人们可以在不到一秒的时间内计算出 fact(100_000)),但对于十进制数,Python 默认情况下将使用 64 位浮点数 - 这些只能保留那么多小数位,并且过去的事实(1000)(如果那么多的话)你不会获得任何更好的精度。

您可以使用 Python 的

decimal.Decimal
来代替普通的浮点数 - 它们具有可配置的精度,并且至少可以使用此方法获得几百个小数位,直到一切都变得太消耗 CPU 或内存为止。


from decimal import Decimal, getcontext

getcontext().prec = 200 # use 200 digits of precision:

def calc_e(iterations):
    to_e = 0
    for i in range(iterations + 1):
        to_e += Decimal(1) / math.factorial(i)

    if i % 100 == 0:
        print("The approximation using", i + 1, "iterations is: ", to_e)


请注意,显示大量数字的函数并不意味着这些显示的数字与

e
数字中正确数字的值相匹配,您必须使用参考
e
值(除了 Python 中提供的值)
math.e
这也是一个 float 64 数字),或其他公式,以检查您的值的正确位数。

© www.soinside.com 2019 - 2024. All rights reserved.