简体   繁体   中英

Python - bisection method crashes whole application

I have strange problem with my window application. It's task is to compute roots of polynomial of n-degree with bisection method or secant method, it depends on user will. And now my problem starts because if I will put certain interval into the method, it crashes sometimes after first click of star button but if it makes through first time, on second time if I adjust interval [a,b] and punt into "a" result of first go, it crashes without error. I'm not even mentioning that my secant method is going nuts, for some intervals answers are good, for some they are just random.

    def secant(self,f, a, b, err):
        fb=f(b)
        while np.absolute(fb)>err:
            midPoint=b-(b-a)*fb/(fb-f(a))
            a=b
            b=midPoint
            fb=f(b)
        return b
#--------------------------------------------------------------
    def bisection(self,f,a,b,err):
        while np.absolute(b-a)>err:
            midPoint=(a+b)*0.5
            if f(midPoint)*f(a)<0:
                b=midPoint
            midPoint=(a+b)*0.5
            if f(midPoint)*f(b)<0:
                a=midPoint
            midPoint=(a+b)*0.5
        return midPoint
def bisect(f, a, b, e):
    """ Bisection Method

    inputs:
    f - a function.
    a - Starting interval
    b - Ending interval
    e - Acceptable value for 0; (e.g. consider 0.001 == 0)
    """

    iterations = 0
    while True:
        c = (a + b)/2
        if b - c <= e:
            print('Iterated:', iterations, 'times.')
            return c
        elif f(b)*f(c) <= 0:
            a = c
        else:
            b = c
        iterations += 1

Check out more here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM