3. Write a program to demonstrate Newton-Raphson Method.

            
    #include <stdio.h>
    #include <math.h>
    double f(float x)
    {
        double val = 0.0;
        val = x * x * x + x * x - 1;
        return val;
    }
    double diff(float x)
    {
        double val = 0.0;
        val = 3 * x * x + 2 * x;
        return val;
    }
    void main()
    {
        int i, n, max, count = 0;
        float x0, x1, aerr;
        double err, y0, dy0;
        printf("Enter initial guess, number of iterations and maximum allowed error: \n");
        scanf("%f%d%f", &x0, &max, &aerr);
        while (count < max)
        {
            y0 = f(x0);
            dy0 = diff(x0);
            if (y0 == 0)
            {
                printf("Root is %f ", x0);
                return;
            }
            else
            {
                x1 = x0 - (y0 / dy0);
                err = fabs(x1 - x0);
                if (err < aerr)
                {
                    count++;
                    printf("\nAfter %d iterations root=%f\n", count, x1);
                    return;
                }
                count++;
                x0 = x1;
                printf("Iteration no. %d: x=%f\n", count, x0);
            }
        }
        printf("Solution does not converge,iterations not sufficient");
        return;
    }

            

Output

           
    Enter initial guess, number of iterations and maximum allowed error: 
    4 10 0.008
    Iteration no. 1: x=2.589286
    Iteration no. 2: x=1.677368
    Iteration no. 3: x=1.123514
    Iteration no. 4: x=0.845007
    Iteration no. 5: x=0.762180

    After 6 iterations root=0.754931