Advertisement
tsounakis

Taylor (Lab 1)

Oct 26th, 2021 (edited)
1,043
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 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. double ddf(double x){                                                   // f''(x) derivative function of f(x)
  14.     return exp(-10 * pow(x,2)) * (400 * pow(x,2) * cos(x) + 40 * x * sin(x) - 21 * cos(x));
  15. }
  16.  
  17. int main(){
  18.     double x, x0 = -0.7;                                                // variable x and initial value of x (x_0)
  19.     double error;
  20.     int k = -10, i = 0;
  21.  
  22.     printf("i:\tx:\t\tf(x):\t\tError:\n");
  23.  
  24.     do{
  25.         i++;
  26.         x = x0 - 2 * (f(x0) * df(x0) / (2*pow(df(x0),2) - f(x0)*ddf(x0)));
  27.         error = fabs(x - x0);
  28.         printf("%3d\t%14.10f\t%14.10f\t%14.10f\n", i, x, f(x), error);  // print the data of the calculations
  29.         x0 = x;
  30.     } while(error >= 0.5 * pow(10.0,k));                                // do until error is smaller than 10^-10
  31.  
  32.     getchar();
  33.     return 0;
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement