Skip to content

Instantly share code, notes, and snippets.

@alexshires
Last active August 29, 2015 13:57
Show Gist options
  • Save alexshires/9737529 to your computer and use it in GitHub Desktop.
Save alexshires/9737529 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <gsl/gsl_integration.h>
#include <functional>
class A
{
public :
A(const double & _z = 1.0) : z(_z) {;}
double f( double x ) { return z*x*x ; }
double test( double x, void * y ) { return f(x) ; }
friend double test2( double x, void * y ) ;
private :
const double z ;
};
//cplusplus example
struct MyPair {
double a,b;
double multiply() {return a*b;}
};
double test2( double x , void * v )
{
return ((A*)v)->f(x) ;
}
int main(int argc, char *argv[])
{
//cplusplus example
MyPair ten_two {10,2};
// binding members:
auto bound_member_fn = std::bind (&MyPair::multiply,std::placeholders::_1); // returns x.multiply()
std::cout << bound_member_fn(ten_two) << '\n'; // 20
auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a
std::cout << bound_member_data() << '\n';
A a(2) ;
double alpha = 2.0 ;
double beta = 4.0 ;
auto f1 = std::bind(&A::f, a, std::placeholders::_1);
//
std::cout << f1(alpha) << std::endl ;
//
//
auto f2 = std::bind(&A::test, a, std::placeholders::_1, std::placeholders::_2);
std::cout << f2(alpha,&beta) << std::endl ;
//
double result, error;
double expected = 2.0 * 1./3. ;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
gsl_function F;
//fails the bind
//F.function = &f2;
//F.params = &alpha;
// friend functions
F.function = &test2;
F.params = &a;
//func, min, max, error min, error max, limit, workspace, result, error
gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000,
w, &result, &error);
printf ("result = % .18f\n", result);
printf ("exact result = % .18f\n", expected);
printf ("estimated error = % .18f\n", error);
printf ("actual error = % .18f\n", result - expected);
printf ("intervals = %d\n", w->size);
gsl_integration_workspace_free (w);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment