tampurus

Unit 1.5 Secant Method

Mar 31st, 2022 (edited)
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #define f(x) ((x * x * x) - (9*x) + 1)
  4. int main()
  5. {
  6.     float x0,x1,x2,xm,c,E;    
  7.     int i = 0;
  8.     printf("Enter the initial values\n");
  9.     scanf("%f %f %f",&x0,&x1,&E);
  10.    
  11.     if (f(x0) * f(x1) > 0){
  12.         printf("Can not find a root in the given interval");
  13.         return 0;
  14.     }
  15.    
  16.     do
  17.     {
  18.         x2 = (x0 * f(x1) - x1 * f(x0)) / (f(x1) - f(x0));
  19.         c = f(x0) * f(x2);
  20.        
  21.         x0 = x1;
  22.         x1 = x2;
  23.        
  24.         i++;
  25.        
  26.         if (c == 0) break;
  27.         xm = (x0 * f(x1) - x1 * f(x0)) / (f(x1) - f(x0));
  28.     } while (fabs(xm - x2) >= E);
  29.  
  30.     printf("Root of the given equation= %f\n", x2);
  31.     printf("No. of iterations = %d\n", i);
  32.    
  33.     return 0;
  34. }
  35.  
  36. /*
  37. Output
  38. Enter the initial values
  39. 2 3 0.001
  40. Root of the given equation= 2.942849
  41. No. of iterations = 3
  42. */
Add Comment
Please, Sign In to add comment