Search & Find out

Thursday, November 26, 2009

Bisection Method

 It includes accepting a function, two initial values & find the  solution 

#include "stdio.h"
#include "conio.h"
#include "math.h"



void main()
{
     int power,i=0,m,n,n1,l;
     double x1,x2,x0,fx1,fx2,fx0,c[100],n2,fx;
     clrscr();


     printf("\nHi, Welcome to Bisection Method \n\n");

     printf("\n\nEnter the maximum power\t");
     scanf("%d",&power);

     for(i=power;i>=0;i--)
     {
       if(i==0)
       {
    printf("Enter a constant number\t");
       }
       else
       {
    printf("Enter the coefficient of the power %d \t",i);
       }

       scanf("%lf",&c[i]);
     }
      printf("\n\n");

     for(i=power;i>=0;i--)
     {
       if(i==0)
       {
    printf("(%lf)  = 0\n",c[i]);
       }
       else
       {
    printf("(%lf) x^%d + ",c[i],i);
       }
     }

       printf("\nEnter the value of x1 & x2\n\n");
       scanf("%lf%lf",&x1,&x2);


tej:
       printf("\nhey...! do you want to perform function till \n\n1)No. of ittrations\t2)Accuracy\n\n");
       scanf("%d",&n);

     if(n==1)
     {
      printf("\nSo, enter the no. of ittrations\t");
      scanf("%d",&n1);
     }
     else if(n==2)
     {
      printf("\nSo, enter the Accuracy till\t");
      scanf("%lf",&n2);
     }
     else
     {
      clrscr();
      printf("\n\tInvalid option try again\n");
      goto tej;
     }

     clrscr();


     for(  l=1,fx0=1;  (n==1?l<=n1:fabs(fx0)>=n2);   l++  )

    {
        for(fx1=0,i=power;i>=0;i--)
        {
          fx=c[i] * pow(x1,i);
          fx1=fx+fx1;
        }
        for(fx2=0,i=power;i>=0;i--)
        {
          fx=c[i] * pow(x2,i);
          fx2=fx+fx2;
        }

          x0=(x1+x2)/2;

        for(fx0=0,i=power;i>=0;i--)
        {
          fx=c[i] * pow(x0,i);
          fx0=fx+fx0;
        }

       if(l==1)
       {
         printf("\nIttration  x1       x2         x0         fx1         fx2          fx0\n");
       }

       printf("\n%d    %lf    %lf    %lf    %lf    %lf    %lf\n",l,x1,x2,x0,fx1,fx2,fx0);

        if((fx1>0&&fx2>0)||(fx1<0&&fx2<0))
        {

          printf("\n\nThe function won't be perform further, because  f(x1) * f(x2) > 0 \n");
          goto exit;
        }

       x1=((fx0>0&&fx1>0)||(fx0<0&&fx1<0)?x0:x1);
       x2=((fx0>0&&fx2>0)||(fx0<0&&fx2<0)?x0:x2);

   }

exit:
     getch();

}




Download the executable (.exe)  file for this program..
download

0 comments:

Post a Comment

 

My Blog List

Term of Use