Skip to content

Instantly share code, notes, and snippets.

@floswald
Created October 22, 2013 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floswald/7103615 to your computer and use it in GitHub Desktop.
Save floswald/7103615 to your computer and use it in GitHub Desktop.
#include <gsl/gsl_roots.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include <iostream>
// forward definition of param struct
struct gsl_f_pars;
// Class Definition
// ================
class MyClass {
private:
gsl_f_pars *p;
public:
double obj(double x, void * pars);
double GetSolution( void );
void setPars( gsl_f_pars * xp ) { p = xp; };
double getC( void ) ;
};
// param struct
struct gsl_f_pars {
double a;
double b;
double c;
MyClass * pt_MyClass;
};
// Wrapper that points to member function
// Trick: MyClass is an element of the gsl_f_pars struct
// so we can tease the value of the objective function out
// of there.
double gslClassWrapper(double x, void * pp) {
gsl_f_pars *p = (gsl_f_pars *)pp;
return p->pt_MyClass->obj(x,p);
}
// helper function for GSL root finder
// ===================================
double find_root(gsl_root_fsolver *RootFinder, gsl_function * F, double x_lo, double x_hi) {
gsl_root_fsolver_set (RootFinder, F, x_lo , x_hi );
//std::cout << "objective function value is " << GSL_FN_EVAL(F,2.0) << std::endl;
int iter = 0,status;
int maxiter = 100;
double r;
printf ("%5s [%9s, %9s] %9s %9s\n",
"iter", "lower", "upper", "root",
"err(est)");
do {
iter++;
status = gsl_root_fsolver_iterate (RootFinder);
r = gsl_root_fsolver_root (RootFinder);
x_lo = gsl_root_fsolver_x_lower (RootFinder);
x_hi = gsl_root_fsolver_x_upper (RootFinder);
status = gsl_root_test_interval (x_lo, x_hi,0, 0.0001);
printf ("%5d [%.7f, %.7f] %.7f %.7f\n",
iter, x_lo, x_hi,
r,
x_hi - x_lo);
} while (status == GSL_CONTINUE && iter < maxiter);
return(r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment