You don't need function pointers. Use the polymorphic behavior of the evualate method to perform the integration.
Change the floats to doubles in the signature of both SingleVariableFunction and QuadtraticFunction.
IE,
Code:
#include <iostream>
class SingleVariableFunction {
public:
virtual double evaluate(double x)=0;
// print method might be nice as well
virtual ~SingleVariableFunction() { }
};
class QuadtraticFunction: public SingleVariableFunction {
public:
QuadtraticFunction(double a_, double b_, double c_) {
a = a_;
b = b_;
c = c_;
}
virtual ~QuadtraticFunction() { }
virtual double evaluate(double x) {
return x*(a*x + b) + c;
}
private:
double a, b, c;
};
double trapezoidalIntegration(SingleVariableFunction* func, double lowerLim, double upperLim, int numIterations) {
double integralSum=0.0;
double deltaX = (upperLim - lowerLim) / (double) numIterations;
double x = lowerLim;
// can be optimized... only half the calls are really needed, but the loop gets messier and I don't want to think :)
for ( int i = 0; i < numIterations; i++) {
integralSum += func->evaluate(x) + func->evaluate(x+ deltaX);
x+=deltaX;
}
integralSum = integralSum * deltaX/ 2;
return integralSum;
}
int main() {
SingleVariableFunction* func = new QuadtraticFunction(1, 0, 0);
std::cout << "Integral of 1*x^2 from 0 to 2 is " << trapezoidalIntegration(func, 0, 2, 1000) << std::endl;
delete func;
return 0;
}
Edit:
Evaluate is the hardest damned word to spell in the English langauge .