[英]Solving nonlinear systems of equations using Python's fsolve function
[英]Vectorizing fsolve/ solving multiple nonlinear equations for multiple values
fsolve 从初始估计中找到(一个系统)非线性方程的解。 我可以向量化的多个起始点我的函数调用来使用fsolve,有可能找到多种解决方案,如解释在这里。 在这个问题中,描述了如何使用 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:数组的索引太多'我尝试了一些不同的方法,但除了使用简单的 for 循环之外,我无法计算出任何功能代码。 有什么建议?
使用 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
控制有多少并发作业正在运行。
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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.