Search code examples
pythonscipymathematical-optimization

Finding the root of a multivariate function at different variable values with Python


I a have a function of two variables and need to find the root of this function for a large number of different values for the other variable. What is the best way of doing this?

I can do it with loops, but I assume that there is a much better way of going about it.

import scipy as sp
def g(y,x):
    return x**2+y
for i in range(1000):
    sp.optimize.fsolve(g,0,i)

Solution

  • As @Zhenya comments you can make your function vector-based. Actually it already is and you can just call

    xs = arange(1000) 
    sp.optimize.fsolve(g,zeros_like(xs), xs)
    

    However, this way you are making fsolve think that it has one 1000-dimensional COUPLED problem, not 1000 uncoupled problems.

    Thus a loop is probably the best thing to do.

    I would suggest that you use the results of the last iteration as the new initial guess for the next iteration something like

    y_root = .0
    for i in range(1000):
        y_root = sp.optimize.fsolve(g,y_root,i)