Python查找两个图的所有交点

2024-05-14 08:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到两个图形的所有交点,并在最终的绘图中显示它们。我环顾四周,尝试了很多东西,但我没能得到我想要的东西。

目前,我正在尝试生成一个列表,其中列出了交叉点,尽管我一直得到以下错误:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt


x = np.arange(-7.0, 7.0, 0.05)

def y(x):
    return np.sin(x)*(0.003*x**4 - 0.1*x**3 + x**2 + 4*x + 3)

def g(x):
    return -10 * np.arctan(x)

def intersection(x):
    if (y(x) - g(x)) == 0:
        print y.all(x)

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

plt.show()

Tags: theimport图形绘图列表returnplotdef
2条回答

对于单个解决方案,这在http://glowingpython.blogspot.de/2011/05/hot-to-find-intersection-of-two.html中得到了回答:

from scipy.optimize import fsolve

def findIntersection(fun1,fun2,x0):
    return fsolve(lambda x : fun1(x) - fun2(x),x0)

result = findIntersection(y,g,0.0)

现在,您只需要遍历您的范围来获得所有根。这将提供一些重复项,可以通过使用mpmath、将精度设置得足够低以及使用集合来删除这些重复项。

from scipy.optimize import fsolve
import numpy as np

rng = np.arange(-7.0, 7.0, 0.05)

def y(x):
    return np.sin(x)*(0.003*x**4 - 0.1*x**3 + x**2 + 4*x + 3)

def g(x):
    return -10 * np.arctan(x)

def findIntersection(fun1,fun2,x0):
    return fsolve(lambda x : fun1(x) - fun2(x),x0)

result = []
for x in rng:
    result.append(float(findIntersection(y,g,x)))

类似于:

Intersection of two graphs in Python, find the x value:

import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt


x = np.arange(-7.0, 7.0, 0.05)

y = np.sin(x)*(0.003*x**4 - 0.1*x**3 + x**2 + 4*x + 3)

g = -10 * np.arctan(x)

def intersection():
    idx = np.argwhere(np.isclose(y, g, atol=10)).reshape(-1)
    print idx

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

    plt.show()

intersection()

编辑:您不使用函数,而是使用值列表

相关问题 更多 >

    热门问题