Loops 当python循环到达特定数字的范围时,如何停止它?

Loops 当python循环到达特定数字的范围时,如何停止它?,loops,Loops,我是一名计算机科学的新生,在编码方面几乎没有经验,我遇到了一个路障 我们的任务是使用巴比伦算法找到用户输入的数字的平方根。巴比伦算法是(猜测+输入/猜测)/2。我正在使用一个循环,并用上一次迭代的答案替换“猜测” 我想做的是,一旦循环在真平方根的10倍^-15范围内,停止循环并打印答案 Repeat = True while Repeat == True: og = float(input("What do you want to find the square root of?: ")

我是一名计算机科学的新生,在编码方面几乎没有经验,我遇到了一个路障

我们的任务是使用巴比伦算法找到用户输入的数字的平方根。巴比伦算法是(猜测+输入/猜测)/2。我正在使用一个循环,并用上一次迭代的答案替换“猜测”

我想做的是,一旦循环在真平方根的10倍^-15范围内,停止循环并打印答案

Repeat = True
while Repeat == True:
    og = float(input("What do you want to find the square root of?: "))
    print("Okay, we will use the Babylonian algorithm to find the square root of " + str(og) + ".")
    guess = float(input("Roughly estimate what the square root of " + str(og) + " is: "))
    print("Each answer will get closer to the true square root.")
    for answer in range(1,15):
        answer = ((guess + (og/guess))/2)
        print(answer)
        guess = (answer)
    else:
    print("The square root of " + str(og) + " is roughly " + str(answer) + ".")
    end = input("Do you want to find the square root of another number? y/n: ")
    if end == 'y':
            Repeat = True #This repeats the program
        else:
            Repeat = False #This ends the 'Repeat' loop. 
            print("Okay, thank you for using my program!")

目前,我需要重复一定的次数(15次)。但就像我说的,我不希望它重复一定的次数,而是希望它在一定程度上接近真实答案

你可以做一个while循环,直到达到你的ε。大概是这样的:

Repeat = True
while Repeat == True:
    og = float(input("What do you want to find the square root of?: "))
    print("Okay, we will use the Babylonian algorithm to find the square root of " + str(og) + ".")
    guess = float(input("Roughly estimate what the square root of " + str(og) + " is: "))
    print("Each answer will get closer to the true square root.")
    for answer in range(1,15):
        answer = ((guess + (og/guess))/2)
        print(answer)
        guess = (answer)
    else:
    print("The square root of " + str(og) + " is roughly " + str(answer) + ".")
    end = input("Do you want to find the square root of another number? y/n: ")
    if end == 'y':
            Repeat = True #This repeats the program
        else:
            Repeat = False #This ends the 'Repeat' loop. 
            print("Okay, thank you for using my program!")
while closeness > epsilon:
   answer = ((guess + (og/guess))/2)
   answer_squared = answer * answer
   closeness = answer_squared - og
   guess = (answer)
与此相反:

for answer in range(1,15):
    answer = ((guess + (og/guess))/2)
    print(answer)
    guess = (answer)
您可以执行while循环:

import math
real_answer=math.sqrt(og)
while abs(real_answer-guess)<=x: #x is how close you want your guess to be to the real answer
    guess=(guess+(og/guess))/2
    print(guess)
导入数学
real_answer=math.sqrt(og)
而abs(真实答案猜测)