def ternary_search(func, lo, hi, abs_prec=1e-7):
    """ Find maximum of unimodal function func() within [lo, hi] """
    while abs(hi - lo) > abs_prec:
        lo_third = lo + (hi - lo) / 3
        hi_third = hi - (hi - lo) / 3

        if func(lo_third) < func(hi_third):
            lo = lo_third
        else:
            hi = hi_third

    return (lo + hi) / 2