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

Recursive square root loop in python with a epsilon of .0001

我需要平方根计算器方面的帮助。 方向如下:

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

提示用户输入大于零的整数值。 检查以确保该值确实大于零。如果不是,程序会显示一条错误消息并再次要求输入。 使用上面概述的巴比伦方法计算值的平方根。 向用户显示平方根,格式为精确显示小数点后 3 位(不超过 3 位,也不少于 3 位)。"

我无法使用 sqrt 函数。我真的很接近但不能完全进入正确的循环。这是我目前所拥有的

# 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 循环的条件错误。 number9estimate3。所以你必须检查 number - estimate*estimate(取绝对值,因为估计值从上面收敛到 3,起始值为 4)。根据 Babylonian method on 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