# 递归平方根循环在python中的epsilon为.0001

“您需要实现巴比伦方法来计算平方根。基于该核心功能，您将编写一个交互式程序，该程序：

``````# Ask user if they would like to calculate a square root for a single number or range.
single = input("Enter 'single' or 'range' to solve for a single square root or a range of values, respectively: ")

# Set error message to let the user know 'range' calculation are not currently available.
if single == 'single' or 'Single':

# Ask user to enter a positive integer.
number = int(input("Enter a positive integer value: "))

# Set error message asking for valid number if user enters something other than a positive integer.
while number < 0:
print("Please enter a valid number.")
else:
# Choose epsilon
epsilon = .0001

# Choose estimate for the square root of x
estimate = 4

# Evaluate the estimate
while number - estimate > epsilon:
# Calculate the square root using the Babylonian Method.
estimate = (number + 1.0) / 2.0
second_estimate = (estimate + number / estimate) / 2.0

# Print the users selected value and its square root.
print("Value", "   ", "Square Root")
print(" ", number, "        ", format(second_estimate, '.3f'))
else:
# Tell user 'range' calculation are not currently available.
print("That function is not currently available.")
``````

while循环的条件是错误的。`number``9`并且`estimate``3`因此，您必须进行检查`number - estimate*estimate`（取绝对值，因为`3`对于的初始值，估算值从上面收敛到`4`）。您不需要根据Wikipedia上的巴比伦方法进行第一次估算此外，估算始终`5`在您的代码中。总是`estimate = (number + 1.0) / 2.0`在哪里`number``9`

``````number = 9
epsilon = .0001
estimate = 4
while abs(number - estimate*estimate) > epsilon:
estimate = (estimate + number/estimate) / 2.0
print("Value", "   ", "Square Root")
print(" ", number, "        ", format(estimate, '.4f'))
``````

``````Value     Square Root
9          3.1250
Value     Square Root
9          3.0025
Value     Square Root
9          3.0000
``````

0 条评论