【问题标题】:How can I sum up the different values within this while loop?如何总结此 while 循环中的不同值?
【发布时间】:2013-08-16 23:44:20
【问题描述】:

这看起来很简单,但我很难让它发挥作用。我试图在“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)

【问题讨论】:

    标签: python python-2.7 while-loop


    【解决方案1】:

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

    factorial using while-loop

    factorial using recursion

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

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

    def estimate_pi(k):
        x = ...
        if x >= ...:
            print ...
            return x + estimate_pi(k+1)
        return 0
    

    【讨论】:

    • 你说函数不会因为return语句而再次进入while循环。怎么会在 Ashwini 的代码中出现?
    • Ashwini 的代码也不会重新进入 while 循环。请注意,您的 while 循环条件检查值“x”。但是'x'永远不会在循环内改变。因此,如果您的 while 循环重新进入,您的代码将陷入无限循环。
    【解决方案2】:

    这样的?

    def estimate_pi(k, k2=0):
        ...
        while x >= 1e-15:
            k2 += x
            ...
            return estimate_pi(k, k2)
    

    【讨论】:

    • 谢谢。但是为什么这个函数需要 k2 的输入,而像这样的阶乘函数却不需要: def factorial(n): while n != 0: recurse = factorial(n-1) result = n * recurse return result else:返回 1
    • @Quester 要记住递归调用期间k2 的先前值,我们需要传递它的值。
    • 正确,但是在我使用相同参数发布的阶乘函数(使用while循环)的情况下,我们需要记住变量“result = n*recurse" 每次我们通过递归调用。
    【解决方案3】:

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

    global k2
    def estimate_pi(k):
      global k2
      while x >= 1e-15:
        k2+=x
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2021-02-09
      • 1970-01-01
      • 2020-03-27
      • 2014-08-26
      • 2012-01-18
      • 1970-01-01
      相关资源
      最近更新 更多