Search root in python

Edit: The big problem is that it scipy.optimize.brentqrequires the limits of the search interval to have the opposite sign. If you cut your search interval into arbitrary sections and run brentqin each section, as I do below, and, as Dan says in the comments, you throw a lot of worthless ValueErrors. Is there an affordable way to handle this in Python?

Original post: I repeatedly look at functions for their largest zero in python. Right now I am using scipy.optimize.brentqto search for the root, and then using the cruel search method if my initial grades do not work:

#function to find the largest root of f
def bigRoot(func, pars):
    try:
        root = brentq(func,0.001,4,pars)
    except ValueError:
        s = 0.1
        while True:
            try:
                root = brentq(func,4-s,4,pars)
                break
            except ValueError:
                s += 0.1
                continue
    return root

There are two big problems with this.

, , brentq . , , -, , , .

, script , , , bigRoot, 0. 0,1 0,01, . , , bigRoot, , , .

, python?


, ; .

, , , . ( ).

I'd like to find the largest root of this function

0 (, , ), , . 1, . , ( , 10 ^ -3).

from numpy import exp as e
#this isn't the function I plotted
def V(r):
    return  27.2*(
                23.2*e(-43.8*r) + 
                8.74E-9*e(-32.9*r)/r**6 - 
                5.98E-6*e(-0.116*r)/r**4 + 
                0.0529*( 23*e(-62.5*r) - 6.44*e(-32*r) )/r -
                29.3*e(-59.5*r)
            )

#this is the definition of the function in the plot
def f(r,b,E):
    return 1 - b**2/r**2 - V(r)/E

#the plot is of f(r,0.1,0.06)
+4
1

, , Python.

, . , , & pm; 1 , 1.

f(x) = sin(1/(1-x))

, [0,1), .

, , .

: , . brentq , / . .

from scipy.optimize import brentq

# This function should recursively find ALL the roots in the interval
# and return them ordered from smallest to largest.

from scipy.optimize import brentq
def find_all_roots(f, a, b, pars=(), min_window=0.01):
    try:
        one_root = brentq(f, a, b, pars)
        print "Root at %g in [%g,%g] interval" % (one_root, a, b)
    except ValueError:
        print "No root in [%g,%g] interval" % (a, b)
        return [] # No root in the interval

    if one_root-min_window>a:
        lesser_roots = find_all_roots(f, a, one_root-min_window, pars)
    else:
        lesser_roots = []

    if one_root+min_window<b:
        greater_roots = find_all_roots(f, one_root+min_window, b, pars)
    else:
        greater_roots = []

    return lesser_roots + [one_root] + greater_roots

, ~ 0.14.

- brentq, :

print find_all_roots(sin, 0, 10, ())

Root at 0 in [0,10] interval
Root at 3.14159 in [0.01,10] interval
No root in [0.01,3.13159] interval
No root in [3.15159,10] interval
[0.0, 3.141592653589793]

sin 0, & pi;, 2 & pi;, 3 & pi;. . , : f (a) f (b) . , root-find scipy.optimize , .

+5

Source: https://habr.com/ru/post/1545409/


All Articles