How to do the Bisection method in Python

前端 未结 7 2436
小蘑菇
小蘑菇 2021-02-15 15:05

I want to make a Python program that will run a bisection method to determine the root of:

f(x) = -26 + 85x - 91x2 +44x3 -8x4 + x5

The Bisecti

7条回答
  •  野的像风
    2021-02-15 15:26

    It is possible to modify the Bisection-method above with a tolerance as the stopper:

    def samesign(a, b):
            return a*b > 0
    
    def bisect(func, low, high):
        assert not samesign(func(low), func(high))
        n = 20
        e = 0.01 # the epsilon or error we justify for tolerance
        for i in range(n):
            if abs(func(low)-func(high)) > e:
                midpoint = (low + high) / 2
                print(i, midpoint, f(midpoint))
                if samesign(func(low), func(midpoint)):
                    low = midpoint
                else:
                    high = midpoint
            else:
                return round(midpoint, 2)
        return round(midpoint, 2)
    

提交回复
热议问题