fork download
  1. #include <iostream> //id=240242103
  2. #include <cmath>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. // Horner's rule to evaluate f(x)
  7. double horner(double coeff[], int n, double x) {
  8. double result = coeff[n];
  9. for (int i = n - 1; i >= 0; i--)
  10. result = result * x + coeff[i];
  11. return result;
  12. }
  13.  
  14. int main() {
  15. int degree;
  16. cout << "Enter the degree of the polynomial: ";
  17. cin >> degree;
  18.  
  19. double coeff[degree + 1];
  20. for (int i = 0; i <= degree; i++) {
  21. cout << "x^" << i << "::";
  22. cin >> coeff[i];
  23. }
  24.  
  25. double x1, x2, tol;
  26. cout << "Enter first initial guess x1: ";
  27. cin >> x1;
  28. cout << "Enter second initial guess x2: ";
  29. cin >> x2;
  30. cout << "Enter tolerance: ";
  31. cin >> tol;
  32.  
  33. double f1 = horner(coeff, degree, x1);
  34. double f2 = horner(coeff, degree, x2);
  35. double x3, f3;
  36. int iter = 0;
  37.  
  38. cout << fixed << setprecision(6);
  39. cout << "Iteration x1 x2 x3 f(x3)\n";
  40. cout << "--------------------------------------------\n";
  41.  
  42. do {
  43. x3 = (f2 * x1 - f1 * x2) / (f2 - f1); // Secant formula
  44. f3 = horner(coeff, degree, x3);
  45.  
  46. iter++;
  47. cout << iter << "\t" << x1 << "\t" << x2 << "\t" << x3 << "\t" << f3 << endl;
  48.  
  49. // Update for next iteration
  50. x1 = x2;
  51. f1 = f2;
  52. x2 = x3;
  53. f2 = f3;
  54.  
  55. } while (fabs(f3) > tol); // Stop when residual < tolerance
  56.  
  57. cout << "--------------------------------------------\n";
  58. cout << "Approximate root = " << x3 << endl;
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5276KB
stdin
3
-3
-1
0
1
4
2
0.000001
stdout
Enter the degree of the polynomial: x^0::x^1::x^2::x^3::Enter first initial guess x1: Enter second initial guess x2: Enter tolerance: Iteration  x1        x2        x3        f(x3)
--------------------------------------------
1	4.000000	2.000000	1.888889	1.850480
2	2.000000	1.888889	1.710024	0.290396
3	1.888889	1.710024	1.676730	0.037265
4	1.710024	1.676730	1.671828	0.000947
5	1.676730	1.671828	1.671700	0.000003
6	1.671828	1.671700	1.671700	0.000000
--------------------------------------------
Approximate root = 1.671700