fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. double f(double x) {
  8. return ((2.0 * x - 3.0) * x + 4.0) * x - 5.0;
  9. }
  10.  
  11. int main() {
  12. double x1, x2, x3, f1, f2, f3, tolerance;
  13.  
  14. cout << "Secant Method with Horner's Rule" << endl;
  15. cout << "f(x) = 2x³ - 3x² + 4x - 5" << endl;
  16.  
  17. cout << "Enter the value of x1: ";
  18. cin >> x1;
  19. cout << "Enter the value of x2: ";
  20. cin >> x2;
  21. cout << "Enter the tolerance: ";
  22. cin >> tolerance;
  23.  
  24. f1 = f(x1);
  25. f2 = f(x2);
  26.  
  27. cout << fixed << setprecision(6);
  28. cout << "\nIteration\tx1\t\tx2\t\tx3\t\tf(x1)\t\tf(x2)\t\tResidual" << endl;
  29. cout << "----------------------------------------------------------------------------------------" << endl;
  30.  
  31. int iteration = 0;
  32.  
  33. do {
  34. x3 = (f2 * x1 - f1 * x2) / (f2 - f1);
  35. f3 = f(x3);
  36.  
  37. iteration++;
  38.  
  39. cout << iteration << "\t\t" << x1 << "\t" << x2 << "\t" << x3
  40. << "\t" << f1 << "\t" << f2 << "\t" << fabs(f3) << endl;
  41.  
  42. x1 = x2;
  43. f1 = f2;
  44. x2 = x3;
  45. f2 = f3;
  46.  
  47. } while (fabs(f3) >= tolerance && iteration < 100);
  48.  
  49. cout << "\nApproximate root = " << x3 << endl;
  50. cout << "Final residual = " << f3 << endl;
  51. cout << "Iterations needed = " << iteration << endl;
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Secant Method with Horner's Rule
f(x) = 2x³ - 3x² + 4x - 5
Enter the value of x1: Enter the value of x2: Enter the tolerance: 
Iteration	x1		x2		x3		f(x1)		f(x2)		Residual
----------------------------------------------------------------------------------------
1		0.000000	0.000000	inf	-5.000000	-5.000000	inf
2		0.000000	inf	-nan	-5.000000	inf	nan

Approximate root = -nan
Final residual = -nan
Iterations needed = 2