![](/img/trans.png)
[英]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.