Professional Documents
Culture Documents
Repetition SquareRoot
Repetition SquareRoot
Ibrahim Abou-Faycal
#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Repetition - Finding Square Root - Bisection Method
Exhaustive search
• Divide the interval [0,1] into say 1000000 equally spaced points
• Sequentially loop over the points to find the point p such that p*p is closest to x
• Very slow
1
[ ]: # Square-root computation: bisection method
x = float(input("Enter non-negative real number <=1:"))
if x > 1:
print('Error, the number has to be less or equal to 1')
else:
epsilon = 0.0001
low = x
high = 1
mid = (low+high)/2
while abs(mid*mid-x)>epsilon:
if mid*mid<x:
low = mid
else:
high = mid
mid = (low+high)/2
print("Approximate square root of", x,"is: ", mid, "The power operator␣
,→gives:", x**0.5)
• Why efficient?
√ √ (high−low)
If low ≤ x ≤ high, then |mid − x| ≤ 2 :
√
Number of iterations Search interval length Error |mid− x| is at most
(1 − x) 1
Before entering loop 1−x ≤
2 2
(1 − x) (1 − x) 1
After first iteration ≤ 2
2 22 2
(1 − x) (1 − x) 1
After second iteration ≤ 3
22 23 2
(1 − x) (1 − x) 1
After k iterations ≤ k+1
2k 2k+1 2
2
To compare two floats x and y:
• instead of checking if x == y
• check if abs(x − y) ≤ epsilon, for small number epsilon