fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  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;
  20. double co[20];
  21. double x0, x1, fx, dfx, E, error;
  22. int iteration = 1, maxIter = 20;
  23.  
  24. cout << "ENTER THE TOTAL NO. OF POWER::: ";
  25. cin >> n;
  26.  
  27. for (int i = 0; i <= n; i++) {
  28. cout << "x^" << i << " :: ";
  29. cin >> co[i];
  30. }
  31.  
  32. cout << "\nTHE POLYNOMIAL IS ::: ";
  33. for (int i = n; i >= 0; i--) {
  34. cout << co[n - i] << "x^" << i << " ";
  35. }
  36. cout << endl;
  37.  
  38. cout << "\nEnter initial guess x0: ";
  39. cin >> x0;
  40. cout << "Enter tolerance (e.g. 0.0001): ";
  41. cin >> E;
  42.  
  43. cout << "\n***********************************************";
  44. cout << "\nIteration\t x\t\t f(x)\t\t f'(x)\t\t Error\t\t %Error";
  45. cout << "\n***********************************************\n";
  46.  
  47. while (iteration <= maxIter) {
  48. fx = f(co, n, x0);
  49. dfx = df(co, n, x0);
  50.  
  51. if (dfx == 0) {
  52. cout << "Division by zero!.\n";
  53. return 0;
  54. }
  55.  
  56. x1 = x0 - fx / dfx;
  57. error = fabs((x1 - x0) / x1);
  58.  
  59. cout << fixed << setprecision(6);
  60. cout << setw(5) << iteration << "\t"
  61. << setw(10) << x1 << "\t"
  62. << setw(10) << fx << "\t"
  63. << setw(10) << dfx << "\t"
  64. << setw(10) << error << "\t"
  65. << setw(10) << error * 100 << endl;
  66.  
  67. if (error < E)
  68. break;
  69.  
  70. x0 = x1;
  71. iteration++;
  72. }
  73.  
  74. cout << "\n***********************************************";
  75. cout << "\nTHE ROOT OF EQUATION IS " << x1 << endl;
  76. cout << "***********************************************\n";
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0.01s 5320KB
stdin
2
-1
stdout
ENTER THE TOTAL NO. OF POWER::: x^0 :: x^1 :: x^2 :: 
THE POLYNOMIAL IS ::: -1x^2 0x^1 0x^0 

Enter initial guess x0: Enter tolerance (e.g. 0.0001): 
***********************************************
Iteration	 x		 f(x)		 f'(x)		 Error		 %Error
***********************************************
Division by zero!.