在条款系列Nilakantha在python

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

我知道这很可能是一个非常简单的代码,但我似乎无法找出什么在世界上是错的。每次我得到0作为一个答案,如果我尝试只是直接进行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。

python
2个回答
0
投票

你的回报表现,n == Pi总是False,这是算术0。只是返回Pi

EDIT2:原因输出仍为0是PI(0) - actualPi <10 ** M代表任何非负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

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
© www.soinside.com 2019 - 2024. All rights reserved.