尝试使用循环函数求数字的平方根。 我正在尝试使用巴比伦方法,但它不会返回正确的答案。如果有人能指出我哪里有错误,我将不胜感激。
def sqrt(number, guess, threshold):
x = number / 2
prev_x = x + 2 * threshold
while abs(prev_x - x) > threshold:
prev_x = x
x = (x + guess / x) / 2
square_root = x
return square_root
test = sqrt(81, 7, 0.01)
print (test)
最佳答案
更改
x = (x+猜测/x)/2
因为这将进展到猜测的平方根。将其更改为
x = (x+number/x)/2
将 return 语句移出 while 循环
初始化 x 来猜测而不是 number/2
关于python - 使用巴比伦方法求平方根返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52378408/