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

时间:2019-02-04 20:42:52

标签: python loops square-root

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

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

提示用户输入大于零的整数值。 检查以确保该值确实大于零。如果不是,程序将显示错误消息,并再次要求输入。 使用上述巴比伦方法计算值的平方根。 向用户显示平方根,其格式设置为精确显示小数点后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.")

1 个答案:

答案 0 :(得分:1)

while循环的条件错误。 collectnumber9转到estimate。因此,您必须检查3(取绝对值,因为对于起始值number - estimate*estimate,估计值从上方收敛到3)。您不需要根据Babylonian method on wikipedia进行第一估算。 另外,估算值始终在您的代码中4。 (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'))