Wednesday, June 7, 2017

The Newton's Method Matlab, Numerical Method


In numerical analysis, Newton's method (also known as the Newton–Raphson method), named after Isaac Newton and Joseph Raphson, is a method for finding successively better approximations to the roots (or zeroes) of a real-valued function.
x:f(x)=0\,.
The Newton–Raphson method in one variable is implemented as follows:
The method starts with a function f defined over the real numbers x, the function's derivative f ′, and an initial guess x0 for a root of the function f. If the function satisfies the assumptions made in the derivation of the formula and the initial guess is close, then a better approximation x1 is
x_{1}=x_{0}-{\frac {f(x_{0})}{f'(x_{0})}}\,.
Geometrically, (x1, 0) is the intersection of the x-axis and the tangent of the graph of f at (x0, f (x0)).
The process is repeated as
x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}\,
Matlab Sript

clear all
clc


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                    %
%             KONG THEARA            %
% Institut of Techonlogy of Cambodia %
%                                    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% Funtion
syms x
f = @(x) exp(-x)-x^2+x^3
deriv = inline(diff(f(x),x),'x');

%Condition
xi=4;
xj = 0;
i = 0;
es = 1e-16;

% While loop will break when hit the condition and return a root

while(1)
    ea=abs(((xj-xi)/xj)*100); % Calculate the error
    xi = xj;
    xj = xi - f(xi)/deriv(xi); % Calculate root by x
    i = i+1;
   
    % Break and return root if error <= 1e-16 or iteration >=1000
    if ea <= es || i >= 1000
        root = xj
        break
    end
end


% Enjoy the Newton's Method