Skip to main content
 首页 » 编程设计

python之使用python计算长序列

2025年05月04日14bluestorm

伙计们,我正在尝试使用 python 求解这个方程式

我们需要找到一个值 N,该等式给出的结果为 2.718。 到目前为止,我在处理小数问题时所做的是:

import math 
from decimal import Decimal 
import scipy.misc 
 
limit = 2.718 
ris = 0 
n = 1 
while ris <= limit: 
   ris = Decimal(n / math.pow(scipy.misc.factorial(n), 1/n)) 
   n= n + 1 
 
   print(n,ris) 

主要问题是,在某个时刻它开始只是打印 Zeros,我不知道它是否仍在计算但不再显示结果或者它已经崩溃了。

有解决这个问题的想法吗?

请您参考如下方法:

此解决方案使用幂运算符 **,它比 pow 快一点,因为它没有函数加载和调用的开销。

import math 
from decimal import Decimal 
 
limit = Decimal(2.718) 
 
result = 0 
n = Decimal(1) 
one = Decimal(1) 
n_factor = Decimal(n) 
 
while result <= limit: 
    result = n / Decimal(n_factor ** (one/n)) 
    n += 1 
    n_factor *= n 
    # print (n, result) # uncomment to see intermediate results 
 
print ('Final', n, result) 

注意:它不是最优的,但至少它会计算 N

注意 #2:请参阅下面的评论以了解有关“scipy”和 Zeros 的问题的解释