Sequence of Bisect implementations
Loading...
Searching...
No Matches
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>
11using namespace std;
12
13const double EPS = 1e-6; // global constant
14
15double f(const double x) // declaration and
16{
17 return sin(x) - 0.5 * x ; // definition of function f(x)
18}
19
20double Bisect2(const double a, const double b); // declaration of Bisect2
21
22int 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
47double 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 Bisect2(const double a, const double b)
Definition Bisect2.cpp:47
int main()
Definition Bisect2.cpp:22
const double EPS
Definition Bisect2.cpp:13
clf define function syms x f
Definition bisect.m:6
b
Definition bisect.m:12
define interval a
Definition bisect.m:11