Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

calling an arbitrary function w/ arbitrary arguments

Status
Not open for further replies.

Honestmath

Technical User
Jan 8, 2003
25
US
Hello everyone,

I'm using a root finding algorithm in a function that only takes as arguments a function pointer and two variables that represent guesses at the roots of the function.

Code:
int zbrac(float (*func)(float), float *x1, float *x2)
  float f1,f2;
  f1=(*func)(*x1);
  f2=(*func)(*x2);
 // other stuff here


Problem is, I'm not sure how to pass parameters to the root finding function. For example, if I have an Nth-order polynomial, I could have loads of different coefficients, but obviously the coefficients will change from function to function.

I don't want to use global variables, but figured there was a way to modify the above root-finder to accept and then pass a variable number of parameters to the polynomial (or whatever) function.

How would I do this? Or, is there a better way?

Thanks!

Math

 
How about representing the polynomial as an array of structures, where the structure is one term of the polynomial.

Code:
#include <iostream>

#define NELEMS(x)   (sizeof(x)/sizeof(x[0]))

struct term {
    double power;
    double constant;
};

void function ( int nterms, term terms[] ) {
}

int main() {
    term foo[] = {  // 3x^2 + 4.5x + 7
        { 2.0, 3.0 },
        { 1.0, 4.5 },
        { 0.0, 7.0 },
    };
    function( NELEMS(foo), foo );
    return 0;
}

--
 
Or you could make the array a vector and put it in a polynomial class which could have Evaluate() and Derivative() methods to make your life easier.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top