16 double f(
const double x)
18 return sin(x) - 0.5 * x ;
21 double g(
const double x)
23 return -(x - 1.234567) * (x + 0.987654) ;
26 double h(
const double x)
31 double t(
const double x)
38 double Bisect(
double a,
double b,
double eps);
42 double Bisect(
const std::function<
double(
double)> &func,
43 double a,
double b,
double eps);
47 constexpr
double EPS = 1e-6;
48 array<string, 4> ssf{
"f(x) := sin(x) - x/2",
49 "g(x) := (1.234567-x)*(x+0.987654)",
50 "h(x) := 3.0 - exp(x)",
54 array< std::function<double(
double)>, 4> vff{
f,
g,
h,
t};
57 map<char, int> mmf{{
'f', 0}, {
'g', 1}, {
'h', 2}, {
't', 3}};
60 map<char, std::function<double(
double)> > mapff{{
'f',
f}, {
'g',
g}, {
'h',
h}, {
't',
t}};
64 cout <<
" Determine root in [a,b] by bisection " << endl;
66 for (
size_t k = 0; k < ssf.size(); ++k) {
68 cout << ssf[k] << endl;
72 cout << endl <<
"Which function do you prefer ? ";
75 std::function<double(
double)> ff;
78 ff = mapff.at(choice);
80 catch (out_of_range& ) {
82 ff = mapff.at(choice);
83 cout <<
" incorrect choice. h(x) is used." << endl;
89 cout <<
" " << choice <<
"(a) > 0, a : ";
91 cout <<
" " << choice <<
"(b) < 0, b : ";
95 double const fa = ff(
a);
96 double const fb = ff(
b);
100 if ( abs(fa) <
EPS || abs(fb) <
EPS) {
101 if ( abs(fa) <
EPS ) {
103 cout << endl <<
" point of zero = " << x0 << endl;
105 if ( abs(fb) <
EPS ) {
107 cout << endl <<
" point of zero = " << x0 << endl;
112 cout <<
"I have to swap a and b" << endl;
118 cout << endl <<
" point of zero = " << x0 << endl;
122 cout << endl <<
"There is potentially no solution in [" <<
a <<
"," <<
b <<
"]" << endl;
134 double Bisect(
const std::function<
double(
double)> &func,
135 const double a,
const double b,
const double eps)
137 double const c = (
a +
b) / 2;
138 double const fc = func(c);
141 if ( std::abs(fc) < eps ) {
144 else if ( fc > 0.0 ) {
double Bisect(double a, double b, double eps)