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

标签 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))

直到我 ^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

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

最佳答案

在你的函数中

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会怎样?

关于python - 代码不会停止运行。看起来微不足道,但我无法弄清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327791/

相关文章:

python - 如何使用 Python 解析复杂的 XML

python - 如何在不启用 sigaltstack 的情况下编译 python 3?

elasticsearch - aiohttp 仅下载正文的前 n 个字节

python - 使用PyQt5录制视频

没有 time.sleep() 的 Python 循环延迟

sqlalchemy - SQLAlchemy,如何向两个表中插入数据并引用外键?

python - 无法使用 Django 2.1 和 Python 3.5 创建自定义用户模型

python - QtWidgets.QApplication(sys.argv) 后无法导入 PyQt 模块

python - 如何将以 m 为底的字符串转换为以 n 为底的字符串

c# - pythonnet 在 .net 示例中嵌入 Python 加载模块失败