Approximate solutions

What if we are interested in approximate solutions for numbers that are not perfect cubes?

cube = int(input("Enter a number: ")
epsilon = 0.01
guess = 0.0
increment = 0.0001
num_guesses = 0
while abs(guess**3 - cube) >= epsilon and guess <= cube:
  guess += increment
  num_guesses += 1
if abs(guess**3 - cube) >= epsilon:
  print('Failed on cube root of', cube)
else:
  print(guess, 'is close to the cube root of', cube)
Problem:

Bisection Search

Finding the cube root through a bisection search

cube = int(input("Enter a number: ")
epsilon = 0.01
low = 0
high = cube
guess = (low+high)/2.0
num_guesses = 0
while abs(guess**3 - cube) >= epsilon:
  if guess**3 < cube:
    low = guess
  else:
    high = guess
  guess = (high + low)/2.0
  num_guesses += 1
print 'num_guesses =', num_guesses
print(guess, 'is close to the cube root of', cube)

Convergence of Bisection Search

Functions

Example: Pen

In programming, create structure with decomposition

Functions are reusable pieces/chunks of code. Functions are not run in a program until they are called or invoked in a program. Function characteristics:

Writing a function

def is_odd(i):  #keyword name parameeters
  """  #docstring begin
  Input: i, a positive int
  Returns true if i is odd, otherwise False
  """  #docstring end
  #body
  print("inside is_odd")
  return i%2 == 1   #return is a keyword


is_odd(4)  #later in the code, you call the function using its name and values for parameters