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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -