ホームページ  >  記事  >  バックエンド開発  >  Python で曲線と Y 軸および他の曲線の交点を見つける方法

Python で曲線と Y 軸および他の曲線の交点を見つける方法

Barbara Streisand
Barbara Streisandオリジナル
2024-10-21 07:12:02732ブラウズ

How to Find the Intersection Points of a Curve with the Y-Axis and Other Curves in Python?

曲線のゼロ交差点の決定

Python で、曲線が y 軸と交差する正確な点 (y=0) を見つけます。 ) 難しいかもしれません。 numpy 配列は曲線を表す可能性がありますが、ゼロを識別する直接的な方法は提供されません。

この問題に対処するには、線形補間アプローチを使用できます。次のコードは、正確な交点を見つける方法を示しています:

<code class="python">import numpy as np
import matplotlib.pyplot as plt

# Generate sample data
N = 750
x = 0.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 a function to find roots (zeros)
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 the intersection point
z = find_roots(x, y)

# Plot the curve and the intersection point
plt.plot(x, y)
plt.plot(z, np.zeros(len(z)), marker="o", ls="", ms=4)
plt.show()</code>

このスクリプトは、Y 軸との正確な交点に曲線とマーカーを示すプロットを生成します。

ゼロ以外の値での切片の検索

ゼロ以外の値 (例: y0) での切片を見つけるには、y0 だけシフトされた曲線のゼロを見つけることによって同じアプローチを適用できます。

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

2 つの曲線の交差点

2 つの曲線間の交点を見つけるには、2 つの曲線の差のゼロを見つけます:

<code class="python">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

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>

以上がPython で曲線と Y 軸および他の曲線の交点を見つける方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。