0

I want to do a numerical integration of a function f using the qtrap function defined in "Numerical recipes in C".

double qtrap(double (*func)(double), double a, double b);

As shown, it is a 1-d integration of a variable of type double.

But the function I want to integrate has an additional parameter a:

double f(double x, int a)
{
    return a + x * x;
}

Now I am looking for a way to integrate f for different values of a.

My idea up to now:

typedef double (*fctp1_t)(double);       //function pointer type for 1 arg
typedef double (*fctp2_t)(double, int);  //function pointer type for 2 args

int a = 10;
fctp1_t = f1d;
f1d = reduceArgument(f, a);

qtrap(f1d, 0, 1);

with the reduceArgument something like this:

fctp1_t reduceArgument(fctp2_t f2d, int ia)
{
    return f2d(x, ia);
}    

This code results in the error: 'x' undeclared.

Thanks for any suggestions.

Daniel
  • 69
  • 1
  • 2
  • 2
    Turn on your compiler warnings and **mind the warnings**. – pmg Mar 06 '19 at 14:44
  • Well, with -Wall I get no compiler warnings. – Daniel Mar 06 '19 at 14:52
  • 2
    You have a random variable `x` in your code. Obviously compiler doesn't know what to do with it, but neither do we. – SergeyA Mar 06 '19 at 15:00
  • x is the integration variable of the function f. I see that the compiler cannot handle the x; this is why I got stuck; this is why I am asking the question. I hope the problem is clear for a human mind. – Daniel Mar 06 '19 at 15:04
  • https://stackoverflow.com/questions/4393716/is-there-a-a-way-to-achieve-closures-in-c – Antti Haapala -- Слава Україні Mar 06 '19 at 15:54
  • Well ... in `fctp1_t = f1d;` you're trying to assign *something* (I assumed this *something* is defined) to a type. I didn't test any compiler, but assumed any half decent one would complain. – pmg Mar 06 '19 at 16:04
  • Can you *fork* `qtrap()` to something like `double qtrap2(double (*func)(double, int), double a, double b);`? – pmg Mar 06 '19 at 16:07

1 Answers1

0

C does not allow to build a function like that. You have two way to solve your problem:

  • modify qtrap so that it is able to handle a parametrized function;

  • use a global variable to pass the parameter implicitly.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143