You are on page 1of 3

Repetition_SquareRoot

Ibrahim Abou-Faycal

#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Repetition - Finding Square Root - Bisection Method

Reading: [Guttag, Chapter 3] Material in these slides is based on


• Slides of EECE-230C & EECE-230 MSFEA, AUB
• [Guttag, Chapter 3]

0.1 Bisection Method Example: Finding Square Root



• Given a non-negative(√real number)x, approximate its square-root x without using exponen-
tiation operator ** x = x**0.5

• For simplicity assume that x ≤ 1, thus x ≤ x ≤ 1

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

Bisection method idea



• We know that x is in the interval [x, 1]
(x + 1)
• Compute mid =
2
• Compare mid*mid with x
• If mid*mid < x, narrow down search to the interval [mid,1]
• Else, narrow down search the interval [x,mid]
• Repeat the above process until abs(mid*mid - x) ≤ epsilon

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

Faster method: Heron’s method


• Also based on narrowing down search, but the update is different
• Faster convergence
• Convergence analysis less trivial

0.2 On the float type and accuracy


• Recall that the float type is represented with limited precision (8 bytes)
• Thus, we have approximation error, e.g.,
[ ]: x = 0
for i in range(0,10):
x = x + 0.1
print(x)
print(x == 1)

2
To compare two floats x and y:
• instead of checking if x == y
• check if abs(x − y) ≤ epsilon, for small number epsilon

You might also like