0
votes

I am designing a class (TFunctionWithDerivatives) with methods to compute numerical derivatives of an input function f: x \in R -> R.

I want to account the number of function evaluations (nfeval) employed in the construction of the derivatives using a wrapper on the input function. But the compiler doesnt like my implementation, showing this error E2010 Incompatible types 'TRealFunction' and 'Procedure'.

Here is a simplified code, where an instance of TFunctionWithDerivatives is created in Tform1.Create.

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, 
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type TRealFunction = function(const x : Single) : Single;

type TFunctionWithDerivatives = class

   objfun : TRealFunction;
   nfeval : Integer;

   constructor Create(const _objfun : TRealFunction);
   function NumFirstlDer(const x : Single) : Single;

   private
   objFunWrapper : TRealFunction;

end;

type
  TForm1 = class(TForm)
    procedure Create(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function F1(const x : Single) : Single;
begin
  RESULT := sqr(x);
end;

procedure TForm1.Create(Sender: TObject);
var FWD    : TFunctionWithDerivatives;
begin
   FWD := TFunctionWithDerivatives.create(F1);
end;


// begin methods of TFunctionWithDerivatives
     constructor TFunctionWithDerivatives.Create(const _objfun : TRealFunction);
     begin
        inherited create;
        nfeval := 0;
        objFun := _objfun;
        objFunWrapper := function(const x : Single) : Single
                         begin
                           RESULT := objFun(x);
                           Inc(nfeval);
                         end;
     end;

     function TFunctionWithDerivatives.NumFirstlDer(const x : Single) : Single;
     var h : Single;
     begin
       h:=1e-3;
       // RESULT := (objfun(x+h, Param) - objfun(x, Param)) / h ;
       RESULT := ( objFunWrapper(x+h) - objFunWrapper(x) ) / h;
     end;
// end methods of TFunctionWithDerivatives

end.

Do you know How objFunWrapper can be defined inside my class? Thanks for the help!

1

1 Answers

0
votes

You are declaring an anonymous method. To declare a type that matches, you must use the reference to syntax:

type 
  TRealFunction = reference to function(const x: Single): Single;

Documentation: Anonymous Methods in Delphi.