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

[수치해석] Newton-Raphson Method Matlab Code

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

1. 미분 직접 하는 버전(input으로 받음)

function [root, ea, iter] = newtraph(func, dfunc, xr, es, maxiter)

% [root, ea, iter] = newtraph(func, dfunc, xr, es, maxiter):
%     uses Newton-Raphson method to find the root of func
%     
% input: 
%     func = name of function
%     dfunc = name of derivative of function
%     xr = initial guess
%     es = disired relative error (defaut = 1.0%)
%     maxiter = maximum number of iterations (default = 10)
%     
% output:
%     root = real root
%     ea = appriximate relative error (%)
%     iter = number of iterations used
    
if ( nargin < 3 )
    error('at least 3 input arguments required');
end

if ( nargin < 4 )
    es = 1.0;
end

if ( nargin < 5 )
    maxiter = 10;
end

iter = 1;
xt = 2.86010440550741;
fprintf('iter = %d: xr = %.4f\n', iter, xr);

while (1)
    xrold = xr;
    xr = xr - subs(func,xr) / subs(dfunc, xr);
    
    ea = abs((xr - xrold) / xr) * 100;
    et = abs((xt - xr) / xt) * 100;
    % et = true percent relative error
    iter = iter + 1;

    fprintf('iter = %d: xr = %.4f, ea = %.4f, et = %.4f\n', iter, xr, ea, et);

    if (ea <= es) || (iter > maxiter)
        break;
    end 
end

root = xr;

    

2. 함수 안에서 미분하는 버전

function [root, ea, iter] = newtraph(func, xr, es, maxiter)

% [root, ea, iter] = newtraph(func, dfunc, xr, es, maxiter):
%     uses Newton-Raphson method to find the root of func
%     
% input: 
%     func = name of function
%     dfunc = name of derivative of function
%     xr = initial guess
%     es = disired relative error (defaut = 1.0%)
%     maxiter = maximum number of iterations (default = 10)
%     
% output:
%     root = real root
%     ea = appriximate relative error (%)
%     iter = number of iterations used
    
if ( nargin < 2 )
    error('at least 2 input arguments required');
end

if ( nargin < 3 )
    es = 1.0;
end

if ( nargin < 4 )
    maxiter = 10;
end

iter = 1;
dx = 0.00001;

dfunc = (subs(func, xr+dx) - subs(func, xr)) / dx;
fprintf('iter = %d: xr = %.4f\n', iter, xr);

while (1)
    xrold = xr;
    xr = xr - subs(func,xr) / subs(dfunc, xr);
    
    ea = abs((xr - xrold) / xr) * 100;
    iter = iter + 1;

    fprintf('iter = %d: xr = %.4f, ea = %.4f\n', iter, xr, ea);
    
     if (ea <= es) || (iter > maxiter)
        break;
     end 
end

root = xr;

    

newtraph.m
0.00MB
newtraph_2.m
0.00MB

반응형