代码不会停止运行。看起来微不足道,但我无法弄清楚

时间:2016-02-10 23:08:09

标签: python python-3.5

这是我的近似exp(x)的代码。我知道那里可能是阶乘的功能,但我想确保自己可以创建一个:)

def factorial(n):
    """Computes factorial of a number n"""
    fac = n
    while n != 1:
        fac = fac * (n-1)
        n -= 1
    return fac


def exp_x_approx(x, n):
    """estimates exp(x) using a taylor series with n+1 terms"""
    s = 0
    for i in range(0, n+1):
        s = s + ((x**i)/factorial(i))
        print (s)
    return s

print(exp_x_approx(2,8))

在我停止运行之前没有错误,此时它会显示:

File "/Users/JPagz95/Documents/exp_x_approx.py", line 18, in <module>
    print(exp_x_approx(2,8))
  File "/Users/JPagz95/Documents/exp_x_approx.py", line 13, in exp_x_approx
    s = s + ((x**i)/factorial(i))
  File "/Users/JPagz95/Documents/exp_x_approx.py", line 5, in factorial
    fac = fac * (n-1)
KeyboardInterrupt

我相信它无休止地循环,但我无法弄清楚原因。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

在i = 0时调用您对factorial(i)函数的第一次调用。阶乘外观是while(n!= 0)..... n = n-1。从0开始并将其降低1,因此循环永远不会达到1并停止。

答案 1 :(得分:1)

在你的功能中

def factorial(n):
   """Computes factorial of a number n"""
   fac = n
   while n != 1:
       fac = fac * (n-1)
       n -= 1
   return fac

您可以像这样修改

def factorial(n):
    if n < 0:
        return "some error info."
    fac = 1
    while n>=1:
        fac = fac * n
        n -= 1
    return fac

您应将初始条件设置为fac = 1,并将终止条件设置为n> = 1而不是n!= 1。想想如果我给出数字-2会怎么样?