I am using equation f(x): x^3-2x-5 = x*x*x-2*x-5 (a=2 and b=3)
You can change it(x*x*x-2*x-5) to you own equation
Code:
#include<stdio.h>
#include<conio.h>
# define eqn x*x*x-2*x-5
float f(float x)
{
float ans;
ans=eqn;
return(ans);
}
void main()
{
float a,b,x=0,x1=0;
int i=0;
clrscr();
printf("Enter the a and b");
scanf("%f%f",&a,&b);
if(f(a)*f(b)>=0)
{
printf("The interval is wrong");
getch();
return;
}
do
{
x=(a+b)/2;
printf("\ta=%f\tb=%f\tX%d=%f\tf(x%d)=%f\n",a,b,i,x,i,f(x));
if(x==x1)
{
printf("\n\nThe root is %f\n",x);
break;
}
x1=x;
i++;
if(f(a)*f(x)<0)
b=x;
else
a=x;
}while(f(a)*f(b)<0);
getch();
}
You can change it(x*x*x-2*x-5) to you own equation
#include<stdio.h>
#include<conio.h>
# define eqn x*x*x-2*x-5
float f(float x)
{
float ans;
ans=eqn;
return(ans);
}
void main()
{
float a,b,x=0,x1=0;
int i=0;
clrscr();
printf("Enter the a and b");
scanf("%f%f",&a,&b);
if(f(a)*f(b)>=0)
{
printf("The interval is wrong");
getch();
return;
}
do
{
x=(a+b)/2;
printf("\ta=%f\tb=%f\tX%d=%f\tf(x%d)=%f\n",a,b,i,x,i,f(x));
if(x==x1)
{
printf("\n\nThe root is %f\n",x);
break;
}
x1=x;
i++;
if(f(a)*f(x)<0)
b=x;
else
a=x;
}while(f(a)*f(b)<0);
getch();
}
very helpful tutorial, thank you buddy, i made it with different logic which i want to share here: C program for Bisection method
ReplyDeleteThank u
ReplyDeleteIterations went into infinite loop.. What the hell...
ReplyDeleteThis comment has been removed by the author.
ReplyDelete