0

这看起来很简单,但我很难让它工作。我试图在“while循环”中创建一个新变量来收集每个循环中x的值,比如

k2 += x

但它不起作用。那么我如何总结这个while循环中的不同值呢?非常感谢。

# pi approximation by using Ramanujan Formula

import math

def estimate_pi(k):

    x = (2 * math.sqrt(2)/9801 * math.factorial(4*k) *(1103 + 26390*k))/(math.factorial(k**4)*396**(4*k))
    while x >= 1e-15:
        k += 1
        print '{:>5.15f} {:>5} {:>1}'.format(x, 'for k =', k)
        return estimate_pi(k)

estimate_pi(0)
4

3 回答 3

2

既然你提到了阶乘,我建议你看看以下内容:

使用while循环的阶乘

使用递归的阶乘

一般来说,函数要么有一个while循环,要么函数会调用自身(递归),但不能两者兼而有之。

您的 while 循环只是一个 if 语句,它不会因为该return语句而重新进入循环。您可能正在寻找这样的东西:

def estimate_pi(k):
    x = ...
    if x >= ...:
        print ...
        return x + estimate_pi(k+1)
    return 0
于 2013-08-12T05:34:08.183 回答
1

像这样的东西?

def estimate_pi(k, k2=0):
    ...
    while x >= 1e-15:
        k2 += x
        ...
        return estimate_pi(k, k2)
于 2013-08-12T04:25:22.860 回答
0

或者,您可以将 k2 设为全局,但由于其他原因,这可能只是一个坏主意,但它会起作用

global k2
def estimate_pi(k):
  global k2
  while x >= 1e-15:
    k2+=x
    ...
于 2013-08-16T15:44:20.110 回答