在过去的一个小时里,我一直在尝试破解这个问题,但在这里遇到了一些麻烦。这就是问题
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
andnewGuess
. InitializeoldGuess
ton / 2.0
and calculatenewGuess
according to the above formula. Use a while loop to iterate as long as the absolute value of the difference between theoldGuess
andnewGuess
is greater than1.0E-06
. Do not forget to reset the value ofoldGuess
to thenewGuess
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/