Arnab_Manna

Secant method

Oct 5th, 2020
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1.  //for implementation of regula Secants Method for
  2. // solving equations
  3. #include<stdio.h>
  4. #include<math.h>
  5. #define MAX_ITER 1000000  
  6. #define err 0.00001
  7.  
  8. double f(double x)
  9. {  
  10. return x*x*x - x - 1;
  11. }
  12. // Prints root of f(x) in interval [a, b]
  13.  
  14. void regulaFalsi(double a, double b)
  15. {
  16. int count=0;
  17.     if (f(a) * f(b) >= 0)
  18.     {
  19.         printf("You have not assumed right a and b\n");
  20.         return;
  21.     }
  22.     printf("finding the approx root of eqn. by Secant method\n");
  23.     double c = a;  // Initialize result
  24.     printf("\na\t\tb\t\tf(a)\t\tf(b)\t\tc\t\tf(c)\n");
  25.    
  26.     for (int i=0; i < MAX_ITER; i++)
  27.     {
  28.         printf("%.4f \t\t%.4f \t\t%.4f\t\t%.4f",a,b,f(a),f(b));
  29.         // Find the point that touches x axis
  30.         c = (a*f(b) - b*f(a))/ (f(b) - f(a));
  31.         printf("\t\t%.4f\t\t%.4f\n",c,f(c));
  32.         // Check if the above found point is root
  33.        if (f(c)<=0.00001 && f(c)>=-0.00001)
  34.        {    // if(fabs(a-c)>err)
  35.         break;
  36.         }
  37.         // Decide the side to repeat the steps
  38.            a=b;
  39.            b=c;
  40.                        
  41.             ++count;
  42.     }
  43.     printf( "The value of root is :%.4f ", c);
  44.     printf(" the no of iterations required is %d",(count+1));
  45. }
  46.  
  47. void GetRootRange(double *L, double *U)
  48.  {
  49.  double y;
  50.  for(y=-999999.0l;y<999999.0l;y=y+0.1)
  51.  {
  52.  if(f(y)*f(y+0.1)<0.0)
  53.  {fflush(stdin);
  54.  *L=y;*U=y+0.1;
  55.  return;
  56.  }
  57.  }
  58.  }
  59. // Driver program to test above ftion :""
  60.  
  61. int main()
  62. {
  63.     // Initial values assumed
  64.     double a , b  ;
  65.     GetRootRange(&a,&b);
  66.     regulaFalsi(a, b);
  67.     return 0;
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment