2

I have one list and one value like below:

y = [5, 6, 7, 3, 8, 10, 5, 2, 8, 15]
y0 = 9

if i plot then i am getting below plot

enter image description here

For plotting i am using below code:

a = []
for i in range(len(y)):
    a.append(y0)
x = []
for i in range(len(y)):
    x.append(i)

l5 = list(zip(y, x))
print(l5)
l6 = list(zip(a, x))
print(l6)

plt.plot(x, y, '-')
plt.plot(x, a, '-')
plt.show()

From the plot i can see there are 3 intersections. How can i get the intersection point's index(x value from the x axis)? For example in the above plot something like (4.2, 5.3, 8.1).

BC Smith
  • 727
  • 1
  • 7
  • 19

2 Answers2

1

I think this simple snippet of code could help you.

y = [5, 6, 7, 3, 8, 10, 5, 2, 8, 15]
y0 = 9

fr = y[0]
for i in range(1, len(y)):
    to = y[i]
    if fr <= y0 <= to or to <= y0 <= fr:
        y_delta = abs(to-fr)
        modifier = (y0-min(fr, to))/y_delta
        print("between", i-1, "and", i, "x =", i-1+modifier)
    fr = to
Konstantin
  • 133
  • 1
  • 8
1

The following should do the trick. It also handles fractions of x.

y = [
    5, 6, 7, 3, 8, 10, 5, 2, 8, 15,
    9, 10, 9, 9, 8, 9  # additional corner cases
]
y0 = 9
intersecting_x = [
    float(x + (y0 - y[x]) / (y[x+1] - y[x]) if y[x+1] != y[x] else x + 1)
    for x in range(len(y)-1)
    if y[x+1] == y0 or y[x] < y0 < y[x+1] or y[x] > y0 > y[x+1]
]
print(intersecting_x)

# [4.5, 5.2, 8.142857142857142, 10.0, 12.0, 13.0, 15.0]
André C. Andersen
  • 8,955
  • 3
  • 53
  • 79