Sequence of Bisect implementations
Bisect2.cpp
Go to the documentation of this file.
1 // Bisect2.cpp
2 
3 // Recursive function
4 // Example: Find the solution by bisection
5 
6 // Version 2: f(x) is globally declared and defined
7 // epsilon as global constant
8 
9 #include <cmath>
10 #include <iostream>
11 using namespace std;
12 
13 const double EPS = 1e-6; // global constant
14 
15 double f(const double x) // declaration and
16 {
17  return sin(x) - 0.5 * x ; // definition of function f(x)
18 }
19 
20 double Bisect2(const double a, const double b); // declaration of Bisect2
21 
22 int main()
23 {
24  double a, b;
25 
26  cout << endl;
27  cout << " Determine point of zero in [a,b] by bisection" << endl;
28 
29  cout << " f(a) > 0, a : ";
30  cin >> a;
31  cout << " f(b) < 0, b : ";
32  cin >> b;
33 
34  double x0 = Bisect2(a, b); // call recursive function
35 
36  cout << endl;
37  cout << " point of zero = " << x0 << endl;
38  cout << endl;
39 
40  return 0;
41 }
42 
43 // ---------------------------------------------------------------
44 // Recursive function Bisect2
45 // ---------------------------------------------------------------
46 
47 double Bisect2(const double a, const double b) // definition of Bisect2
48 {
49  double x0, fc, c = (a + b) / 2;
50 
51  fc = f(c);
52  if ( std::abs(fc) < EPS ) {
53  x0 = c; // end of recursion
54  }
55  else if ( fc > 0.0 ) {
56  x0 = Bisect2(c, b); // search in right intervall
57  }
58  else { // i.e., fc < 0.0
59  x0 = Bisect2(a, c); // search in left intervall
60  }
61 
62  return x0; // return with solution
63 }
64 
65 
66 
67 
68 
69 
70 
71 
72 
double f(const double x)
Definition: Bisect2.cpp:15
double Bisect2(const double a, const double b)
Definition: Bisect2.cpp:47
int main()
Definition: Bisect2.cpp:22
const double EPS
Definition: Bisect2.cpp:13
b
Definition: bisect.m:12
define interval a
Definition: bisect.m:11