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