Tuesday, May 10, 2011

How to find the intersection of two functions

Previously we have seen how to find roots of a function with fsolve, in this example we use fsolve to find an intersection between two functions, sin(x) and cos(x):
from scipy.optimize import fsolve
import pylab
import numpy

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

result = findIntersection(numpy.sin,numpy.cos,0.0)
x = numpy.linspace(-2,2,50)
pylab.plot(x,numpy.sin(x),x,numpy.cos(x),result,numpy.sin(result),'ro')
pylab.show()
In the graph we can see sin(x) (blue), cos(x) (green) and the intersection found (red dot) starting from x = 0.

2 comments:

  1. How can you rewrite it to implement other functions?
    E.g. I have two functions other that sin and cos and want to implement them, but they are not an array; If I try to implement the functions I get an error in spyder saying:
    "minpack.error: Result from function call is not a proper array of floats."

    This is the rewritten code:

    from depairfoil import f_dep
    from indepairfoil import f_ind
    from scipy.optimize import fsolve
    import pylab
    import numpy

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

    result = findIntersection(f_dep,f_ind,0.0)
    x = numpy.linspace(0,1.5,50)
    pylab.plot(x,numpy.array(f_dep(x)),x,numpy.array(f_ind(x)),result,f_dep(result),'ro')
    pylab.show()

    ReplyDelete
  2. You can use all the kind of function you want but the fsolve takes in input a function that returns a scalar. In my case, the input of fsolve is 'fun1(x) - fun2(x)' and it returns a scalar.

    ReplyDelete

Note: Only a member of this blog may post a comment.