Home > OS >  Using a BREAK statement to exit this while loop changes the value of the variable and gives incorrec
Using a BREAK statement to exit this while loop changes the value of the variable and gives incorrec

Time:12-27

Question:

Write a program that implements Newton’s method to compute and display the square root of a number entered by the user. The algorithm for Newton’s method follows: Read x from the user Initialize guess to x/2 While guess is not good enough do Update guess to be the average of guess and x/guess When this algorithm completes, guess contains an approximation of the square root. The quality of the approximation depends on how you define “good enough”. In the author’s solution, guess was considered good enough when the absolute value of the difference between guess ∗ guess and x was less than or equal to 10−12.

Solution:

x = int(input("Enter x: "))

guess = x/2

while guess != (abs(guess * guess - x <= 10 ** -12)):

    guess =  (guess   x/guess)/2

    print(guess)

Note: if I add a break statement, it changes the value. Ex: square root of 9 = 3 using the above solution.

but If I add a BREAK statement...

while guess != (abs(guess * guess - x <= 10 ** -12)):

    guess =  (guess   x/guess)/2

    print(guess)

    break  

Enter x: 9 3.25

why does adding a break statement change the value of the guess variable? How do I terminate this loop without changing the value and simply print guess and exit loop?

endloop is not working and exit() seems to have the same effect. Any help will be greatly appreciated. Thank you !

if type(guess) != str:
    break

I have also tried placing such a condition. same effect. prints incorrect value for guess.

CodePudding user response:

This demonstrates the correct while condition:

x = int(input("Enter x: "))
guess = x/2
while abs(guess * guess - x) >= 10 ** -12:
    guess =  (guess   x/guess)/2
    print(guess)

Output:

C:\tmp>python x.py
Enter x: 9
3.25
3.0096153846153846
3.000015360039322
3.0000000000393214
3.0

CodePudding user response:

Here's a slightly different approach that uses an extra variable and thus a less complicated conditional expression. Also use a variable to determine the level of accuracy and also use that same variable to the presentation of the result.

x = float(input('X: '))

guess = x / 2
prev = x

DP = 4 # no. of decimal places accuracy
MARGIN = 10 ** -DP

while abs(guess - prev) > MARGIN:
    prev = guess
    guess = (guess   x / guess) / 2

print(f'{guess:.{DP}f}')

Example:

X: 17
4.1231
  • Related