Minimize a Convex Function - Uber Coding Interview | ShowOffer
You are given a convex function f(x) that is defined on the real numbers. The function is guaranteed to have a unique minimum. You are also given a range [a, b] that contains the minimum of the function. Your task is to find the minimum of the function within the given range.
Examples:
f(x) = (x - 1)^2, a = 0, b = 2
f(x) = x^2 + 10x + 25, a = -10, b = 0
Constraints:
Hints:
Solution:
To find the minimum of a convex function f(x) within a given range [a, b], you can use a binary search approach. Here's a step-by-step algorithm:
This approach works because the function is convex, and the minimum is guaranteed to be unique. By evaluating the function at the midpoint and updating the range accordingly, you can efficiently narrow down the range until the minimum is found.
Here's a Python implementation of the algorithm:
python def minimize_convex_function(f, a, b, tol=1e-6): while (b - a) > tol: m = (a + b) / 2 if f(m) < f(a) and f(m) < f(b): a = m else: b = m return (a + b) / 2
You can use this function to find the minimum of a convex function within a given range by passing the function f, the range [a, b], and an optional tolerance tol to control the accuracy of the result.