Advertisement
tsounakis

Secant (Lab 1)

Oct 26th, 2021
1,063
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.86 KB | None | 0 0
  1. #include <stdio.h>                                                      // Thanasis Tsounakis 2021 NEWTON-RAPHSON METHOD
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. double f(double x){                                                     // f(x) function
  6.     return x + exp(-10 * pow(x,2)) * cos(x);
  7. }
  8.  
  9. double df(double x){                                                    // f'(x) derivative function of f(x)
  10.     return 1.0 - exp(-10 * pow(x,2)) * ( sin(x) + 20 * x  * cos(x));
  11. }
  12.  
  13. int main(){
  14.     double x, x0 = -0.7, x1 = 0;                                        // variable x and value of x1 (x_n) and x0 (x_n-1)
  15.     double error;
  16.     int k = -10, i = 1;
  17.  
  18.     printf("i:\tx:\t\tf(x):\t\tError:\n");
  19.  
  20.     do{
  21.         i++;
  22.         x = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
  23.         error = fabs(x - x0);
  24.         printf("%3d\t%14.10f\t%14.10f\t%14.10f\n", i, x, f(x), error);  // print the data of the calculations
  25.         x0 = x1;
  26.         x1 = x;
  27.     } while(error >= 0.5 * pow(10.0,k));                                // do until error is smaller than 10^-10
  28.  
  29.     getchar();
  30.     return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement