/* C Program To Find The Root Of The Equation x*x-25 Using Bisection Method */ #include<stdio.h> #include<math.h> #include<conio.h> float f(float); int main() { float x0,x1,x2,y0,y1,y2,e; int i; printf("Enter the initial guess\n"); scanf("%f%f",&x0,&x1); y0=f(x0); y1=f(x1); if((y0*y1)>0) { printf("Invalid guess.\n"); exit(0); } printf("Enter the allowable error:\n"); scanf("%f",&e); printf("f(x)=x*x-25\n"); printf("-------------------------------------------------------\n"); printf("i\tx0\tx1\ty0\ty1\tx2\ty2\n"); printf("-------------------------------------------------------\n"); i=0; while((x1-x0)/x1>e) { printf("%d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",i,x0,x1,y0,y1,x2,y2); x2=(x0+x1)/2; y2=f(x2); if(y0*y0>0) { x0=x2; y0=y2; } else{ x1=x2; y1=y2; } i++; } printf("-------------------------------------------------------\n"); printf("The root is %.3f",x2); return 0; } float f(float x) { return(x*x-25); }
Enter the initial guess 2 7 Enter the allowable error: .01 f(x)=x*x-25 ------------------------------------------------------- i x0 x1 y0 y1 x2 y2 ------------------------------------------------------- 0 2.000 7.000 -21.000 24.000 0.000 0.000 1 4.500 7.000 -4.750 24.000 4.500 -4.750 2 5.750 7.000 8.063 24.000 5.750 8.063 3 6.375 7.000 15.641 24.000 6.375 15.641 4 6.688 7.000 19.723 24.000 6.688 19.723 5 6.844 7.000 21.837 24.000 6.844 21.837 6 6.922 7.000 22.912 24.000 6.922 22.912 ------------------------------------------------------- The root is 6.961
No comments:
Post a Comment