Lecture 7 Finger Exercise
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
You may consider the adjusted code below: What is the value of x by splitting the search interval exactly in half each time.
In this variation, we are looking for the cube root of a value y.
Furthermore, our algorithm is biased: instead of splitting the interval in the middle, it always sets the next guess to be exactly one-third of the way between the low and high bounds.
y = 12
epsilon = 0.2
num_guesses = 0
low = 0
high = y
guess = low + (high - low) / 3
error = abs(guess**3 - y)
while error >= epsilon:
if guess**3 < y:
low = guess
else:
high = guess
guess = low + (high - low) / 3
num_guesses += 1
error = abs(guess**3 - y)
num_guesses when this finishes running?
Suppose we have a function Instead of picking one midpoint, we pick two points, We repeat this process until the search range is sufficiently small: Implement f that is convex (i.e., "U-shaped"), and we want to find its minimum value.
Also suppose we know that the minimum must lie in a certain range of [low, high].p1 and p2, which divide the current search range into three equal segments.
To narrow our range, we compare the function values at these two test points:
f(p1) < f(p2):
The minimum cannot be in the rightmost third (from p2 to high).
Why? Because in a convex function, if the value at p1 is already lower than the value at p2, it means the valley (where the minimum is located) must be located to the left of p2.
Thus, we can set high to be p2.f(p1) > f(p2):
The minimum cannot be in the leftmost third (from low to p1).
We update low to be p1.f(p1) = f(p2):
The minimum must be in the middle third.
We update high to be p2 and low to be p1.high - low <= epsilon.ternary_search() below and return a list of [low, high].