# Functions for Assignment 2
# Bill Campbell
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 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))
# Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21,...
def rfib(n):
""" Return the nth number in the Fibonacci sequence"""
if n == 1:
return 1
elif n == 2:
return 1
else:
return rfib(n-2) + rfib(n-1)
# pseudocode for ifib(n)
#
# The 1st Fibonacci number is 1
# The 2nd Fibonacci number is 1
# Otherwise, we compute the nth Fibonacci number iteratively,
# Starting with a sequence 1,1 or prev = 1, last = 1
# Using a definite loop, do n-2 times:
# prev, last = last, prev + last
# Return last (which is the nth element of the Fibonacci sequence.
#
for i in range(1,40):
print(str(rfib(i)) + ", ", end = "")