fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double f(double co[], int n, double x) {
  5. double result = co[0];
  6. for (int i = 1; i <= n; i++)
  7. result = result * x + co[i];
  8. return result;
  9. }
  10.  
  11. double df(double co[], int n, double x) {
  12. double result = co[0] * n;
  13. for (int i = 1; i < n; i++)
  14. result = result * x + co[i] * (n - i);
  15. return result;
  16. }
  17.  
  18. int main() {
  19. int n, i, iteration = 1, maxIter = 20;
  20. double co[20], x0, x1, fx, dfx, E, error;
  21.  
  22. printf("ENTER THE TOTAL NO. OF POWER::: ");
  23. scanf("%d", &n);
  24.  
  25. for (i = 0; i <= n; i++) {
  26. printf("x^%d :: ", i);
  27. scanf("%lf", &co[i]);
  28. }
  29.  
  30. printf("\nTHE POLYNOMIAL IS ::: ");
  31. for (i = n; i >= 0; i--)
  32. printf("%.2lfx^%d ", co[n - i], i);
  33. printf("\n");
  34.  
  35. printf("\nEnter initial guess x0: ");
  36. scanf("%lf", &x0);
  37. printf("Enter tolerance (e.g. 0.0001): ");
  38. scanf("%lf", &E);
  39.  
  40. printf("\n***********************************************");
  41. printf("\nIteration\t x\t\t f(x)\t\t f'(x)\t\t Error\t\t %%Error");
  42. printf("\n***********************************************\n");
  43.  
  44. while (iteration <= maxIter) {
  45. fx = f(co, n, x0);
  46. dfx = df(co, n, x0);
  47. if (dfx == 0) {
  48. printf("Division by zero!\n");
  49. return 0;
  50. }
  51. x1 = x0 - fx / dfx;
  52. error = fabs((x1 - x0) / x1);
  53. printf("%5d\t%10.6lf\t%10.6lf\t%10.6lf\t%10.6lf\t%10.6lf\n",
  54. iteration, x1, fx, dfx, error, error * 100);
  55. if (error < E)
  56. break;
  57. x0 = x1;
  58. iteration++;
  59. }
  60.  
  61. printf("\n***********************************************");
  62. printf("\nTHE ROOT OF EQUATION IS %.8lf", x1);
  63. printf("\n***********************************************\n");
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 5320KB
stdin
3
-6
11
-6
1
3.5
0.0001
stdout
ENTER THE TOTAL NO. OF POWER::: x^0 :: x^1 :: x^2 :: x^3 :: 
THE POLYNOMIAL IS ::: -6.00x^3 11.00x^2 -6.00x^1 1.00x^0 

Enter initial guess x0: Enter tolerance (e.g. 0.0001): 
***********************************************
Iteration	 x		 f(x)		 f'(x)		 Error		 %Error
***********************************************
    1	  2.546823	-142.500000	-149.500000	  0.374261	 37.426133
    2	  1.916633	-42.048401	-66.723409	  0.328800	 32.880035
    3	  1.504846	-12.335800	-29.956756	  0.273641	 27.364054
    4	  1.243721	 -3.565800	-13.655501	  0.209955	 20.995514
    5	  1.090958	 -0.990101	 -6.481285	  0.140027	 14.002664
    6	  1.019561	 -0.244343	 -3.422324	  0.070027	  7.002704
    7	  1.001214	 -0.041845	 -2.280737	  0.018325	  1.832476
    8	  1.000005	 -0.002438	 -2.017019	  0.001209	  0.120858
    9	  1.000000	 -0.000010	 -2.000072	  0.000005	  0.000512

***********************************************
THE ROOT OF EQUATION IS 1.00000000
***********************************************