0

I am looking for a simple approach to finding the interpolated intersection between two Numpy arrays. I know that this is simply achieved if we have two function handles, rather than two arrays, as shown in this link using Scipy or using Sympy. I want to do the same, but given two arrays, specifically between the linear spline that results from connecting array entries by lines.

For example, suppose we have two arrays, y_1 and y_2, both thyought of as being evaluated at xSupport.

import numpy as np
xSupport = np.array([0,1])
y_1 = np.array([0,2])
y_2 = np.array([1,0])

I am looking for the function that returns 1/3, which is the x value at the intersections between these two lines. In my application the support is larger than two, so I am looking for an approach that is independent of the arrays' length.

splinter
  • 3,727
  • 8
  • 37
  • 82

2 Answers2

3

Along the same lines as ser's answer:

import numpy as np
x = np.array([0,1])
y1 = np.array([0,2])
y2 = np.array([1,0])

def solve(f,x):
    s = np.sign(f)
    z = np.where(s == 0)[0]
    if z:
        return z
    else:
        s = s[0:-1] + s[1:]
        z = np.where(s == 0)[0]
        return z

def interp(f,x,z):
    m = (f[z+1] - f[z]) / (x[z+1] - x[z])
    return x[z] - f[z]/m

f = y1-y2
z = solve(f,x)
ans = interp(f,x,z)

print(ans)

The problem can be simplified by assuming that you're finding a zero, and then performing the function on the difference of the two series. First, 'solve' finds where a sign transition occurs (implying a zero occurs somewhere in between) and then 'interp' performs a linear interpolation to find the solution.

Cory Nezin
  • 1,551
  • 10
  • 22
1

Over in Digitizing an analog signal, I created a function called find_transition_times . You could use that function by passing y_1 - y_2 for y and 0 for threshold:

In [5]: xSupport = np.array([0,1])
   ...: y_1 = np.array([0,2])
   ...: y_2 = np.array([1,0])
   ...: 

In [6]: find_transition_times(xSupport, y_1 - y_2, 0)
Out[6]: array([ 0.33333333])
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214