fork download
  1. #include <iostream> //id=240242103
  2. #include <cmath>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. double horner(double coeff[], int n, double x) {
  7. double result = coeff[n];
  8. for (int i = n - 1; i >= 0; i--)
  9. result = result * x + coeff[i];
  10. return result;
  11. }
  12.  
  13. double horner_derivative(double coeff[], int n, double x) {
  14. double result = n * coeff[n];
  15. for (int i = n - 1; i >= 1; i--)
  16. result = result * x + i * coeff[i];
  17. return result;
  18. }
  19.  
  20. int main() {
  21. int degree;
  22. cout << "ENTER THE TOTAL NO. OF POWER:::: ";
  23. cin >> degree;
  24.  
  25. double coeff[degree + 1];
  26. for (int i = 0; i <= degree; i++) {
  27. cout << "x^" << i << "::";
  28. cin >> coeff[i];
  29. }
  30.  
  31. cout << "THE POLYNOMIAL IS ::: ";
  32. for (int i = degree; i >= 0; i--) {
  33. if (coeff[i] >= 0 && i != degree) cout << "+";
  34. cout << coeff[i] << "x^" << i << " ";
  35. }
  36. cout << endl;
  37.  
  38. double x0;
  39. cout << "INITIAL X1 ------ >";
  40. cin >> x0;
  41.  
  42. double E = 1e-6; // stopping criterion
  43. double x1, f0, f1, Ea;
  44. int iter = 0;
  45.  
  46. cout << "**************************************\n";
  47. cout << "ITERATION X FX F'X Ea(%)\n";
  48. cout << "**************************************\n";
  49.  
  50. do {
  51. f0 = horner(coeff, degree, x0);
  52. f1 = horner_derivative(coeff, degree, x0);
  53. x1 = x0 - f0 / f1;
  54.  
  55. if (iter == 0)
  56. Ea = 0;
  57. else
  58. Ea = fabs((x1 - x0) / x1) * 100;
  59.  
  60. iter++;
  61. cout << iter << "\t" << x1 << "\t" << f0 << "\t" << f1 << "\t" << Ea << endl;
  62.  
  63. x0 = x1;
  64.  
  65. } while (Ea > E);
  66.  
  67. cout << "**************************************\n";
  68. cout << "THE ROOT OF EQUATION IS " << fixed << setprecision(6) << x1 << endl;
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0.01s 5320KB
stdin
1
2
10
42
11
stdout
ENTER THE TOTAL NO. OF POWER:::: x^0::x^1::THE POLYNOMIAL IS ::: 10x^1 +2x^0 
INITIAL X1 ------ >**************************************
ITERATION  X      FX      F'X      Ea(%)
**************************************
1	-0.2	422	10	0
**************************************
THE ROOT OF EQUATION IS -0.200000