기계공학/Numerical Method (수치해석)

[수치해석] Linear Interpolation Matlab Code

Mech_Mollayo 2021. 4. 17. 08:48
반응형

function [root, ea, iter] = LinearInterpolation(func, xl, xu, es)


if ( nargin < 3 )
    error('at least 3 input arguments required');
end

% input argument를 3개만 쳤을 때, es는 default 값인 0.1로 설정해줌
if nargin < 4
    es = 0.1;
end


test_init = func(xl) * func(xu);

% initial test 값이 0보다 크면 에러를 내라
if test_init > 0
    error('no sign change');
end

iter = 0;
xr = xl;

while (1)
    xrold = xr;
    
    xr = xu - (func(xu) .* (xl - xu))./(func(xl) - func(xu));
    iter = iter + 1;
    
    ea = abs((xr - xrold)/xr) * 100;
    
    if (iter == 1)
        fprintf('iter = %d: xl = %.2f, xu = %.2f\n', iter, xl, xu);
    
    else
        fprintf('iter = %d: xl = %.2f, xu = %.2f, ea = %.2f\n', iter, xl, xu, ea);
    end
    
    
    test = func(xl) * func(xr);
    
    if test < 0
        xu = xr;
    elseif test > 0
        xl = xr;
    else
        ea = 0;
    end
    
    if ea <= es
        break;
    end
    
end

root = xr


   

LinearInterpolation.m
0.00MB

반응형