0
 // Function as parameter of a function

#include <iostream>
#include <cmath>
#include <cassert>

using namespace std;

const double PI = 4 * atan(1.0); // tan^(-1)(1) == pi/4 then 4*(pi/4)== pi

typedef double(*FD2D)(double);

double root(FD2D, double, double); //abscissae of 2-points, 
//For the algorithm to work, the function must assume values of opposite sign in these two points, check
// at point 8

double polyn(double x) { return 3 - x*(1 + x*(27 - x * 9)); }

int main() {
double r;

cout.precision(15);

r = root(sin, 3, 4);
cout << "sin:       " << r << endl
    << "exactly:  " << PI << endl << endl;

r = root(cos, -2, -1.5);
cout << "cos:       " << r << endl
    << "exactly:  " << -PI/2 << endl << endl;

r = root(polyn, 0, 1);
cout << "polyn:       " << r << endl
    << "exactly:  " << 1./3 << endl << endl;

/* 
we look for the root of the function equivalent to function polyn
but this time defined as a lambda function 
*/
r = root([](double x) -> double { 
            return 3 - x*(1 + x*(27 - x * 9)); 
        }, 0, 1);
cout << "lambda:       " << r << endl
    << "exactly:  " << 1. / 3 << endl << endl;

return 0;
}
// Finding root of function using bisection.
// fun(a) and fun(b)  must be of opposite sign

double root(FD2D fun, double a, double b) {

static const double EPS = 1e-15; // 1×10^(-15)
double f, s, h = b - a, f1 = fun(a), f2 = fun(b);

if (f1 == 0) return a;
if (f2 == 0) return b;
assert(f1*f2<0); // 8.- macro assert from header cassert.

do {
    if ((f = fun((s = (a + b) / 2))) == 0) break;
    if (f1*f2 < 0) { 
        f2 = f; 
        b = s;
    }
    else {
        f1 = f; 
        a = s; 
    }

} while ((h /= 2) > EPS);

    return (a + b) / 2;

}

ダブルルート関数のループがどのように機能するかを誰かに説明してもらえますか? 私は 100% 理解していないようです。この二分法をオンラインで確認し、紙で試してみましたが、この例からは理解できません。前もって感謝します!

4

1 に答える 1