shdotcom
shdotcom

Reputation: 157

"Floating point overflow" error in Delphi code

I have this source code in Delphi, why I get this error "Floating point overflow." when I run the code? and how to correct it?

The error message:

enter image description here

The code:

procedure TForm1.Button1Click(Sender: TObject);
 var n, d, i, j, maxiter , iter: Integer;
 Lower,Upper : Double;
 X, V : TArray<TArray<Double>>;
 begin
  Lower := 0;
  Upper := 0.2;
  n := 100;
  d := 55;
  SetLength(V, n, d);
  SetLength(X, n, d);
  maxiter := 2000;
  iter := 1;

  for i:= 0 n-1 do
    for j:=0 to d-1 do
     begin
      X[i][j]:= Lower + (Upper - Lower) * Random;
      V[i][j] := 0.1 * X[i][j];
     end;

 while (iter <= maxiter) do
  begin
   for  i:= 0 to n-1 do
     for j:= 0 to D-1 do
       V[i][j]:= 5 * V[i][j] + 2.0 * Random;

   iter := iter +1;
  end;

end;

Upvotes: 3

Views: 3262

Answers (1)

MBo
MBo

Reputation: 80177

Look here: V[i][j]:= 5 * V[i][j] + 2.0 * Random;

You make 2000 iterations, so your results might be as large as 7^2000 ~ 10^1690, but max value for Double type is about 10^308. So “Floating point overflow” error is exact diagnosis.

You could see V[] values about 10^307 in debug watch or immediate watch (mouse over V[]) when error occurred.

You can use 10-byte Extended type(probably not available for 64-bit compilers) to avoid overflow for these given variable values, but this is not good solution in general case.

Aside note: You did not set i index value for this code piece:

for j:=0 to d-1 do
  begin
    X[i][j]:= Lower + (Upper - Lower) * Random;
    V[i][j] := 0.1 * X[i][j];
  end;

Upvotes: 10

Related Questions