Sequence of Bisect implementations
Loading...
Searching...
No Matches
Bisect3.cpp
Go to the documentation of this file.
1// Bisect3.cpp
2// Recursive function
3// Example: Find the point of zero by bisection
4
5// Version 3: func(x) and epsilon as parameters
6
7#include <cmath>
8#include <functional> // function; C++11
9#include <iostream>
10using namespace std;
11
18double f(const double x) // declaration and
19{
20 return sin(x) - 0.5 * x ; // definition of function f(x)
21}
22
29double g(const double x) // declaration and
30{
31 return -(x - 1.234567) * (x + 0.987654) ; // definition of function g(x)
32}
33
34// declaration of Bisect3
49double Bisect3(const std::function<double(double)>& func,
50 const double a, const double b, const double eps = 1e-6);
51
52int main()
53{
54 // ...
55 const double EPS = 1e-6; // accuracy constant
56
57 cout << endl;
58 cout << " Determine point of zero in [a,b] by bisection " << endl;
59
60 double a, b;
61 cout << "f(a) > 0, a : ";
62 cin >> a;
63 cout << "f(b) < 0, b : ";
64 cin >> b;
65 cout << endl;
66
67 //double x0 = Bisect3(f, a, b, EPS); // call recursive function with f
68 double x0 = Bisect3(g,a,b,EPS); // call recursive function with g
69
70 cout << endl << " point of zero = " << x0 << endl;
71 cout << endl;
72
73 return 0;
74}
75
76// ---------------------------------------------------------------
77// Recursive function Bisect3
78// ---------------------------------------------------------------
79// definition of Bisect3
80
81double Bisect3(const std::function<double(double)>& func, const double a, const double b,
82 const double eps)
83{
84 double x0;
85 double c = (a + b) / 2; // center of interval
86 double fc = func(c); // function value in center
87
88 if ( std::abs(fc) < eps ) { // end of recursion
89 x0 = c;
90 }
91 else if ( fc > 0.0 ) {
92 x0 = Bisect3(func, c, b, eps); // search in the right intervall
93 }
94 else { // i.e., fc < 0.0
95 x0 = Bisect3(func, a, c, eps); // search in the left intervall
96 }
97
98 return x0; // return the solution
99}
100
101
102
103
104
105
106
107
108
const double EPS
Definition Bisect2.cpp:13
double Bisect3(const std::function< double(double)> &func, const double a, const double b, const double eps=1e-6)
Returns one solution for the equation with .
Definition Bisect3.cpp:81
double g(const double x)
Calculates function .
Definition Bisect3.cpp:29
int main()
Definition Bisect3.cpp:52
clf define function syms x f
Definition bisect.m:6
define interval a
Definition bisect.m:11
b
Definition bisect.m:12
elseif x
Definition bisect_vis.m:169
Call the bisection method to find the root of the function eps
Definition bisect_vis.m:31
end switch method_loc case midpoint c
Definition bisect_vis.m:81
fc
Definition bisect_vis.m:67