在这个Delphi代码中,为什么更新 X 后 F_pBest 的值会发生变化?
在更新 X
之前,它应该是相同的值德尔福代码:
...........
type TMDarray = array of array of Double;
............
public
{ Public declarations }
X, pBest : TMDarray;
F_X, F_pBest : array of Double;
D, maxIter, N : Integer;
Lower, Upper : Double;
end;
.................
procedure TForm1.btn1Click(Sender: TObject);
begin
main();
end;
function TForm1.FitnessFunc(X : array of Double): Double;
var
sum : Double;
i, j : Integer;
begin
d := length(X);
sum := 0;
for j := 1 to D-1 do
sum := sum + x[j] * x[j];
Result := sum;
end;
procedure TForm1.initialize();
var
i, j : Integer;
begin
Lower := 0.0;
Upper := 10.0;
D := 3;
N := 6;
maxiter := 1;
SetLength(X, N, D);
SetLength(pBest, N, D);
SetLength(F_X, N);
SetLength(F_pBest, N);
for i:= 0 to N-1 do
begin
for j:=0 to D-1 do
begin
X[i][j]:= Lower + (Upper - Lower) * Random;
end;
F_X[i] := FitnessFunc(X[i]);
end;
pBest := X;
F_pBest := F_X;
end;
主要功能:
procedure TForm1.main();
var
iter, j, i : Integer;
begin
initialize();
iter := 0;
while (iter < maxiter) do
begin
更新X之前<=> // ======================= ===========
for i:= 0 to N-1 do
begin
StringGrid3.Cells[0,i] := FloatToStr( F_X[i] );
StringGrid3.Cells[1,i] := FloatToStr( F_pBest[i] );
end;
//===========================================================
for i:= 0 to N-1 do
begin
for j:= 0 to D-1 do
begin
X[i][j] := Random();
end;
end;
for i := 0 to N-1 do
begin
F_X[i] := FitnessFunc(X[i]); // Update X
// =======================更新后X ===========
StringGrid3.Cells[2,i] := FloatToStr( F_X[i] );
StringGrid3.Cells[3,i] := FloatToStr( F_pBest[i] );
end;
//=======================================
iter := iter + 1;
end;
end;
end.
答案 0 :(得分:5)
在初始化中,运行:F_pBest := F_X
。那个丢弃以前由F_pBest
引用的数组(当你在其上调用SetLength
时设置),而是使F_pBest
成为别名 F_X
。通过一个变量对数组的更改通过引用同一数组的任何其他变量反映出来。
动态数组的引用计数与字符串类似,但与字符串不同,它们在被索引修改时不会被隐式复制。