递归平方根循环在python中的epsilon为.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循环的条件是错误的。number9并且estimate3因此,您必须进行检查number - estimate*estimate(取绝对值,因为3对于的初始值,估算值从上面收敛到4)。您不需要根据Wikipedia上的巴比伦方法进行第一次估算此外,估算始终5在您的代码中。总是estimate = (number + 1.0) / 2.0在哪里number9

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档