syrte
7/5/2016 - 3:11 AM

findroot.py

def findroot(y0, x, y):
    """
    y0: scalar
    x: 1D array
    y: function or 1D array
    """
    import numpy as np
    x = np.asarray(x)
    assert x.ndim == 1
    
    if callable(y):
        y = y(x)
    y = np.asarray(y)
    assert x.shape == y.shape
    
    ix1 = np.diff(y - y0 >= 0).nonzero()[0]
    ix2 = ix1 + 1
    x1, x2 = x[ix1], x[ix2]
    y1, y2 = y[ix1], y[ix2]
    x0 = (y0 - y1) / (y2 - y1) * (x2 - x1) + x1
    return x0