Monday, December 9, 2013

Newton Raphson Method to solve non-linear equations

Introduction

It is one of the most widely used methods of solving equation as it is more rapidly convergent than other methods. Starting from single initial estimate, x0, that is not too far from a root, we move along the tangent to its intersection with the x-axis, and take that as the next approximation. This is continued as
x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} \,
until either the successive x-values are sufficiently close or the value of the function is sufficiently near zero.


Newton Raphson Method in Codes

/*A program to find a root of function using Newton Raphson Method */

#include<stdio.h>
#include<math.h>

float f(float x)
{
    return x*sin(x) + cos(x);
}

float g(float x)
{
    return x*cos(x);        /* Derivative of function f(x) */
}

int main()
{
    float x0, x1, a, b, c;

    printf("Enter the 'a' and 'b' of interval (a,b)\n\n");
    scanf("%f%f",&a,&b);

    x0= (a+b)/2;

    for(c=0;c<20;c++)     /* The loop is repeated just 20 times as this method is expected to give root in 5/10 steps generally */
    {
        if(g(x0)==0)
            printf("\n\nErooooooooorrrrrr");
        else
            x1 = x0 - f(x0) / g(x0);

        x0=x1;
    }

    printf("\n\nThe required root is %f\n\n",x0);
    return 0;

}

No comments:

Post a Comment