简体   繁体   English

找到两条曲线之间的交点

[英]Find intersection point between two curves

I have two curves ( supply and demand ) and I want to find their intersection point (both, x and y ).我有两条曲线( supplydemand ),我想找到它们的交点( xy )。 I was not able to find a simple solution for the mentioned problem.我无法找到上述问题的简单解决方案。 I want my code in the end to print what is the value of X and what is the value of Y .我希望我的代码最终打印出X的值和Y的值。

supply = final['0_y']
demand = final['0_x']
price = final[6]
plt.plot(supply, price)
plt.plot(demand, price)

The main problem and challenge (something wrong) are that I have tried every other method, and every single time I get an empty set/list.主要问题和挑战(有问题)是我尝试了所有其他方法,并且每次我得到一个空集/列表。 Even when I try to visualize the intersection, I also get empty visual.即使当我试图想象交叉点时,我也会得到空洞的视觉效果。

GRAPH:图形:
在此处输入图像描述

As the implementation of the duplicate is not straightforward, I will show you how you can adapt it to your case.由于副本的实现并不简单,我将向您展示如何使其适应您的情况。 First, you use pandas series instead of numpy arrays, so we have to convert them.首先,您使用 pandas 系列而不是 numpy arrays,因此我们必须对其进行转换。 Then, your x- and y-axes are switched, so we have to change their order for the function call:然后,您的 x 轴和 y 轴被切换,因此我们必须为 function 调用更改它们的顺序:

import pandas as pd          
import matplotlib.pyplot as plt  
import numpy as np 


final = pd.DataFrame({'0_y': [0, 0, 0, 10, 10, 30], 
                      '0_x': [20, 11, 10, 4, 1, 0,], 
                      "6": [-200, 50, 100, 200, 600, 1000]})

supply = final['0_y'].to_numpy()
demand = final['0_x'].to_numpy()
price = final["6"].to_numpy()
plt.plot(supply, price)
plt.plot(demand, price)


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)

z = find_roots(price, supply-demand)
x4z = np.interp(z, price, supply)


plt.scatter(x4z, z, color="red", zorder=3)
plt.title(f"Price is {z[0]} at supply/demand of {x4z[0]}")

plt.show()

Sample output:样品 output: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM