Finding Curve Intersections with Zero
In Python, obtaining exact y-axis values from a plot can be challenging when the value is not a whole number. This article addresses this issue and presents a solution based on linear interpolation.
Given two arrays (vertical_data and gradient(temperature_data)), a plot is generated using plt.plot. However, the plot displays a y-value that is close to but not exactly zero.
Linear Interpolation for Root Estimation
To estimate the exact root of a numpy array, a simple linear interpolation method can be used. The following code demonstrates how to find the zero values of an arbitrary curve:
import numpy as np
def find_roots(x, y):
s = np.abs(np.diff(np.sign(y))).astype(bool)
return x[:-1][s] np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s]) 1)
x = .4 np.sort(np.random.rand(750))*3.5
y = (x-4)*np.cos(x*9.)*np.cos(x*6 0.05) 0.1
z = find_roots(x,y)
plt.plot(x,y)
plt.plot(z, np.zeros(len(z)), marker="o", ls="", ms=4)
This code identifies the roots of the curve and plots them as circles at the exact y-value of zero.
Non-Zero Intercepts
The same approach can be used to find the intersection of a curve with any non-zero y-value (y0) by modifying the line that finds the roots:
z = find_roots(x,y-y0)
Two Curve Intersections
The linear interpolation method can also be used to find the intersection between two curves. By finding the roots of the difference between the two curves, we can estimate their intersection point:
y2 = (x - 2) * np.cos(x * 8.) * np.cos(x * 5 0.03) 0.3
z = find_roots(x,y2-y1)
plt.plot(x,y1)
plt.plot(x,y2, color="C2")
plt.plot(z, np.interp(z, x, y1), marker="o", ls="", ms=4, color="C1")
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3