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

Susan Sarandon
Release: 2024-10-21 07:12:29
Original
690 people have browsed it

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:

<code class="python">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)</code>
Copy after login

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:

<code class="python">z = find_roots(x,y-y0)</code>
Copy after login

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:

<code class="python">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")</code>
Copy after login

The above is the detailed content of How to Find Exact Zero and Non-Zero Intercepts on Plots Using Linear Interpolation in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!