17 double f(
const double x)
19 return sin(x) - 0.5 * x ;
22 double g(
const double x)
24 return -(x - 1.234567) * (x + 0.987654) ;
27 double h(
const double x)
32 double t(
const double x)
37 double dc(
const double x)
39 return x>=std::sqrt(2.0)? -x : 2.0*x ;
44 double Bisect(
double a,
double b,
double eps);
48 double Bisect(
const std::function<
double(
double)> &func,
49 double a,
double b,
double eps);
53 constexpr
double EPS = 1e-6;
54 array<string, 5> ssf{
"f(x) := sin(x) - x/2",
55 "g(x) := (1.234567-x)*(x+0.987654)",
56 "h(x) := 3.0 - exp(x)",
58 "d(x) := x>=std::sqrt(2.0)? -x : 2.0*x" };
61 array< std::function<double(
double)>, 5> vff{
f,
g,
h,
t,
dc};
64 map<char, int> mmf{{
'f', 0}, {
'g', 1}, {
'h', 2}, {
't', 3}, {
'd',4}};
67 map<char, std::function<double(
double)> > mapff{{
'f',
f}, {
'g',
g}, {
'h',
h}, {
't',
t}, {
'd',
dc} };
71 cout <<
" Determine root in [a,b] by bisection " << endl;
73 for (
size_t k = 0; k < ssf.size(); ++k) {
74 cout << ssf[k] << endl;
78 cout << endl <<
"Which function do you prefer ? ";
81 std::function<double(
double)> ff;
84 ff = mapff.at(choice);
86 catch (out_of_range ) {
88 ff = mapff.at(choice);
89 cout <<
" incorrect choice. h(x) is used." << endl;
95 cout <<
" " << choice <<
"(a) > 0, a : ";
97 cout <<
" " << choice <<
"(b) < 0, b : ";
101 double const fa = ff(
a);
102 double const fb = ff(
b);
106 if ( abs(fa) <
EPS || abs(fb) <
EPS) {
107 if ( abs(fa) <
EPS ) {
109 cout << endl <<
" point of zero = " << x0 << endl;
111 if ( abs(fb) <
EPS ) {
113 cout << endl <<
" point of zero = " << x0 << endl;
118 cout <<
"I have to swap a and b" << endl;
124 cout << endl <<
" point of zero = " << x0 << endl;
128 cout << endl <<
"There is potentially no solution in [" <<
a <<
"," <<
b <<
"]" << endl;
140 double Bisect(
const std::function<
double(
double)> &func,
141 const double a,
const double b,
const double eps)
143 double const c = (
a +
b) / 2;
144 double const fc = func(c);
147 cout <<
a <<
" " <<
b << endl;
149 if ( std::abs(fc) < eps || std::abs(
b-
a) < 1e-14) {
152 else if ( fc > 0.0 ) {
double Bisect(double a, double b, double eps)
double dc(const double x)