2

I'm trying to find all the intersection points of two graphs and display them on the final plot. I've looked around and tried multiple things, but I haven't been able to obtain what l'm looking for.

Currently, I attempting to generate a list wherein the intersection points would be listed, though I keep getting the following error:

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()
FunkySayu
  • 7,641
  • 10
  • 38
  • 61
Nicolas
  • 21
  • 1
  • 1
  • 2

2 Answers2

1

It's similar to:

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

edit: you don't use a function, but a list of values

Community
  • 1
  • 1
Piotr Pęczek
  • 410
  • 7
  • 14
0

For single solutions, this is answered in 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)

Now, you just need to iterate through your range to get all the roots. This gives some duplicates, which you might be able to remove by using mpmath, setting the precision low enough, and using a set.

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)))
serv-inc
  • 35,772
  • 9
  • 166
  • 188