【问题标题】:Recursive square root loop in python with a epsilon of .0001python中的递归平方根循环,epsilon为0.0001
【发布时间】:2019-02-04 20:42:52
【问题描述】:

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

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

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

【问题讨论】:

  • single == 'single' or 'Single' 将始终返回 True,因为字符串 'Single' 将充当 True。尝试以下方法来解决这个问题:if single.lower()=='single': 这样你就不必担心大小写了
  • 谢谢帕特里克!对我的方程式循环有什么想法吗?它最终成为一个无限循环,其中 9 的平方根(例如)是 3.400,而没有递归得到实际的平方根。
  • 你永远不会更新number。因此,estimate 永远不会改变。对于你的例子,我永远得到estimate = 5.0, number-estimate=4.0

标签: python loops square-root


【解决方案1】:

while 循环的条件错误。 number9estimate 转到 3。所以你必须检查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

【讨论】:

  • 哦耶!我现在看到了。太棒了。谢谢乔纳斯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多