-2

Anyone know how to use Boost to solve simple definite integrals?

E.g. -x^2 + 1 from -1 to 1?

I have tried reading the boost documentation, but I can't seem to figure out how to properly pass the function.

Thanks

Edit: My attempt so far

using namespace boost::math;

typename function_type; // this is probably wrong

function_type f     // and this
{
    return -x*x+1;
};

int main(int, char**)
{
    const double val  =
    integral(0.0,
    1,  
    0.001,
    f);        // my question is, what do I put in here? How do I format f.
}
storluffarn
  • 121
  • 2
  • 11
  • 1
    What have you tried already, and what are the errors you encounter? – JHBonarius Apr 07 '17 at 12:57
  • I added my what I've tried so far. Seems like function_type command is bad, because I get unknown type name. But If I make f an ordinary function, double f(double x) then the integral command gives me an error "use of undeclared identifier", which I guess it does because it expects a function_type... – storluffarn Apr 07 '17 at 16:08
  • Since I'm not a frequent stack overflow user: was not the kind of question intended for this community? Or did I phrase it poorly? I'm just wondering since it was downvoted, and I'd of course want to stick to community policy in the future. – storluffarn Apr 07 '17 at 20:07

1 Answers1

0

The first thing to observe is that the Boost library you've shown doesn't actually have a function to calculate integrals. That might have set you on the wrong track.

The library is used for multi-precision floating point operations, and one of the examples happens to be a simple approximation of integrals, per Riemann. The point of the example is that Riemann integrals are so simple that you can use them to demonstrate a fancy library.

In your case, you wouldn't even need to bother with passing a function. You can just write out the Riemann method substituting -x^2 + 1 directly.

That said, the typical C++ way to pass it as an argument would be [](double x) { return -x*x+1.0;}. That's an unnamed function or lambda. It doesn't need a name of its own, since the parameter already has a name.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • I figured there was some standard, general purpose, numerical integration solver. GSL got the gsl_integration_qags, but it seemed very c rather than c++. Googling I found boost, which seems to do the trick, but maybe it's just one of those things that are just easier and cheaper (resourcewise) to write yourself. Anyway, thanks for the answer. – storluffarn Apr 07 '17 at 20:03