牛顿近似平方根的方法

Jianna

我正在尝试编写一个函数来计算牛顿方法。期待我的代码中不断出现错误。这是提示我为

这是我写下的代码

import math

def newton(x):
   tolerance = 0.000001
   estimate = 1.0
   while True:
        estimate = (estimate + x / estimate) / 2
        difference = abs(x - estimate ** 2)
        if difference <= tolerance:
            break
   return estimate

def main():
   while True:
       x = input("Enter a positive number or enter/return to quit: ")
       if x == '':
           break
       x = float(x)
       print("The program's estimate is", newton(x))
       print("Python's estimate is     ", math.sqrt(x))
main()

它似乎正在工作,但是在对Cengage进行检查时我一直收到此错误

我不太确定这意味着什么,因为我的代码似乎运行得很好。有人可以帮忙解释一下吗?

忙程序员

输入为空白时,似乎会出现此问题。假设您只想使用正数作为输入,一个可能的解决方法是设置一个负数(或其他任何选择),例如-1作为退出条件:

x = input("Enter a positive number or enter/return to quit: ")
if not x:
    break
x = float(x)

This should avoid the EOFError.


Edit

If you want to use a blank input (hitting the return line) to break out of the loop, you can try this alternative syntax:

x = input("Enter a positive number or enter/return to quit: ")
if not x:
    break
x = float(x)

The not x checks if x is blank. It is also more pythonic than x == "". Additional methods to detect a blank input are in this post as well: How do you get Python to detect for no input.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章