Search code examples
pythonscipynumerical-methodsscipy-optimize

Alternative to scipy function


I need to find the root of a multidimentional function F(x), I'm using the scipy function scipy.optimization.root(...,method=''), which allows me to select different methods for the solution. However, for some problems it becomes slow and not convergent, maybe it would be useful to try an alternative package. Do you know some of them?


Solution

  • Generally, the more you know about the problem the better. For example you may know an approximate range in which the root occurs. Then you may first run a brute search (using np.linspace for example) to find a good starting point for the method you want to use. Example:

    Let's say you have a function like

    def f(x):
        return np.exp(-x)*(x-1)**4
    

    scipy will fail to find a root if you start at x0=5, because of the exponential. However, if you know that the solution is somewhere in (-10,10), you can do something like

    X=np.linspace(-10,10,10)
    x0 = X[ np.argmin( np.abs( f(X) ) ) ]
    
    from scipy.optimize import root
    y=root(f,x0)
    print(y.x)
    

    and you get a nice result (fast!), because np.argmin( np.abs( f(X) ) ) gives you the argument of X where f is closest to 0.

    You have to keep in mind that such "tricks" are also dangerous if you use them without triple checking, and you always should have some intuition (or even better an analytical approximation) on what you expect.