【问题标题】:Python curves intersection with fsolve() and function arguments using numpyPython 曲线与 fsolve() 的交集和使用 numpy 的函数参数
【发布时间】:2012-11-13 11:35:48
【问题描述】:

我正在尝试使用此处引用的 fsolve:http://glowingpython.blogspot.gr/2011/05/hot-to-find-intersection-of-two.html

为了找到两条曲线之间的交点。两条曲线基本上都是两个浮点数组。

第一个是一维数组Pmech ( Pmech(x) ),第二个是二维数组Pair ( Pair(x,y) )

x 轴对两个数组都是通用的,所以我想要做的是让每个 y 看看 Pair 和 Pmech 相交的位置。

我知道fsolve() 将函数作为参数,而不是数组,因此我编写了两个基本函数来实现此功能:

def Pmix(x):
    return Pmech[x]

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

如上链接所示,我实现了findIntersection 函数:

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

但我收到以下错误:

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.

【问题讨论】:

    标签: python numpy intersection curves


    【解决方案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】:

      在您的示例中,如果没有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))

        是一个生成器

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

        是一个列表。你需要后者。

        但是,正如 btel 在另一个答案中提到的那样,对于数组中的交集,您不能只重用用于查找函数交集的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-13
          • 1970-01-01
          相关资源
          最近更新 更多