我觉得我一切都对,但我似乎无法得到正确的平方根。每次我运行它时,答案都是关闭的。
例如,当我插入 100 时,它会输出 26 作为平方根,这是不正确的。
我做错了什么?
def sqrt(n):
nextGuess = n / 2
lastGuess = 1
accuracy = 0.000001
while lastGuess > accuracy:
x = (lastGuess + n / lastGuess) / 2
lastGuess = nextGuess - x
nextGuess = x
return x
n = float(input('Enter a value:'))
if n <= 0:
print('Invalid number. Enter a positive number.')
else:
print(sqrt(n))
您的代码中有两个错误:首先您的
return
语句缩进错误,第二您的 lastGuess
应该使用 abs
def sqrt(n):
nextGuess= n/2
lastGuess=1
accuracy= 0.000001
while lastGuess > accuracy:
x = (lastGuess + n/ lastGuess) / 2
lastGuess = abs(nextGuess - x)
nextGuess = x
return x
您无需了解特定算法即可实现它。一些打印语句会显示您的代码有什么问题。
看看你的 while 循环:
while lastGuess > accuracy:
x = (lastGuess + n/ lastGuess) / 2
lastGuess = nextGuess - x
nextGuess = x
return x # This shouldn't be indented
通过在 while 循环中返回,你不是在循环,你只是在返回。所以让我们解决这个问题并打印一些东西
[131]: def sqrt(n):
...: nextGuess= n/2
...: lastGuess=1
...: accuracy= 0.000001
...: while lastGuess > accuracy:
...: x = (lastGuess + n/ lastGuess) / 2
...: lastGuess = nextGuess - x
...: nextGuess = x
...: print(x, lastGuess, nextGuess)
...: return x
...:
[132]: sqrt(100)
50.5 -0.5 50.5
Out[132]: 50.5
因此你的
lastGuess
立即下降到准确度以下,从而停止循环。您不想检查最后的猜测是否大于准确度,而是检查 x_n
和 x_{n-1}
之间的差异是否小于您的准确度。因此,让我们创建一个 delta
变量来跟踪它。您也不需要 x
、lastGuess
和 nextGuess
。您的 x
是您的下一个猜测,所以我们也来清理它。您还希望将最后的猜测设置为 x,而不是差值。实施这些更改如下所示:
In [135]: def sqrt(n):
...: lastGuess = n/2
...: accuracy = 1e-3
...: delta = 1
...: while delta > accuracy:
...: x = (lastGuess + n/ lastGuess) / 2
...: delta = abs(x - lastGuess)
...: lastGuess = x
...: print(x, lastGuess)
...: return x
...:
In [136]: sqrt(100)
26.0 26.0
14.923076923076923 14.923076923076923
10.812053925455988 10.812053925455988
10.030495203889796 10.030495203889796
10.000046356507898 10.000046356507898
10.000000000107445 10.000000000107445
Out[136]: 10.000000000107445