python求两条直线的交点,在Python中两个图形的交点,找到x值

Let 0 <= x <= 1. I have two columns f and g of length 5000 respectively. Now I plot:

plt.plot(x, f, '-')

plt.plot(x, g, '*')

I want to find the point 'x' where the curve intersects. I don't want to find the intersection of f and g.

I can do it simply with:

set(f) & set(g)

解决方案

You can use np.sign in combination with np.diff and np.argwhere to obtain the indices of points where the lines cross (in this case, the points are [ 0, 149, 331, 448, 664, 743]):

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 1000)

f = np.arange(0, 1000)

g = np.sin(np.arange(0, 10, 0.01) * 2) * 1000

plt.plot(x, f, '-')

plt.plot(x, g, '-')

idx = np.argwhere(np.diff(np.sign(f - g))).flatten()

plt.plot(x[idx], f[idx], 'ro')

plt.show()

e0be882f2b321089a50d7f373eb6286a.png

First it calculates f - g and the corresponding signs using np.sign. Applying np.diff reveals all the positions, where the sign changes (e.g. the lines cross). Using np.argwhere gives us the exact indices.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值