fsolve根据初始估计值找到(一组)非线性方程组的解。我可以向量化我的函数调用,以在多个起点上使用fsolve,并可能找到多个解决方案,如here所解释的那样。在this问题中,描述了如何用fsolve求解多个非线性方程组。然而,我遇到了将两者结合在一起的问题,即从多个初始值求解多个非线性方程。我知道我总是可以遍历我的起始值并使用第二个posts答案,但是,我必须这样做可能超过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:太多的数组索引‘我尝试了一些不同的方法,但是除了使用一个简单的for循环之外,我不能在这上面写出任何有效的代码。有什么建议吗?
发布于 2018-02-08 07:29:39
使用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
控制正在运行的并发作业的数量。
发布于 2018-02-08 04:41:44
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 ]
https://stackoverflow.com/questions/48677230
复制相似问题