Advertisement
tampurus

Unit 1.3 Bisection root of equation

Mar 13th, 2022 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. // one more way to get the answer written in this code by comment where changes has to be made
  2. #include <stdio.h>
  3. #include <math.h>
  4.  
  5. #define f(x) ((x*x*x) - (2*x) - 5)
  6. int main()
  7. {
  8.     float x0,x1,e,x2,y0,y1,y2;
  9.     int i=0;
  10.     printf("Enter the value of x0,x1,e");
  11.     scanf("%f %f %f",&x0,&x1,&e);
  12.     y0 = f(x0);
  13.     y1 = f(x1);
  14.     if(y1*y0>0){
  15.         printf("\nIntial values are not correct");
  16.         return 0;
  17.     }
  18.     while(fabs((x1-x0)/x1)>e){ // only do while
  19.         x2=(x0+x1)/2;
  20.         y2=f(x2);
  21.         i++;
  22.        
  23.         if(y2*y0>0){
  24.             x0 = x2;
  25.             y0 = y2;
  26.         }
  27.         else{
  28.             x1 = x2;
  29.             y1 = y2;
  30.         }
  31.     } // condition (fabs(y2)>e);
  32.     printf("\nHence the root is %f",x2);
  33.     printf("\nTotal number of interations are %d",i);
  34.     return 0;
  35. }
  36.  
  37. /*
  38. Ouput
  39. Enter the value of x0,x1,e
  40. -1 3 0.0001
  41.  
  42. Hence the root is 2.094604
  43. Total number of iterations are 15
  44. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement