"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Find Exact Zero and Non-Zero Intercepts on Plots Using Linear Interpolation in Python?

How to Find Exact Zero and Non-Zero Intercepts on Plots Using Linear Interpolation in Python?

Published on 2024-11-04
Browse:198

How to Find Exact Zero and Non-Zero Intercepts on Plots Using Linear Interpolation in Python?

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")
Release Statement This article is reprinted at: 1729465881 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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