【问题标题】:Vectorizing fsolve/ solving multiple nonlinear equations for multiple values向量化 fsolve/为多个值求解多个非线性方程
【发布时间】:2018-07-18 12:51:21
【问题描述】:

fsolve 从初始估计中找到非线性方程组的解。我可以矢量化我的函数调用以在多个起点上使用 fsolve 并可能找到多个解决方案,如 here 所述。在this 问题中描述了如何使用 fsolve 求解多个非线性方程。但是,我在将两者结合起来时遇到问题,即从多个起始值求解多个非线性方程。我知道我总是可以遍历我的起始值并使用第二个帖子的答案,但是,必须这样做可能超过 100000 点,我真的想找到一个更 Pythonic(并且希望更快)的解决方案。

我尝试了不同的方法,例如以下(以及许多其他方法):

from scipy.optimize import fsolve
import numpy as np

def equations(x): # x+y^2-4, sin(x)+x*y-3
    ret = np.array([x[:,0]+x[:,1]**2-4, np.sin(x[:,0]) + x[:,0]*x[:,1] - 3]).T
    return ret

p1 = np.array([0,0]) # first initial value
p2 = np.array([1,1]) # second initial value
x0 = np.array([p1,p2])

print(x0[0,1])
print(equations(x0))
print(fsolve(equations, x0=x0))

形状和所有的工作,但fsolve throws: 'IndexError: too many indices for array' 我尝试了一些不同的方法,但是除了使用简单的 for 循环之外,我无法在此上解决任何功能代码。有什么建议吗?

【问题讨论】:

    标签: python numpy equation solver


    【解决方案1】:
    def eq(x):
         return x[0] + x[1]**2 - 4 , np.sin(x[0]) + x[0]*x[1] - 3
    
    fsolve(eq, [0, 1])
    
    output: array([ 1.23639399,  1.6624097 ])
    

    在这种情况下,我建议使用蛮力方法:

    x0 = [[i, j] for i, j in zip(range(10), range(10))]
    
    for xnot in x0:
        print(fsolve(eq, xnot))
    
    [  1.33088471e-07   2.09094320e+00]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    [ 1.23639399  1.6624097 ]
    

    【讨论】:

    • 这会从起点 (0,1) 找到一个解决方案。我想要一次有几个解决方案。
    • 我将其添加到我的答案中。然后使用 np.isclose() 筛选出相同的答案。
    • 我提到我知道我可以在 for 循环中做到这一点,我正在寻找矢量化版本
    【解决方案2】:

    使用 joblib 怎么样?这不是直接的向量化,而是不同的起点会并行执行。

    from scipy.optimize import fsolve
    import numpy as np
    from joblib import Parallel, delayed
    
    def equations(x): # x+y^2-4, sin(x)+x*y-3
        ret = np.array([x[0]+x[1]**2-4, np.sin(x[0]) + x[0]*x[1] - 3]).T
        return ret
    
    p1 = np.array([0,0]) # first initial value
    p2 = np.array([1,1]) # second initial value
    x0 = [p1, p2]
    
    sol = Parallel(n_jobs=2)(delayed(fsolve)(equations, x0=p) for p in x0)
    print(sol)
    

    参数n_jobs 控制有多少并发作业正在运行。

    【讨论】:

    • 我以前从未听说过joblib,但我要看看它谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多