# Functions for Assignment 1
# Bill Campbell
""" We have discussed these functions in class. Function sqrtguess(n, epsilon)
computes and returns an estimate of the square root of n that is within
epsilon of n when squared. Function sqrtNR() does the same thing, but
using the Newton-Raphson method. Both function are iternative in nature;
they repeatedly compute estimates that are closer and closer to the
square root of n.
Function sqrtguessCounter() is just like sqrtguess(), but instead of returning
the computed result, it counts (using the variable, counter) the number of
iterations (succesive guesses) required to compute the result,
and returns that count.
"""
# Sqrt by bisection
def sqrtguess(x, epsilon):
low = 0.0
high = max(1.0, x)
guess = (high + low)/2.0
while abs(guess ** 2 - x) >= epsilon:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
return guess
print("sqrtguess:")
print(sqrtguess(25, .01))
print(sqrtguess(25, .0000000001))
print(sqrtguess(.25, .001))
def sqrtguessCounter(x, epsilon):
low = 0.0
high = max(1.0, x)
guess = (high + low)/2.0
counter = 0
while abs(guess ** 2 - x) >= epsilon:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
counter += 1 # same as: counter = counter + 1
return counter
print("sqrtguessCounter:")
print(sqrtguessCounter(25, .01))
print(sqrtguessCounter(25, .0000000001))
print(sqrtguessCounter(.25, .001))
# sqrt by Newton-Raphson
def sqrtNR(x, epsilon):
x = float(x)
guess = x/2.0
diff = guess**2 - x
while abs(diff) > epsilon:
guess = guess - diff/(2.0*guess)
diff = guess**2 - x
return guess
print("sqrtNR:")
print(sqrtNR(25, .01))
print(sqrtNR(25, .0000000001))
print(sqrtNR(.25, .001))