dpatherton
06-13-2002, 10:23 AM
I am new to both the c language and NR. I am trying to use the qsimp function in a program, but I do not quit understand the function prototype: float qsimp(float (*func)(float), float a, float b). Specifically, I don't undrestand the "float (*func)(float)" part. How do I send the function( F(x) ) to the qsimp functon.
I would be grateful for any help.
Thanks,
David Atherton
William Vetterling
06-15-2002, 10:41 PM
David,
Thanks for the question. This usage is common in the Recipes, so this is a good chance to write a little about it.
There are many situations in which we want to write a Recipe that operates on a function, but the actual function will not be known until the Recipe is used in a specific application. Good examples are the integration routines. For these, we have a general algorithm for carrying out the integration, but we do not know the identity of the function until the user specifies it. We need a way to pass this function to the routine as part of calling sequence of the Recipe.
In C, this is quite easy. Let us suppose the function is F(x). The function itself is specified with some code like
double F(double x)
{
return x*x;
}
When we define a function like this, then C interpretes the name of the function (in this case, F) as being a "pointer-to-function". Effectively, the symbol F is a pointer that contains address in memory at which the code for the function can be found. In this particular case, F is a pointer to a function that takes a double argument, and returns a double. The syntax for this is
double (* F)(double)
So, when you see
double (* func)(double)
in the argument list of a Recipe, you know that you can pass the name of any function that has a double argument and returns a double. Internal to the Recipe, this function will be referred to by the name func(), but its actual name is whatever you pass as the argument.
In the particular case of qsimp(), for example, you could write
a=qsimp(F,1.0,2.0);
to integrate the function F(x) defined above, or
a=qsimp(bessj0,1.0,2.0);
to integrate the function bessj0(x) (which is a Bessel function Recipe that happens to take a double argument and return a double).