fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. #include <iomanip>
  5.  
  6. using namespace std;
  7.  
  8. // Function to evaluate polynomial at x
  9. double evaluatePolynomial(const vector<double>& coeffs, double x) {
  10. double result = 0;
  11. int degree = coeffs.size() - 1;
  12. for (int i = 0; i <= degree; ++i) {
  13. result += coeffs[i] * pow(x, degree - i);
  14. }
  15. return result;
  16. }
  17.  
  18. // Function to evaluate derivative of polynomial at x
  19. double evaluateDerivative(const vector<double>& coeffs, double x) {
  20. double result = 0;
  21. int degree = coeffs.size() - 1;
  22. for (int i = 0; i < degree; ++i) {
  23. result += coeffs[i] * (degree - i) * pow(x, degree - i - 1);
  24. }
  25. return result;
  26. }
  27.  
  28. // Synthetic division to deflate polynomial
  29. vector<double> syntheticDivision(const vector<double>& coeffs, double root) {
  30. int n = coeffs.size();
  31. vector<double> newCoeffs(n - 1);
  32. newCoeffs[0] = coeffs[0];
  33. for (int i = 1; i < n - 1; ++i) {
  34. newCoeffs[i] = coeffs[i] + newCoeffs[i - 1] * root;
  35. }
  36. return newCoeffs;
  37. }
  38.  
  39. int main() {
  40. int degree;
  41. cout << "Enter the degree of the polynomial: ";
  42. cin >> degree;
  43.  
  44. vector<double> coeffs(degree + 1);
  45. cout << "Enter the coefficients of the polynomial (from highest to lowest degree):\n";
  46. for (int i = 0; i <= degree; ++i) {
  47. cin >> coeffs[i];
  48. }
  49.  
  50. double x0, E;
  51. cout << "Enter the initial guess (x0): ";
  52. cin >> x0;
  53. cout << "Enter the error tolerance (E): ";
  54. cin >> E;
  55.  
  56. vector<double> currentCoeffs = coeffs;
  57. for (int n = degree; n > 1; --n) {
  58. double f_x0 = evaluatePolynomial(currentCoeffs, x0);
  59. double f_prime_x0 = evaluateDerivative(currentCoeffs, x0);
  60. double x1 = x0 - f_x0 / f_prime_x0;
  61.  
  62. cout << fixed << setprecision(6);
  63. cout << "Iteration " << degree - n + 1 << ":\n";
  64. cout << "x0 = " << x0 << ", x1 = " << x1 << endl;
  65.  
  66. if (fabs(x1 - x0) < E) {
  67. cout << "Root: " << x1 << endl;
  68. break;
  69. }
  70.  
  71. currentCoeffs = syntheticDivision(currentCoeffs, x1);
  72. x0 = x1;
  73. }
  74.  
  75. if (currentCoeffs.size() == 2) {
  76. double root = -currentCoeffs[0] / currentCoeffs[1];
  77. cout << "Final root: " << root << endl;
  78. }
  79.  
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0.01s 5320KB
stdin
Enter the degree of the polynomial: 3
Enter the coefficients of the polynomial (from highest to lowest degree):
1 -6 11 -6
Enter the initial guess (x0): 2
Enter the error tolerance (E): 0.0001
stdout
Enter the degree of the polynomial: Enter the coefficients of the polynomial (from highest to lowest degree):
Enter the initial guess (x0): Enter the error tolerance (E):