Advertisement
tsounakis

Newton-Raphson Method (Lab 1)

Oct 26th, 2021
968
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.81 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;                                                // variable x and initial value of x (x_0)
  15.     double error;
  16.     int k = -10, i = 0;
  17.  
  18.     printf("i:\tx:\t\tf(x):\t\tError:\n");
  19.  
  20.     do{
  21.         i++;
  22.         x = x0 - f(x0)/df(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 = x;
  26.     } while(error >= 0.5 * pow(10.0,k));                                // do until error is smaller than 10^-10
  27.  
  28.     getchar();
  29.     return 0;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement