You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Shapely库获取多条曲线交点值的问题

多条曲线交点检测的问题修正

问题根源

  1. x轴不匹配:计算g系列曲线时,使用了独立的np.arange(0,10,0.01)数组,但绘制和构建LineString时却用了x = np.arange(0,1000),导致g曲线的x轴被错误拉伸,数值对应关系混乱,很多交点无法被正确识别。
  2. 交点计算范围局限:当前代码仅计算索引相同的g[i]与f[i]的交点,而非所有g曲线与f曲线的组合交点。

修正后的代码

import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import LineString

# 统一x轴,确保所有曲线基于同一x范围计算
x = np.arange(0, 1000)

# 定义f系列线性曲线
f1 = np.arange(0, 500, 0.5)
f2 = np.arange(0, 1000)
f3 = np.arange(0, 2000, 2)
f4 = np.arange(0, 2000, 2)
f = np.stack((f1, f2, f3, f4))

# 修正g系列曲线的计算,基于统一的x轴
# 保持原有的周期和振幅,调整系数使x范围匹配
g1 = np.sin(x * 0.02) * 500
g2 = np.sin(x * 0.02) * 600
g3 = np.sin(x * 0.02) * 800
g4 = np.sin(x * 0.02) * 1000
g = np.stack((g1, g2, g3, g4))

# 绘制所有曲线
for i in range(len(f)):
    plt.plot(x, f[i], label=f'f{i+1}')
for i in range(len(g)):
    plt.plot(x, g[i], label=f'g{i+1}')

# 构建所有曲线的LineString对象
g_lines = [LineString(np.column_stack((x, g[i]))) for i in range(len(g))]
f_lines = [LineString(np.column_stack((x, f[i]))) for i in range(len(f))]

# 计算所有g曲线与f曲线的交点
all_intersections = []
for g_line in g_lines:
    for f_line in f_lines:
        inter = g_line.intersection(f_line)
        if inter.geom_type in ('Point', 'MultiPoint'):
            all_intersections.append(inter)

# 绘制所有交点
for inter in all_intersections:
    if inter.geom_type == 'MultiPoint':
        plt.plot(*LineString(inter).xy, 'ro')
    elif inter.geom_type == 'Point':
        plt.plot(*inter.xy, 'ro')

plt.legend()
plt.show()

修正说明

  • 统一了所有曲线的x轴,确保g系列曲线的计算与f系列基于同一x数组,解决了数值映射混乱的问题。
  • 使用嵌套循环遍历所有g曲线与f曲线的组合,计算并收集所有交点。
  • 添加了图例方便区分不同曲线,用红色圆点标记所有交点。

内容的提问来源于stack exchange,提问作者shoggananna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:05:26