an example of C++ function pointer that finds a root of a continuous function in an interval


👍 g++ root.cpp && ./a.out
3.1416
👍 cat root.cpp 
#include <iostream>
#include <cmath>
using namespace std;

double root(double (*f)(double),
            double a,
            double b,
            double epsilon) {
  double middle = (a + b) / 2;
  while (f(middle) != 0 && 
         fabs(b - a) > epsilon) {
    if (f(a) * f(middle) < 0) {
      b = middle;
    } else {
      a = middle; 
    }
    middle = (a + b) / 2;
  }
  return middle;
}

int main() {
  double r = root(sin,
                  0.1 * M_PI,
                  1.3 * M_PI,
                  0.00001);
  cout << r << endl;
}