首页 文章

矢量化fsolve /求解多个非线性方程的多个值

提问于
浏览
1

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 抛出:'IndexError: too many indices for array'我尝试了一些不同的方式,但除了使用简单的for循环,我无法解决任何功能上的代码 . 有什么建议?

2 回答

  • 0

    使用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 控制正在运行的并发作业数 .

  • 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 ]
    

相关问题