Thursday 25 August 2016

Coding the well known Bisection Method

Getting root of an equation by Bisection Method through C programming language.

The Method:
The method is applicable for numerically solving the equation f(x) = 0 for the real variable x, where f is a continuous function defined on an interval [ab] and where f(a) and f(b) have opposite signs. In this case a and b are said to bracket a root since, by the intermediate value theorem, the continuous function f must have at least one root in the interval (ab).
At each step the method divides the interval in two by computing the midpoint c = (a+b) / 2 of the interval and the value of the function f(c) at that point. Unless c is itself a root (which is very unlikely, but possible) there are now only two possibilities: either f(a) and f(c) have opposite signs and bracket a root, or f(c) and f(b) have opposite signs and bracket a root.[5] The method selects the subinterval that is guaranteed to be a bracket as the new interval to be used in the next step. In this way an interval that contains a zero of f is reduced in width by 50% at each step. The process is continued until the interval is sufficiently small.
Explicitly, if f(a) and f(c) have opposite signs, then the method sets c as the new value for b, and if f(b) and f(c) have opposite signs then the method sets c as the new a. (If f(c)=0 then c may be taken as the solution and the process stops.) In both cases, the new f(a) and f(b) have opposite signs, so the method is applicable to this smaller interval.


SOURCE CODE:


#include<stdio.h>
float f(float x)
{
    float z;
    z= x*x*x-4*x-9;
    return z;
}// Getting the value of f(x)
void main()
{


    printf("\n \n Equation is \tx^3-4x-9\n");
    int n;
    float c,i,a,b,r,A,B,C;
    printf("\n Enter the number of iterations\n");
    scanf("%d",&n);// n is the number of the iterations

    for(i=0.0;i<3.0;i=i+0.001)
    {
        if(f(i)<0.001)
        {
            a=i;

            }
    }
    b=a+0.01;
//Here a and b variables are the intervals
    printf("Root lies between %f and %f ", a,b);
do
{
    c=(a+b)/2;
   if(f(a)*f(c)<0)
    b=c;
   if(f(b)*f(c)<0)
    a=c;

    r=f(c);
    --n;
}while(n!=0);
printf("\n Root is %f \n",(a+b)/2);


}

No comments:

Post a Comment