Monday, September 14, 2009

C Program for Bisection Method

Bisection method:
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "iostream.h"
 
int fn[20];
int n;
double a,b,x0;
double fnval;
 
float abso(float x)
{
        if (x<0) return -x;else return x;
}
 
double power(double a,int b)
{
        int i;
        double c=1;
        for (i=0;i<=b;i++)
c=c*a;
        return c;
}
 
void getfunction()
{
        int i;
        printf("Enter the degree of the function: ");
        cin >> n;
        printf("\nStart entering the coefficients\n\n");
        for (i=n;i>=0;i--)
        {
               printf("Enter coefiicient of degree %d: ",i);
               cin >> fn[i];
        }
}
 
void displayfunction()
{
        int i;
        printf("\nCurrent function is:\n ");
        for (i=n;i>-1;i--)
        {
               if (i==0) printf("%d",fn[i]);
               else printf("%dx^%d + ",fn[i],i);
        }
}
 
float getaccuracy()
{
        float no;
        printf("\nEnter the accuracy required: ");
        cin >> no;
        return no;
}
 
double fx(double x)
{
        int i;
        double ans=0;
        for (i=n;i>-1;i--)
        {
               ans=ans+fn[i]*power(x,i);
        }
        return ans;
}
 
void getinitialvals()
{
        float curr=0,prev=0;
        static float left=-100;
        for (int i=left;i<=100;i++)
        {
               curr=fx(i);
               a=i-1;b=i;
               if (curr==0)
               {
                       left=i+1;
                       printf("\nroot is %f",b);
                       getinitialvals();
               }
 
               if (i==99)
               {
                       printf("\n\nThe equation has no further real roots");
                       exit(1);
               }
 
               if (curr*prev<0)
               {
                       left=i;
                       break;
               }
               prev=curr;
        }
}
 
void checkinivals()
{
        if(fx(a)>fx(b))
        {
               double temp=a;
               a=b;
               b=temp;
        }
}
 
 
int main()
{
        int i=0,itr=0;
        int j=1;
        clrscr();
        getfunction();
        float accu=getaccuracy();
        displayfunction();
        do
        {
               i=0;
               getinitialvals();
               checkinivals();
               cout << "\n\nInitial values are "<< a<< " and " << b << "\n";
               do
               {
                       x0=(a+b)/2;
                       fnval=fx(x0);
                       printf("%d%15f%15f%15f%15f%15f\n",i+1,a,b,x0,fnval,b-a);
                       if (fnval<0) a=x0; else b=x0;
                       i++;
               } while (abso(b-a)>accu);
 
               printf("\n\nThe root of the equation is %f in %d iterations",x0,i);
               printf("\nPress any key to search for more roots");
               getch();
 
        } while(1);
}

No comments:

Post a Comment