首页  >  文章  >  后端开发  >  如何在Python中找到曲线与Y轴和其他曲线的交点?

如何在Python中找到曲线与Y轴和其他曲线的交点?

Barbara Streisand
Barbara Streisand原创
2024-10-21 07:12:02731浏览

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>

两条曲线的交点

要找到两条曲线之间的交点,请找到两条曲线之间差异的零点:

<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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn