Python中的Nilakantha系列中的术语

时间:2019-02-06 01:50:28

标签: python

我知道这很可能是一段非常简单的代码,但是我似乎无法弄清楚世界上到底有什么问题。每次我得到0作为答案,如果我尝试直接使pi = Pi,则会给我一个“浮动”错误,并说它是不可调用的。

def pi(n):
  result = 0;
  N= int(input("Input desired iterations: "))
  M = 1.0
  denom = 2.0
  Pi = 3.0
  for I in range (1, N+1):
      Pi += ((4.0/(denom*(denom+1)*(denom+2.0)))*M)
      denom += 2.0
      M *= -1.0
  return n == Pi

m = int(input("M: "))
actual_pi =3.1415926535897932384626433832795028841971693993751058209749445923078164062
for i in range(0, 50000) : 
  val = pi(i)
  if (val - actual_pi) <= (10 ** m):
      print(i)
      break

这应该是我认为正确的代码,但是除了0之外我什么也得不到。This is the question I'm trying to solve. It also has the answer I should be getting.

编辑:刚注意到我没有在图片中输入正确的数字。是24834。

2 个答案:

答案 0 :(得分:0)

您的返回表达式n == Pi始终为False,算术上为0。只需返回Pi

EDIT2:输出仍然为0的原因是,对于任何非负M,Pi(0)-actualPi <10 ** M。

还有其他问题,可以通过将pi的测试放在pi函数的循环中来避免,如下所示。

actual_pi =3.1415926535897932384626433832795028841971693993751058209749445923078164062
def pi(testexp=14):

    M = 1.0
    denom = 2.0
    Pi = 3.0
    for i in range(50000):
        delta = abs(Pi - actual_pi)
        if not i % 1000: print(i, delta)
        if delta <= (10 ** -14):
            return i - 1  # Last iteration did not change Pi
        else:
            Pi += ((4.0/(denom*(denom+1)*(denom+2.0)))*M)
            denom += 2.0
            M *= -1.0

print(pi())
# 24834

答案 1 :(得分:0)

解决该问题的一种简单方法是为“ Nilakantha系列”创建一个生成器,然后仅enumerate()累积的项,直到得到错误为止:

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

注意:如果取消注释导入并删除Decimal = float,则会得到:

In []:
term_count(nilakantha_series(), 10**-M, PI)

Out[]:
29240