Python curves intersection with fsolve() and function arguments using numpy
Asked Answered
A

3

6

I am trying to use fsolve as quoted here : http://glowingpython.blogspot.gr/2011/05/hot-to-find-intersection-of-two.html,

On order to find the intersection between two curves. Both curves basically are two arrays of floats.

The first of them is a one dimension array Pmech ( Pmech(x) ) and the second is a two dimension array Pair ( Pair(x,y) )

The x - axis is common for both arrays ,so what i want to do is for every y to see where Pair and Pmech intersect.

I am aware of the fact that fsolve() take as arguments functions, not arrays so I wrote two basic functions to implement this feature:

def Pmix(x):
    return Pmech[x]

def Paera(x,y):
    return Pair[x,y]

So as demonstrated in the above link I implemented the findIntersection function :

def findIntersection(fun1,fun2,x0): 
    return fsolve(lambda x: (fun1(x) - fun2(x,y) for y in range(1,100)),x0)

but I get the following error :

TypeError: float() argument must be a string or a number
Traceback (most recent call last):
  File "batteries.py", line 261, in <module>
    findIntersection(Pmix,Paera,0)
  File "batteries.py", line 238, in findIntersection
    fsolve(lambda x: (fun1(x) - fun2(x,y) for y in range(1,100) ),x0)
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 125, in fsolve
    maxfev, ml, mu, epsfcn, factor, diag)
minpack.error: Result from function call is not a proper array of floats.
Albertoalberts answered 13/11, 2012 at 11:35 Comment(0)
C
3
from scipy.optimize import fsolve

def pmix(x):
    return x

def paera(x, y):
    return x**2 - y**2

def findIntersection(fun1, fun2, x0):
    return [fsolve(lambda x:fun1(x)-fun2(x, y), x0) for y in range(1, 10)]

print findIntersection(pmix, paera, 0)
Countryman answered 13/11, 2012 at 11:52 Comment(0)
E
3

It seems that in your example you might solve it much easier without fsolve:

import numpy as np
pair = np.array(pair)
pmech = np.array(pmech)

intersect_x=np.abs(pair-pmech[:,None]).argmin(0)
Exhume answered 13/11, 2012 at 11:53 Comment(0)
G
1

(fun1(x) - fun2(x,y) for y in range(1,100))

is a generator

[fun1(x) - fun2(x,y) for y in range(1,100)]

is a list. You need the latter.

However, as btel mentions in the other answer, for intersections in arrays, you cannot just reuse code used for finding intersections of functions.

Grogan answered 13/11, 2012 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.