猿问

牛顿近似平方根的方法

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

这是我写下的代码


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 运行检查时,我不断收到此错误

http://img1.mukewang.com/61b16e4a0001a30310680913.jpg

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


繁华开满天机
浏览 225回答 2
2回答

元芳怎么了

当输入为空时,似乎会出现此问题。一个潜在的解决方法,假设您只想要正数作为输入,将设置一个负数(或您选择的任何其他内容),例如 -1,作为退出条件:x = input("Enter a positive number or enter/return to quit: ")if not x:&nbsp; &nbsp; breakx = float(x)这应该避免EOFError.编辑如果您想使用空白输入(点击返回行)来跳出循环,您可以尝试以下替代语法:x = input("Enter a positive number or enter/return to quit: ")if not x:&nbsp; &nbsp; breakx = float(x)该not x检查是否x为空。这也更符合Python比x == ""。

倚天杖

我是这样做的,Cengage 接受了。import mathtolerance = 0.000001def newton(x):&nbsp; &nbsp;estimate = 1.0&nbsp; &nbsp;while True:&nbsp; &nbsp; &nbsp; &nbsp; estimate = (estimate + x / estimate) / 2&nbsp; &nbsp; &nbsp; &nbsp; difference = abs(x - estimate ** 2)&nbsp; &nbsp; &nbsp; &nbsp; if difference <= tolerance:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp;return estimatedef main():&nbsp; &nbsp;while True:&nbsp; &nbsp; &nbsp; &nbsp;x = input("Enter a positive number or enter/return to quit: ")&nbsp; &nbsp; &nbsp; &nbsp;if x == "":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break&nbsp; &nbsp; &nbsp; &nbsp;x = float(x)&nbsp; &nbsp; &nbsp; &nbsp;print("The program's estimate is", newton(x))&nbsp; &nbsp; &nbsp; &nbsp;print("Python's estimate is&nbsp; &nbsp; &nbsp;", math.sqrt(x))if __name__ == "__main__":&nbsp; &nbsp; main()
随时随地看视频慕课网APP

相关分类

Python
我要回答