擅长:python、mysql、java
<p>解决这个问题的一个简单方法是为“Nilakantha Series”创建一个生成器,然后只<code>enumerate()</code>累积项,直到出现错误:</p>
<pre><code>import itertools as it
Decimal = float
#from decimal import Decimal # To use arbitrary precision decimal type
def nilakantha_series():
yield Decimal(3)
c = it.cycle([1, -1])
for d in it.count(2, 2)
yield Decimal(next(c)*4)/Decimal(d*(d+1)*(d+2))
def term_count(series, error, exact):
for N, value in enumerate(it.accumulate(series)):
if abs(value - exact) <= error:
return N
In []:
PI = Decimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062')
M = 14
term_count(nilakantha_series(), 10**-M, PI)
Out[]:
24835
</code></pre>
<p>注意:如果您取消了import的注释并删除了<code>Decimal = float</code>,那么您将得到:</p>
^{pr2}$