Search code examples
pythonnumerical-methodsequationnonlinear-functionsfixed-point-iteration

Solve this equation with fixed point iteration method in python


f(x) = x^2- 2x - 3 = 0

How can I solve this equation non-linear, and used fixed point iteration method in Python ?


Solution

  • Fixed Point Iteration

    f(x) = x^2-2x-3 = 0 ⇒ x(x-2) = 3 ⇒ x = 3/(x-2)

    import math
    
    def g(x):
       if 2 == x:
           return x + 1e-10
       return 3/(x-2)
    
    def quadratic(ff,x=0):
        while abs(x-ff(x)) > 1e-10:
            x = ff(x);
        return x
    
    print(quadratic(g))
    

    -1

    root finding formula

    # -*- coding:utf8 -*-
    import math
    def quadratic(a, b, c):
        ''' ax² + bx + c = 0
            return
            True  : all real number
            Fasle :  no solutions
            (x1,x2)
        '''
        if not isinstance(a, (int, float)):
            raise TypeError('a is not a number')
        if not isinstance(b, (int, float)):
            raise TypeErrot('b is not a number')
        if not isinstance(c, (int, float)):
            raise TypeError('c is not a number')
        derta = b * b - 4 * a * c
        if a == 0:
            if b == 0:
                if c == 0:
                    return True
                else:
                   return False
            else:
                x1 = -c / b
                x2 = x1
                return x1, x2
        else:
            if derta < 0:
                return False
            else:
                x1 = (-b + math.sqrt(derta)) / (2 * a)
                x2 = (-b - math.sqrt(derta)) / (2 * a)
                return x1, x2
    
    print(quadratic(1, -2, -3))
    

    (3.0, -1.0)