def linecut(x, y, ycut):
    """
    Given a sequence of line segments defined by arrays x, y, and a
    specified y value ycut, return a list of x values where the line
    segments cross ycut, return empty list if they don't cut.  

    NB: Often useful when e.g. x is an iteration number and y a
    residual, xcut gives then at what iterations a convergence
    criteria was achieved.
    """
    xcut = []
    if x.size < 2:
        return []
    for i in range(x.size - 1):
        xx, yy = [x[i], x[i + 1]], [y[i], y[i + 1]]
        if yy[1] < yy[0]:
            xx.reverse()
            yy.reverse()
        if ycut >= yy[0] and ycut < yy[1]:
            yfrac = (ycut - yy[0]) / (yy[1] - yy[0])
            xcut.append(xx[0] + yfrac * (xx[1] - xx[0]))
    return xcut