bisection search for square root


In [1]:
x = 12345
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
    print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
    numGuesses += 1
    if ans**2 < x:
        low = ans
    else:
        high = ans
    ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))


low = 0.0 high = 12345 ans = 6172.5
low = 0.0 high = 6172.5 ans = 3086.25
low = 0.0 high = 3086.25 ans = 1543.125
low = 0.0 high = 1543.125 ans = 771.5625
low = 0.0 high = 771.5625 ans = 385.78125
low = 0.0 high = 385.78125 ans = 192.890625
low = 0.0 high = 192.890625 ans = 96.4453125
low = 96.4453125 high = 192.890625 ans = 144.66796875
low = 96.4453125 high = 144.66796875 ans = 120.556640625
low = 96.4453125 high = 120.556640625 ans = 108.500976562
low = 108.500976562 high = 120.556640625 ans = 114.528808594
low = 108.500976562 high = 114.528808594 ans = 111.514892578
low = 108.500976562 high = 111.514892578 ans = 110.00793457
low = 110.00793457 high = 111.514892578 ans = 110.761413574
low = 110.761413574 high = 111.514892578 ans = 111.138153076
low = 110.761413574 high = 111.138153076 ans = 110.949783325
low = 110.949783325 high = 111.138153076 ans = 111.043968201
low = 111.043968201 high = 111.138153076 ans = 111.091060638
low = 111.091060638 high = 111.138153076 ans = 111.114606857
low = 111.091060638 high = 111.114606857 ans = 111.102833748
low = 111.102833748 high = 111.114606857 ans = 111.108720303
low = 111.102833748 high = 111.108720303 ans = 111.105777025
low = 111.105777025 high = 111.108720303 ans = 111.107248664
low = 111.107248664 high = 111.108720303 ans = 111.107984483
low = 111.107984483 high = 111.108720303 ans = 111.108352393
low = 111.107984483 high = 111.108352393 ans = 111.108168438
numGuesses = 26
111.108076461 is close to square root of 12345

Newton-Raphson for square root


In [2]:
epsilon = 0.01
y = 24.0
guess = y/2.0

while abs(guess*guess - y) >= epsilon:
    guess = guess - ((guess**2 - y)/(2*guess))
    print(guess)
print('Square root of ' + str(y) + ' is about ' + str(guess))


7.0
5.21428571429
4.90851272016
4.89898874321
Square root of 24.0 is about 4.89898874321

In [3]:
def findRoot3(x, power, epsilon):
    if x < 0 and power%2 == 0:
        return None
    # can't find even powered root of negative number
    low = min(-1.0, x)
    high = max(1.0, x)
    ans = (high+low)/2.0
    while abs(ans**power - x) > epsilon:
        if ans**power < x:
            low = ans
        else:
            high = ans
        ans = (high+low)/2.0
    return ans

In [4]:
print findRoot3(25.0, 2, .001)
print findRoot3(27.0, 3, .001)
print findRoot3(-27.0, 3, .001)

print findRoot3(0.25, 2, .001)
print findRoot3(-0.125, 3, .001)


4.99992370605
2.99998474121
-2.99998474121
0.5
-0.5