【发布时间】:2018-07-11 08:25:57
【问题描述】:
我正在设计一个类 (TFunctionWithDerivatives) 计算输入数值导数的方法 函数 f: x \in R -> R.
我想计算函数评估的次数 (nfeval) 使用包装器在衍生产品的构造中使用 输入函数。但是编译器不喜欢我的实现, 显示此错误 E2010 不兼容的类型 'TRealFunction' 和 'Procedure'。
这是一个简化的代码,其中一个 TFunctionWithDerivatives 的实例 在 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.
你知道如何在我的类中定义 objFunWrapper 吗? 谢谢您的帮助!
【问题讨论】:
标签: delphi