首頁  >  文章  >  後端開發  >  如何在 Python 中確定資料點的精確 y 軸交點?

如何在 Python 中確定資料點的精確 y 軸交點?

Patricia Arquette
Patricia Arquette原創
2024-10-21 07:15:02908瀏覽

How to Determine the Exact y-Axis Intersection of Data Points in Python?

尋找資料點與 y 軸的精確交點

在 Python 中繪製資料時,取得曲線與 y 軸相交的精確值非常有用 y 軸。該值可以使用數值方法確定,特別是透過線性內插法。

使用線性插值的解決方案

以下程式碼示範如何使用線性內插法來找出資料數組的零交叉點:

<code class="python">import numpy as np

# Generate sample data
N = 750
x = .4 + np.sort(np.random.rand(N)) * 3.5
y = (x - 4) * np.cos(x * 9.) * np.cos(x * 6 + 0.05) + 0.1

# Define function to find roots (zero crossings)
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)

# Find zero crossings
z = find_roots(x, y)

# Plot data and zero crossings
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, np.zeros(len(z)), marker="o", ls="", ms=4)
plt.show()</code>

非零y 值截距的逆圖

可以修改上述方法,透過找出y 的零點來找出非零y 值(y0) 的截距- y0:

<code class="python">y0 = 1.4
z = find_roots(x, y - y0)
plt.plot(z, np.zeros(len(z)) + y0)</code>

兩條曲線之間的交點

與第一種方法類似,找到兩條曲線之間的交點涉及到找到兩個資料數組之間差異的零點:

<code class="python"># Generate sample data
x = .4 + np.sort(np.random.rand(N)) * 3.5
y1 = (x - 4) * np.cos(x * 9.) * np.cos(x * 6 + 0.05) + 0.1
y2 = (x - 2) * np.cos(x * 8.) * np.cos(x * 5 + 0.03) + 0.3

# Find intersection points
z = find_roots(x, y2 - y1)

# Plot data and intersection points
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>

以上是如何在 Python 中確定資料點的精確 y 軸交點?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn