2. Write a program to demonstrate Regula-Falsi Method


    /*Program to demonstrate Tegula-Falsi Method */
    #include <stdio.h>
    #include <math.h>
    double f(float x)
    {
        double val = 0.0;
        val = x * x * x + x - 3;
        return val;
    }
    void main()
    {
        int max, count = 0;
        float x0, x1, x2, aerr;
        double err, y0, y1, y2;
        printf("Enter initial guesses,no of iterations and maximum iteration error: ");
        scanf("%f%f%d%f", &x0, &x1, &max, &aerr);
        while (count < max)
        {
            y0 = f(x0);
            y1 = f(x1);
            if (y0 == 0)
            {
                printf("Root is %f", x0);
                return;
            }
            else if (y1 == 0)
            {
                printf("Root is %f", x1);
                return;
            }
            else if (y0 * y1 > 0)
            {
                printf("Unsuitable starting values");
                return;
            }
            else
            {
                x2 = x0 - ((x1 - x0) / (y1 - y0)) * y0;
                y2 = f(x2);
                if (y0 * y2 < 0)
                    x1 = x2;
                else
                    x0 = x2;
                err = fabs(x1 - x2);
                if (err < aerr)
                {
                    count++;
                    printf("\nAfter %d iteration root= \n%f\n", count, x2);
                    return;
                }
                count++;
                printf("Iteration no. %d: x=%f\n", count, x2);
            }
        }
        printf("Solution does't converge ,iterations not sufficient");
        return;
    }
       

Output

    
    Enter initial guesses, number of iterations and maximum iterations error: 
    1 2 14 0.0001
    Iteration number 1: x = 1.125000
    Iteration number 2: x = 1.177982
    Iteration number 3: x = 1.199415
    Iteration number 4: x = 1.207914
    Iteration number 5: x = 1.211257
    Iteration number 6: x = 1.212568
    Iteration number 7: x = 1.213082
    Iteration number 8: x = 1.213282
    Iteration number 9: x = 1.213361
    Iteration number 10: x = 1.213392
    Iteration number 11: x = 1.213404
    Iteration number 12: x = 1.213409
    Iteration number 13: x = 1.213410
            
    After 14 iterations root = 1.213411"