Consider the code below:
public class Analyzer {
protected Func f,fd;
public delegate double Func( double x );
public Analyzer( Func f, Func fd ) {
this.f = f;
this.fd = fd;
}
public Analyzer( Func f ) {
this.f = f;
fd = dx;
}
public Analyzer( ) { }
protected double dx( double x ) {
double h = x / 50.0;
return ((f(x + h) - f(x - h)) / (2 * h));
}
public double evaluate(double x) {
return f( x );
}
public double evaluateDerived( double x ) {
return fd( x );
}
public double solve(double x0) {
double eps = 1, x1 = f(x0), x2 = fd(x0);
do x0 = x0 - ( f( x0 ) / fd( x0 ) );
while ( f( x0 ) > eps );
return x0;
}
}
public class PolyAnalyzer : Analyzer {
private double[] coefs;
public PolyAnalyzer( params double[] coef ) {
coefs = coef;
f = poly;
fd = dx;
}
private double poly( double x ) {
double sum = 0;
for ( int i = 0 ; i < coefs.Length ; i++ ) {
sum += coefs[i] * Math.Pow(x,coefs.Length-1-i);
}
return sum;
}
}
I was trying to think of a way to send poly to the constructor Analyser(Func f), is there a way to do that here? tried something like :
public PolyAnalyzer( params double[] coef ) : base(new Func(poly)){
coefs = coef;
}
but it doesnt compile... compilation error:: An object reference is required for the nonstatic field, method, or property 'member'
Id appriciate a well explained answer, and not just how its done... :)
Func<double,double>delegate instead of defining your own. If you really want your own, give it a name other thanFuncto not confuse it with the BCL "Func" delegates...polyis a non-static member, if you make it static it will compile... but you should think this idea a little more, I don't see any sense on doing that, maybe if you describe what you need to accomplish we can help you.