2015-07-21 72 views
2

我試圖找到兩個圖的所有交點並將它們顯示在最終圖上。我環顧四周,嘗試了很多東西,但我一直無法獲得我期待的東西。Python - 查找2個圖的所有交點

目前,我試圖生成,其中交叉點會被列出清單,但我不斷收到以下錯誤:

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() 
+0

哪一行會引發錯誤? – soon

回答

1

它類似於:

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() 

編輯:你不使用一個函數,而是一個值列表

0

對於單一的解決方案,這是回答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)))