天天看點

不動點疊代法的matlab實作

不動點疊代法(Fixed point iteration method)

原理網上已經很多了,這裡不再贅述。

需要注意的是不動點疊代法的使用條件。

舉個簡單的例子,利用不動點法求解方程

f(x) = 1 + 0.5*sin(x) − x = 0

在(1,2)區間的根。

令g(x)=1+0.5*sin(x)

g = @(x) fun2(x);
% Initialization
x0 = 0;
tol = 1e-5;
maxIter = 40;

% Test biSection function
[xStar,xRoot] = fixPoint(g,x0,tol,maxIter);
fprintf('The fixed point is: %d\n',xStar);
fprintf('The root of the equation is: %d\n',xRoot);

function [xStar,xRoot] = fixPoint(fun2,x0,tol,maxIter)
% Inputs:
% fun2: a function handle, standing for the function written above
% x0: the initial guess of the fixed point
% tol: the tolerance within which the program can stop
% maxIter: the maximum number of iterations the program is allowed to run
% Outputs:
% xStar: the numerical value of the fixed point
% xRoot: the numerical value of the root

    x = zeros(maxIter,1);
    x(1) = fun2(x0);
    i = 1;

    while abs(fun2(x(i))-x(i))>tol && i<maxIter
        x(i+1) = fun2(x(i));
        xStar = x(i);
        i = i+1;
    end
    xRoot = x(i);

end

function gx = fun2(x)
    gx = 1+0.5*sin(x);
end

           

繼續閱讀