fork download
  1. /*
  2.  * Bisection Method.
  3.  * x^2 - a = 0
  4.  */
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. double EPS = 0.00001;
  10.  
  11. double f(double x, int a) {
  12.  
  13. return x * x - a;
  14. }
  15.  
  16. double divideEtImpera(double lo, double hi, int a) {
  17.  
  18. if(hi - lo <= EPS) return (lo + hi) / 2;
  19.  
  20. else {
  21.  
  22. double m = (lo + hi) / 2;
  23. //cout<<m<<endl;
  24. if(f(lo,a) * f(m,a) < 0) {
  25.  
  26. return divideEtImpera(lo, m, a);
  27.  
  28. } else {
  29.  
  30. return divideEtImpera(m, hi, a);
  31. }
  32. }
  33. }
  34.  
  35. //Bisection method using iteration
  36. void bisection(double lo, double hi, double a) {
  37.  
  38. double m;
  39.  
  40. while((hi - lo) >= EPS) {
  41.  
  42. m = (lo + hi) / 2;
  43.  
  44. if(f(lo, a) * f(m, a) < 0) {
  45.  
  46. hi = m;
  47.  
  48. } else {
  49.  
  50. lo = m;
  51. }
  52.  
  53. cout<<m<<endl;
  54. }
  55.  
  56. cout<<m<<endl;
  57. }
  58.  
  59.  
  60. //Bisection method using iteration - version 2
  61. void bisection2(double lo, double hi, double a) {
  62.  
  63. double m, y_x, y_m;
  64.  
  65. while((hi - lo) >= EPS) {
  66.  
  67. m = (lo + hi) / 2;
  68.  
  69. y_x = lo * lo - a;
  70. y_m = m * m - a;
  71.  
  72. if( (y_x > 0 && y_m < 0) || (y_x < 0 && y_m > 0)) {
  73.  
  74. hi = m;
  75.  
  76. } else {
  77.  
  78. lo = m;
  79. }
  80.  
  81. cout<<m<<endl;
  82. }
  83.  
  84. cout<<m<<endl;
  85. }
  86.  
  87. int main(int argc, char const *argv[]) {
  88. int a;
  89. cin>>a;
  90. cout<<divideEtImpera(0, a + 5, a)<<endl;
  91. bisection(0, a + 5, a);
  92. bisection2(0, a + 5, a);
  93. return 0;
  94. }
Success #stdin #stdout 0.01s 5408KB
stdin
49
stdout
7
27
13.5
6.75
10.125
8.4375
7.59375
7.17188
6.96094
7.06641
7.01367
6.9873
7.00049
6.9939
6.99719
6.99884
6.99966
7.00008
6.99987
6.99997
7.00002
7
7.00001
7.00001
7.00001
27
13.5
6.75
10.125
8.4375
7.59375
7.17188
6.96094
7.06641
7.01367
6.9873
7.00049
6.9939
6.99719
6.99884
6.99966
7.00008
6.99987
6.99997
7.00002
7
7.00001
7.00001
7.00001