Python Forum

Full Version: Finding the intersection of interpolated curves
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,

as the title cites, I am trying to find the intersection of 2 arrays by interpolating them. 
I found this method, but it does not suit my situation as it needs a sorted input Data to work : 

x11=np.array([1.4,2.1,3,5.9,8,9,23])
y11=np.array([2.3,3.1,1,3.9,8,9,11])
x22=np.array([1,2,3,4,6,8,9])
y22=np.array([4,12,7,1,6.3,8.5,12])   

p1=interpolate.PiecewisePolynomial(x11,y11[:,np.newaxis])
p2=interpolate.PiecewisePolynomial(x22,y22[:,np.newaxis])

def pdiff(x):
    return p1(x)-p2(x)

xs=np.r_[x11,x22]
xs.sort()
x_min=xs.min()
x_max=xs.max()
x_mid=xs[:-1]+np.diff(xs)/2
roots=set()
for val in x_mid:
    root,infodict,ier,mesg = optimize.fsolve(pdiff,val,full_output=True)
    # ier==1 indicates a root has been found
    if ier==1 and x_min<root<x_max:
        root.add(root[0])
roots=list(roots)        
print(np.column_stack((roots,p1(roots),p2(roots))))
My x-values are not sorted so the : p1=interpolate.PiecewisePolynomial(x1,y1[:,np.newaxis])
does not work. If I sort my x1 at the beginning, it would yield an answer but I am not able to get back the real one, as my x was changed by sorting. 


Could anyone help please ?
Thank you in advance!

Moderator: Added code tags, please include code tags in future posts. Thank you
Can't you just make copies of your arrays to preserve them? For roots/intersections it should not matter.