Thursday, April 26, 2012

C code - Bisection Method


//to find root of equation x^3-x-1=0 by bisection method
#include<stdio.h>
#include<math.h>
#define fn(x)(x*x*x-x-1)
void main()
{
float a,b,acc,temp,x1,x2,x3,c,ap,an;
clrscr();
l1:printf("enter lower limit: ");
scanf("%f", &a);
printf("enter upper limit: ");
scanf("%f", &b);
x1=fn(a);
x2=fn(b);
  if (x1<0 && x2<0 || x1>0 && x2>0)
{
printf("\n****enter proper range****\n\n");
goto l1;
}
printf("enter accuracy: ");
scanf("%f", &acc);

if (x1<0 && x2>0)
{
ap=b;
an=a;
}
else
{
ap=a;
an=b;
}
c=(a+b)/2;
x3=fn(c);
while (x3<-acc||x3>acc)
{
if (x3<0)
an=c;
else
ap=c;
c=(an+ap)/2;
x3=fn(c);
}
printf("root of the equation is %.5f", c);
}

No comments:

Post a Comment