0

Brand new to programming, python, I want to make this while loop cease execution when the values are equal, but only to 3 decimal points. Appreciate the help!

def newtonSqrt(n):
    approx = 0.5 * n
    better = 0.5 * (approx + n/approx)
    count = 0
    while better != approx:
        approx = better
        better = 0.5 * (approx + n/approx)
        count = 1 + count
    return (approx, count)

print(newtonSqrt(10))
John Montgomery
  • 6,739
  • 9
  • 52
  • 68
nolry
  • 1

2 Answers2

0

Round the values to 3 decimal places (they did 2 in that link but you can just do 3 instead) and then compare them. e.g.:

while round(better, 3) != round(approx, 3):
Random Davis
  • 6,662
  • 4
  • 14
  • 24
0

You should not compare floats directly for equality because of binary representation errors. Rounding might work, but looks hackish.

Instead, use something like while abs(better-approx) < error: with error set to 0.001 for example.

progmatico
  • 4,714
  • 1
  • 16
  • 27