fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. double f(double x) {
  9. return cos(x) - x;
  10. }
  11.  
  12. int main() {
  13. double x1, x2, x0, f1, f2, f0, E;
  14. int iteration = 1;
  15.  
  16. cout << fixed << setprecision(6);
  17.  
  18.  
  19. cout << "Enter the value of x1: ";
  20. cin >> x1;
  21. cout << "Enter the value of x2: ";
  22. cin >> x2;
  23. cout << "Enter the stopping criterion E: ";
  24. cin >> E;
  25.  
  26. f1 = f(x1);
  27. f2 = f(x2);
  28.  
  29.  
  30. if (f1 * f2 > 0) {
  31. cout << "The initial guesses do not bracket the root. Please choose different values." << endl;
  32. return 1;
  33. }
  34.  
  35. cout << "\nIteration\tx1\t\tx2\t\tx0\t\tf(x0)\t\tf(x1)\t\tf(x2)" << endl;
  36.  
  37. do {
  38.  
  39. x0 = x1 - (f1 * (x2 - x1)) / (f2 - f1);
  40. f0 = f(x0);
  41.  
  42.  
  43. cout << iteration << "\t\t" << x1 << "\t" << x2 << "\t" << x0 << "\t" << f0 << "\t" << f1 << "\t" << f2 << endl;
  44.  
  45.  
  46. if (f0 == 0.0) {
  47. cout << "\nExact root found: " << x0 << endl;
  48. break;
  49. }
  50.  
  51.  
  52. if (f1 * f0 < 0) {
  53. x2 = x0;
  54. f2 = f0;
  55. } else {
  56. x1 = x0;
  57. f1 = f0;
  58. }
  59.  
  60.  
  61. if (fabs((x2 - x1) / x2) < E) {
  62. double root = (x1 + x2) / 2;
  63. cout << "\nApproximate root found: " << root << endl;
  64. break;
  65. }
  66.  
  67. iteration++;
  68. } while (true);
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0.01s 5320KB
stdin
-1
1
0.0001
stdout
Enter the value of x1: Enter the value of x2: Enter the stopping criterion E: 
Iteration	x1		x2		x0		f(x0)		f(x1)		f(x2)
1		-1.000000	1.000000	0.540302	0.317251	1.540302	-0.459698
2		0.540302	1.000000	0.728010	0.018489	0.317251	-0.459698
3		0.728010	1.000000	0.738527	0.000934	0.018489	-0.459698
4		0.738527	1.000000	0.739057	0.000047	0.000934	-0.459698
5		0.739057	1.000000	0.739084	0.000002	0.000047	-0.459698
6		0.739084	1.000000	0.739085	0.000000	0.000002	-0.459698
7		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
8		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
9		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
10		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
11		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
12		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
13		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698
14		0.739085	1.000000	0.739085	0.000000	0.000000	-0.459698

Exact root found: 0.739085