python - 计算平方根的逻辑思维

标签 python python-3.3 square-root

在过去的一个小时里,我一直在尝试破解这个问题,但在这里遇到了一些麻烦。这就是问题

This method for calculating the square root of a number n starts by making a (non zero) guess at the square root. It then uses the original guess to calculate a new guess, according to the formula

newGuess = ((n / oldGuess) + oldGuess) / 2.0;

Have two variables oldGuess and newGuess. Initialize oldGuess to n / 2.0 and calculate newGuess according to the above formula. Use a while loop to iterate as long as the absolute value of the difference between the oldGuess and newGuess is greater than 1.0E-06. Do not forget to reset the value of oldGuess to the newGuess value in the while loop.

In your program you will prompt the user to enter a positive number. If the number is negative, print an error message and ask the user to try again. For a positive number, calculate the square root using the above method. Find the difference between the square root you obtained and the value obtained from using the exponentiation operator. Write out the value the user entered, the square root you computed, and the difference (your square root - n ** 0.5)

这是我目前的程序

def main():
    n = eval(input("Enter a positive number: "))
    while (n <= 0):
        print ("Error please re-input")
        n = eval(input("Enter a positive number: "))
     
    oldGuess = n / 2.0
    newGuess = ((n / oldGuess) + oldGuess) / 2.0;
    difference = n - n ** 0.5      
    while (difference < 1 * 10 ** -6):
        print ("Error")
        difference = abs(n - n ** 0.5)
    print ("Difference:", difference)

main()

所以我真的不明白我们如何告诉程序进行猜测,然后计算变量 n 的平方根。我什至认为我的 while 语句在这种情况下是不正确的。我不使用 python 中内置的已嵌入函数 squareroot,因此它必须手动完成我相信我仍然迷失了猜测函数的含义。

最佳答案

while True:
    n = float(input("Enter a positive number: "))
    if n > 0:
        break
    print ("Error please re-input")

oldGuess = n / 2.0
while True:
    newGuess = ((n / oldGuess) + oldGuess) / 2.0;
    oldGuess = newGuess
    if -1e-6 < n - newGuess * newGuess < 1e-6:
        break

print ("Difference:", abs(n ** .5 - newGuess))

关于python - 计算平方根的逻辑思维,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689229/

相关文章:

Python(anaconda)在proxy后面用pip添加包

python - IPython 代码从 Python 2 迁移到 Python 3

python - 使用 Python 的 str.format() 方法使用十六进制、八进制或二进制整数作为参数索引时出现 KeyError

algorithm - 有效地找到一个完美的广场

java - Java中BigDecimal的平方根

math - Swift 中的通用平方根

python - 以固定行和列标题的 html 形式查看 tsv 表

python - 根据上一行的输出分配值

python - 使用 python 2 和 smtplib 发送电子邮件时出现错误

python-3.3 - 我的列表索引有什么问题?指出索引错误