Multivariate Root Finding in Python

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-27 07:58:37

问题


Using excel solver, it is easy to find a solution (optimum value for x and y )for this equation:

(x*14.80461) + (y * -4.9233) + (10*0.4803) ≈ 0

However, I can't figure out how to do this in Python. The existing scipy optimize library function like fsolve() or leastsq() seems to work with only one variable.... (I might just not know how to use them)...

Any suggestions?

Thanks!


回答1:


>>> def f(x):
...     return x[0]*14.80461 + x[1]*(-4.9233) + x[2]*(10*0.4803) 
>>> def vf(x):
...    return [f(x), 0, 0]
>> xx = fsolve(vf, x0=[0,0,1])
>>> 
>>> f(xx)
8.8817841970012523e-16

Since the solution is not unique, different initial values for an unknown lead to different (valid) solutions.

EDIT: Why this works. Well, it's a dirty hack. It's just that fsolve and its relatives deal with systems of equations. What I did here, I defined a system of three equations (f(x) returns a three-element list) for three variables (x has three elements). Now fsolve uses a Newton-type algorithm to converge to a solution.

Clearly, the system is underdefined: you can specify arbitrary values of two variables, say, x[1] and x[2] and find x[0] to satisfy the only non-trivial equation you have. You can see this explicitly by specifying a couple of initial guesses for x0 and see different outputs, all of which satisfy f(x)=0 up to a certain tolerance.



来源:https://stackoverflow.com/questions/14416404/multivariate-root-finding-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!