#include <stdio.h>
#include <conio.h>
#include <math.h>
#define EPS 0.000001
#define F(x) x*x+x-2
void bim(float *a,float *b,float *root, int *s,int *count);
main(){
int s, count;
float a,b,root;
printf("\nSolution By Bisection Method");
printf("\nInput starting value:\n");
scanf("%f%f",&a,&b);
bim(&a,&b,&root,&s,&count);
if (s==0){
printf("\n Starting points do not bracket any root or they bracket an even number of roots\n ");
}
else{
printf("nRoot=%f\n",root);
printf("F(root)=%f\n",F(root));
printf("\n Iterations=%d\n",count);
}
getch();
}
void bim(float *a,float *b,float *root,int *s, int *count){
float x0,x1,x2,f0,f1,f2;
x1=*a;
x0=*b;
f1=F(x1);
f2=F(x2);
if(f1*f2>0){
*s=0;
return;
}
else{
*count=0;
begin:
x0=(x1+x2)/2;
f0=F(x0);
if(f0==0){
*s=1;
*root=x0;
return;
}
if(f1*f0<0){
x2=x0;
}
else{
x1=x0;
f1=f0;
}
if(fabs((x2-x1)/x2)<EPS){
*s=1;
*root=(x1+x2)/2.0;
return;
}
else{
*count=*count+1;
goto begin;
}
}
}
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment