How to do the Bisection method in Python

前端 未结 7 2438
小蘑菇
小蘑菇 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:21

    Basic Technique

    Here's some code showing the basic technique:

    >>> def samesign(a, b):
            return a * b > 0
    
    >>> def bisect(func, low, high):
        'Find root of continuous function where f(low) and f(high) have opposite signs'
    
        assert not samesign(func(low), func(high))
    
        for i in range(54):
            midpoint = (low + high) / 2.0
            if samesign(func(low), func(midpoint)):
                low = midpoint
            else:
                high = midpoint
    
        return midpoint
    
    >>> def f(x):
            return -26 + 85*x - 91*x**2 +44*x**3 -8*x**4 + x**5
    
    >>> x = bisect(f, 0, 1)
    >>> print(x, f(x))
    0.557025516287 3.74700270811e-16
    

    Tolerance

    To exit early when a given tolerance is achieved, add a test at the end of the loop:

    def bisect(func, low, high, tolerance=None):
        assert not samesign(func(low), func(high))   
        for i in range(54):
            midpoint = (low + high) / 2.0
            if samesign(func(low), func(midpoint)):
                low = midpoint
            else:
                high = midpoint
            if tolerance is not None and abs(high - low) < tolerance:
                break   
        return midpoint
    

提交回复
热议问题