Wednesday, 29 June 2011

Numerical Methods Using MATLAB - Newton-Raphson Method


In this post, we learn about solving Algebraic Equation using Newton's Method (or) Newton-Raphson Method.

Newton's Method:
Given an approximate root of an equation, a closer approximation to the root can be found using Newton's Method.

Let a0 be the approximate root of the equation f(x)=0.
Let a be the exact root nearer to a0.

Then, a = a0 + h
where h is an integer with very small value.

Since a is the exact root of f(x)=0,

f(a) = f(a0+h) = 0

By Taylor's expression,
f(a) = f(a0+h) = f(a0) + hf'(a0) + (h^2/2!)f"(a0)+0000=0

Since, h is small, neglecting higher powers h^2, h^3,....etc, we get

f(a0) + hf'(a0) = 0

h = -(f(a0)/f'(a0))

a1 = a0 + h = a0 - (f(a0)/f'(a0))

a2 = a1 + h = a1 - (f(a1)/f'(a1))

Thus, we again get a sequence of approximate roots which converges to form the exact root on a few iterations depending on the required precision.

Source Code:

% this function that calculates solution of algebraic equation
% using Newton-Raphson method

function NewtonFunc(co,range)
  
% the variable prev stores the first approximate root of the eqn.
% here, we assume it to be the mean of the two points p1 and p2 (say)
% such that, f(p1)<0 and f(p2)>0

prev = (range(1) + range(2))/2;

% x is symbol var represented by 'x'
x=sym('x');

% the function 'f' is initialized
f=0;

% n gives the size of the coeff/: vector
[m,n]=size(co);

  % in the loop below, we create the function 'f' using symbol 'x'
% from the coeff/: vector
for i = 1 : n
     % the last element of co vector is the constant
         if i == n
          f = f + co(i);
                end
                % end of if i==n
 
        % adding the terms of the function step by step    
        if co(i) ~= 0  && i ~= n
                  f = f + co(i)*(x^(n-i));
               end
              % end of if
    end
%end of for

% infinite while loop
% where we find the sequence of approximate roots
while ( 1 )
 
% finding the approximate root 
% using Taylor's expansion (neglecting higher powers)
x0=prev-(subs(f,prev)/subs(diff(f),prev));
         
% when the required precision is obtained, break the loop    
if abs( abs(prev) - abs(x0) ) < 0.000001
       break;
end
% end of if
 
% assigning previous value    
prev=x0;
    end
% end of while
disp(x0);
end
% end of function

0 comments:

Post a Comment

தங்களது கருத்துக்களை இங்கே வெளியிடவும்...

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More