Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multivariate Root Finding in Python

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!

like image 984
pacifictoy Avatar asked Jan 19 '13 16:01

pacifictoy


1 Answers

>>> 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.

like image 139
ev-br Avatar answered Sep 23 '22 01:09

ev-br