Friday, May 31, 2013

Newton-Raphson Method (C code for finding a real root of an equation)

This article is about Newton's method for finding roots.

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:
Given a function ƒ defined over the reals x, and its derivative ƒ ', we begin with a first guess x0 for a root of the function f. Provided the function satisfies all the assumptions made in the derivation of the formula, a better approximation x1 is
x_{1} = x_0 - \frac{f(x_0)}{f'(x_0)} \,.
Geometrically, (x1, 0) is the intersection with the x-axis of a line tangent to f at (x0, f (x0)).
The process is repeated as
x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} \,
until a sufficiently accurate value is reached.
This algorithm is first in the class of Householder's methods, succeeded by Halley's method. The method can also be extended to complex functions and to systems of equations.

C code for finding a real root of  the equationf(x)= x*x*x-2*x-5 using Newton-Raphson Method

#include
//#include
#include
int main(){
    //clrscr();
    int i;
    float x,fx,fdx,t;
    printf("Enter x0: ");
    scanf("%f",&x);
    //freopen("file.txt","w",stdout);
    for(;;)
    {
        t=x;
        fx=pow(x,3)-(2*x)-5;
        fdx=3*pow(x,2)-2;
        x=t-(fx/fdx);
        printf("\nthe value of x is::%f\n",x);
        if(fabs(x-t)<=0.0001)
        {
            printf("The root is: %f",x);
            break;
        }
    }
    //fclose(stdout);
    getch();
    return 0;
}

sample output:

Enter x0: 2

the value of x is::2.100000

the value of x is::2.094568

the value of x is::2.094552
The root is: 2.094552

No comments:

Post a Comment