fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Modified function name
  5. double customFunc(double val) {
  6. return (2.0 * val * val * val + 3.0 * val - 1.0);
  7. }
  8.  
  9. int main() {
  10. double left, right, midpoint, f_left, f_right, f_mid, tolerance = 0.0001, root;
  11. int iteration = 0;
  12.  
  13. // Input loop instead of goto
  14. while (true) {
  15. cout << "Enter two initial guesses: ";
  16. cin >> left >> right;
  17.  
  18. f_left = customFunc(left);
  19. f_right = customFunc(right);
  20.  
  21. if (f_left * f_right < 0) {
  22. break;
  23. } else {
  24. cout << "Invalid interval. Try again.\n";
  25. }
  26. }
  27.  
  28. // First midpoint calculation
  29. midpoint = (left + right) / 2.0;
  30. f_mid = customFunc(midpoint);
  31.  
  32. if (f_mid == 0) {
  33. cout << fixed << setprecision(8);
  34. cout << "Exact root found: " << midpoint << endl;
  35. return 0;
  36. }
  37.  
  38. // Header for output
  39. cout << "Iter\tMidpoint\tLeft\tRight\tf(Mid)\tf(Left)\tf(Right)\n";
  40. cout << iteration << "\t" << fixed << setprecision(8) << midpoint << "\t"
  41. << left << "\t" << right << "\t"
  42. << f_mid << "\t" << f_left << "\t" << f_right << endl;
  43.  
  44. while (true) {
  45. midpoint = (left + right) / 2.0;
  46. f_mid = customFunc(midpoint);
  47. iteration++;
  48.  
  49. cout << iteration << "\t" << fixed << setprecision(8) << midpoint << "\t"
  50. << left << "\t" << right << "\t"
  51. << f_mid << "\t" << f_left << "\t" << f_right << endl;
  52.  
  53. if (fabs((right - left) / right) < tolerance || iteration > 8) {
  54. break;
  55. }
  56.  
  57. if (f_left * f_mid < 0) {
  58. right = midpoint;
  59. f_right = f_mid;
  60. } else {
  61. left = midpoint;
  62. f_left = f_mid;
  63. }
  64.  
  65. root = midpoint;
  66. }
  67.  
  68. cout << fixed << setprecision(8) << "Approximate root = " << root << endl;
  69. return 0;
  70. }
Success #stdin #stdout 0s 5312KB
stdin
-1
3
stdout
Enter two initial guesses: Iter	Midpoint	Left	Right	f(Mid)	f(Left)	f(Right)
0	1.00000000	-1.00000000	3.00000000	4.00000000	-6.00000000	62.00000000
1	1.00000000	-1.00000000	3.00000000	4.00000000	-6.00000000	62.00000000
2	0.00000000	-1.00000000	1.00000000	-1.00000000	-6.00000000	4.00000000
3	0.50000000	0.00000000	1.00000000	0.75000000	-1.00000000	4.00000000
4	0.25000000	0.00000000	0.50000000	-0.21875000	-1.00000000	0.75000000
5	0.37500000	0.25000000	0.50000000	0.23046875	-0.21875000	0.75000000
6	0.31250000	0.25000000	0.37500000	-0.00146484	-0.21875000	0.23046875
7	0.34375000	0.31250000	0.37500000	0.11248779	-0.00146484	0.23046875
8	0.32812500	0.31250000	0.34375000	0.05503082	-0.00146484	0.11248779
9	0.32031250	0.31250000	0.32812500	0.02666569	-0.00146484	0.05503082
Approximate root = 0.32812500