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

守給你的承諾、 提交于 2019-12-22 05:36:07

问题


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.

回答1:


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)



回答2:


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)



回答3:


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



来源:https://stackoverflow.com/questions/13360062/python-curves-intersection-with-fsolve-and-function-arguments-using-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!