def line_search(func, x, p, tau=0.5, delta=1.0, tolerance=1e-7):
    """
    Perform a line search
    :param func The function to minimize
    :param x The initial position
    :param p The direction to search
    :param tau: The backtracking parameter
    :param delta: The initial step
    :param tolerance: The algorithm tolerance
    :return: The amount to move in the given direction

    """
    fa = func(x)
    if p.length() < 1:
        min_delta = tolerance
    else:
        min_delta = tolerance / p.length()

    while delta > min_delta:
        try:
            fb = func(x + delta * p)
            if fb <= fa:
                return delta
        except Exception:
            pass
        delta *= tau
    return 0