python - Square root calculation using bisection -
i have following code should find square root using bisection, reason won't. when want find square root of 9 4.5.
y = float(input('enter number want find square root of: ')) z = y x = 0 ans = 0 while abs(ans**2 - abs(y)) > 0.0001 , ans <= x: ans = (x + y) / 2.0 if ans**2 < z: x = ans else: y = ans print 'the square root of', z, 'is', ans
you need check if ans <= y, because y right border in case. need compare ans**2 absolute value of z, not y, because changing y inside loop:
while abs(ans**2 - abs(z)) > 0.00001 , ans <= y: ans = (x + y) / 2.0 if ans**2 < z: x = ans else: y = ans
Comments
Post a Comment