def golden_search(f, a, b, xatol=1e-6, ftol=1e-8, expand_bounds=False):
    """
    Find minimum of a function on interval [a, b]
    using golden section search.

    If expand_bounds=True, expand the interval so that the function is
    first evaluated at x=a and x=b.
    """

    ratio = 2 / (1 + math.sqrt(5))

    if not expand_bounds:
        x0 = a
        x3 = b
    else:
        x0 = (ratio * a - (1 - ratio) * b) / (2*ratio - 1)
        x3 = (ratio * b - (1 - ratio) * a) / (2*ratio - 1)

    x1 = ratio * x0 + (1 - ratio) * x3
    x2 = (1 - ratio) * x0 + ratio * x3

    f1 = f(x1)
    f2 = f(x2)

    f0 = max(abs(f1), abs(f2))

    while True:
        if abs(x0 - x3) < xatol or abs(f1 - f2) < ftol*f0:
            break

        if f2 < f1:
            x0 = x1
            x1 = x2
            x2 = ratio * x1 + (1 - ratio) * x3
            f1 = f2
            f2 = f(x2)
        else:
            x3 = x2
            x2 = x1
            x1 = ratio * x2 + (1 - ratio) * x0
            f2 = f1
            f1 = f(x1)

    if f2 < f1:
        return x2
    else:
        return x1
def golden_search ( f , a , b , xatol = 1e-6 , ftol = 1e-8 , expand_bounds = False ) : ratio = 2 / ( 1 + math . sqrt ( 5 ) ) if not expand_bounds : x0 = a x3 = b else : x0 = ( ratio * a - ( 1 - ratio ) * b ) / ( 2 * ratio - 1 ) x3 = ( ratio * b - ( 1 - ratio ) * a ) / ( 2 * ratio - 1 ) x1 = ratio * x0 + ( 1 - ratio ) * x3 x2 = ( 1 - ratio ) * x0 + ratio * x3 f1 = f ( x1 ) f2 = f ( x2 ) f0 = max ( abs ( f1 ) , abs ( f2 ) ) while True : if abs ( x0 - x3 ) < xatol or abs ( f1 - f2 ) < ftol * f0 : break if f2 < f1 : x0 = x1 x1 = x2 x2 = ratio * x1 + ( 1 - ratio ) * x3 f1 = f2 f2 = f ( x2 ) else : x3 = x2 x2 = x1 x1 = ratio * x2 + ( 1 - ratio ) * x0 f2 = f1 f1 = f ( x1 ) if f2 < f1 : return x2 else : return x1
Find minimum of a function on interval [a, b]
    using golden section search.

    If expand_bounds=True, expand the interval so that the function is
    first evaluated at x=a and x=b.