frain8

Untitled

Nov 19th, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. /* Dasproc C - 2019
  2. William Handi Wijaya
  3. 0087
  4.  
  5. Menghitung estimasi nilai akar menggunakan metode newton
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <math.h>
  10. // function prototypes
  11. double next_approx(double, double, double);
  12. double func(double, double, double);
  13. double derivative(double, double);
  14. int main()
  15. {
  16.     //variable declarations
  17.     double x0, // variable to calculate
  18.            n, // input - power of x
  19.            c, // const of a polinomial
  20.            x1, // Newton's approximation
  21.            i, // loop variable
  22.            temp; // Flag for old approx
  23.     //get the value of n and c
  24.     printf("\nEnter c - ");
  25.     scanf("%lf", &c);
  26.     printf("\nEnter n - ");
  27.     scanf("%lf", &n);
  28.     //calculate and display the results
  29.     x0 = c / 2;
  30.     x1 = x0 - (func(x0, n, c) / derivative(x0, n));
  31.         //program loop
  32.     for(i = 0; i < 100; i++)
  33.     {
  34.         //printing the result every i
  35.         printf("\n%.6f \n", x1);
  36.         x1 = next_approx(x1, n, c);
  37.     }
  38. }
  39. //function to repeat Newton's method
  40. double next_approx(double temp, double n, double c)
  41. {
  42.     double next_approx = temp - (func(temp, n, c) / derivative(temp, n));
  43.     return next_approx;
  44. }
  45. //function to get the value of f(x)=x^n - c
  46. double func(double x, double n, double c)
  47. {
  48.     return ((pow(x, n)) - c);
  49. }
  50. //function to get the value of f(x) derivative = n * x^(n-1)
  51. double derivative(double x, double n)
  52. {
  53.     return (n * pow(x, n - 1));
  54. }
Advertisement
Add Comment
Please, Sign In to add comment