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

Code won't stop running. Seems trivial but I cannot figure it out

这是我用于近似 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))

没有错误,直到我 ^c 从 运行 停止它,此时它显示:

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

我相信它在无限循环,但我不明白为什么。如有任何帮助,我们将不胜感激!

你第一次调用 factorial(i) 函数时 i=0。阶乘看起来是 while(n!=0) ..... n=n-1。您从 0 开始,然后将其降低 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会怎么样?