I've a problem with function pointers:
I need to numerically integrate a function and want therefore pass a pointer with the function to the "integrator". The problem is, that the function to be integrated takes more then just one argument. Something like:
double f(int i, double x){ // i to switch the function, x to evaluate
if(i==1) {return sin(x);}
if(i==2) {return exp(x);}
}
double integrate(double (*function)(double), double x0, double x1){
//integrate the passed *function from x0 to x1
}
int main(){
int i=1; // i want to chose sin(x)
cout << integrate(&f, 0, 5);
}
How can i fix a argument and just pas on the remaining? Thanks for your help!
PS. after what do I have to search, what are keywords, also in perspective to object orientated programming?
this should do it...
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
typedef double (*f_ptr)(double);
double f_sin_x(double x);
double f_exp_x(double x);
f_ptr fchoice(int i);
double integrate(double x0, double x1, double(*function_to_call)(double));
const int num_steps = 100;
int main()
{
double x0(0.0), x1(1.0);
int mychoice = 2;
cout << "Integration Result: "
<< integrate(x0, x1, fchoice(mychoice)) << endl;
return 0;
}
double f_sin_x(double x) {return sin(x);}
double f_exp_x(double x) {return exp(x);}
f_ptr fchoice(int i)
{
if(i == 1) {return &f_sin_x;}
else return &f_exp_x;
}
double f(int i, double x)
{
if(i==1)
return sin(x);
else
return exp(x);
}
double integrate(double x0, double x1, double(*function_to_call)(double))
{
double dx = (x1 - x0)/num_steps;
double result = 0.0;
for (int i = 0; i < num_steps; i++)
{
result += function_to_call(x0 + dx);
}
return result;
}